1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
|
from twisted.internet import reactor
from pprint import pformat
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.http_headers import Headers
from twisted.internet.defer import succeed
#from twisted.python import log
from twisted.internet import task
from twisted.web.client import getPage
from zope.interface import implements
import sys
import urllib
import logging
#__all__ = ['SunshineGaduAPI']
logger = logging.getLogger('Sunshine.GaduAPI')
try:
proper_twisted = True
from twisted.web.iweb import IBodyProducer
from twisted.web.client import Agent
except ImportError:
logger.info("Twisted version is too old.")
proper_twisted = False
try:
import oauth.oauth as oauth
test_oauth = oauth.OAuthSignatureMethod_HMAC_SHA1()
oauth_loaded = True
except:
logger.info("oAuth module can't be loaded")
oauth_loaded = False
import json
import mimetools
import mimetypes
import time
REQUEST_TOKEN_URL = 'http://api.gadu-gadu.pl/request_token'
ACCESS_TOKEN_URL = 'http://api.gadu-gadu.pl/access_token'
AUTHORIZE_TOKEN_URL = 'http://login.gadu-gadu.pl/authorize'
PUT_AVATAR_URL = 'http://api.gadu-gadu.pl/avatars/%s/0.xml'
GET_INFO_URL = 'http://api.gadu-gadu.pl/users/%s.json'
def check_requirements():
if proper_twisted == True and oauth_loaded == True:
return True
else:
return False
logger.info("Requirements related with Gadu-Gadu oAuth API support not fullfilled. You need twisted-core, twisted-web in version 9.0.0 or greater and python-oauth.")
class StringProducer(object):
if check_requirements() == True:
implements(IBodyProducer)
def __init__(self, body):
self.body = body
self.length = len(body)
def startProducing(self, consumer):
consumer.write(self.body)
return succeed(None)
def pauseProducing(self):
pass
def stopProducing(self):
pass
class BeginningPrinter(Protocol):
def __init__(self, finished):
self.finished = finished
self.remaining = 1024 * 10
self.body = ''
def dataReceived(self, bytes):
if self.remaining:
display = bytes[:self.remaining]
self.body = self.body+display
self.remaining -= len(display)
def connectionLost(self, reason):
#print 'Finished receiving body:', reason.getErrorMessage()
self.finished.callback(self.body)
class GG_Oauth(object):
def __init__(self, uin, password):
self.uin = uin
self.password = password
self.timestamp = 0
self.expire_token = 0
self.access_token = None
self.__loopingcall = None
self.agent = Agent(reactor)
self.consumer = oauth.OAuthConsumer(self.uin, self.password)
self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
#
# REQUESTING TOKEN
#
def requestToken(self):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, http_method='POST', http_url=REQUEST_TOKEN_URL) # create an oauth request
oauth_request.sign_request(self._signature_method, self.consumer, None) # the request knows how to generate a signature
auth_header = oauth_request.to_header()
headers = {}
headers['Authorization'] = [auth_header['Authorization']]
headers['Accept'] = ['application/json']
headers['User-Agent'] = ['Gadu-Gadu Client, build 10,1,1,11119']
headers['Host'] = ['api.gadu-gadu.pl']
headers['Content-Length'] = [0]
headers = Headers(headers)
url = REQUEST_TOKEN_URL
d = self.agent.request(
'POST',
REQUEST_TOKEN_URL,
headers,
None)
d.addCallback(self.cbRequestToken)
d.addErrback(self.cbShutdown)
def cbRequestToken(self, response):
finished = Deferred()
response.deliverBody(BeginningPrinter(finished))
finished.addCallback(self.cbRequestTokenSuccess)
finished.addErrback(self.cbShutdown)
return finished
def cbRequestTokenSuccess(self, result):
content = json.loads(result)['result']
oauth_token = oauth.OAuthToken(content['oauth_token'], content['oauth_token_secret'])
postvars = 'callback_url=http://www.mojageneracja.pl&request_token=%s&uin=%s&password=%s' % (oauth_token.key, self.uin, self.password)
headers = {}
headers['User-Agent'] = ['Gadu-Gadu Client, build 10,1,1,11119']
headers['Accept'] = ['*/*']
headers['Content-Type'] = ['application/x-www-form-urlencoded']
headers = Headers(headers)
body = StringProducer(str(postvars))
d = self.agent.request(
'POST',
AUTHORIZE_TOKEN_URL,
headers,
body)
d.addCallback(self.cbTokenAuthorised, oauth_token)
d.addErrback(self.cbShutdown)
def cbTokenAuthorised(self, result, oauth_token):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=oauth_token, http_method='POST', http_url=ACCESS_TOKEN_URL) # create an oauth request
oauth_request.sign_request(self._signature_method, self.consumer, oauth_token) # the request knows how to generate a signature
auth_header = oauth_request.to_header()
headers = {}
headers['Authorization'] = [auth_header['Authorization']]
headers['User-Agent'] = ['Gadu-Gadu Client, build 10,1,1,11119']
headers['Accept'] = ['application/json']
headers['Content-Length'] = [0]
headers = Headers(headers)
d = self.agent.request(
'POST',
ACCESS_TOKEN_URL,
headers,
None)
d.addCallback(self.requestAccessToken, oauth_token)
d.addErrback(self.cbShutdown)
def requestAccessToken(self, response, oauth_token):
finished = Deferred()
response.deliverBody(BeginningPrinter(finished))
finished.addCallback(self.accessTokenReceived, oauth_token)
finished.addErrback(self.cbShutdown)
return finished
def accessTokenReceived(self, result, oauth_token):
content = json.loads(result)['result']
self.access_token = oauth.OAuthToken(content['oauth_token'], content['oauth_token_secret'])
self.expire_token = time.time()+36000
def getContentType(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
def getExtByType(self, mime):
return mimetypes.guess_extension(mime)
def encodeMultipart(self, fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
boundary = mimetools.choose_boundary()
crlf = '\r\n'
l = []
for (k, v) in fields:
l.append('--' + boundary)
l.append('Content-Disposition: form-data; name="%s"' % k)
l.append('')
l.append(v)
for (k, f, v) in files:
l.append('--' + boundary)
l.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (k, f))
l.append('Content-Type: %s' % self.getContentType(f))
l.append('')
l.append(v)
l.append('--' + boundary + '--')
l.append('')
body = crlf.join(l)
return boundary, body
def putAvatar(self, data, ext):
url = str(PUT_AVATAR_URL % self.uin)
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=self.access_token, http_method='PUT', http_url=url) # create an oauth request
oauth_request.sign_request(self._signature_method, self.consumer, self.access_token) # the request knows how to generate a signature
auth_header = oauth_request.to_header()
filename = str(self.uin)+ext
(boundary, body) = self.encodeMultipart(fields=(('_method', 'PUT'),), files=(('avatar', filename, data),))
body = StringProducer(str(body))
headers = {}
#headers['Connection'] = ['keep-alive']
headers['Authorization'] = [auth_header['Authorization']]
headers['User-Agent'] = ['Gadu-Gadu Client, build 10,1,1,11119']
headers['Accept'] = ['*/*']
headers['Content-Type'] = ['multipart/form-data; boundary=%s' % boundary]
headers = Headers(headers)
d = self.agent.request(
'POST',
url,
headers,
body)
d.addCallback(self.putAvatarSuccess)
d.addErrback(self.cbShutdown)
def putAvatarSuccess(self, response):
logger.info("New avatar should be uploaded now.")
def fetchUserInfo(self, uin):
url = str(GET_INFO_URL % uin)
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=self.access_token, http_method='GET', http_url=url) # create an oauth request
oauth_request.sign_request(self._signature_method, self.consumer, self.access_token) # the request knows how to generate a signature
auth_header = oauth_request.to_header()
headers = {}
#headers['Connection'] = ['keep-alive']
headers['Authorization'] = [auth_header['Authorization']]
headers['User-Agent'] = ['Gadu-Gadu Client, build 10,1,1,11119']
headers['Accept'] = ['*/*']
headers = Headers(headers)
d = self.agent.request(
'GET',
url,
headers,
None)
d.addCallback(self.fetchUserInfoSuccess)
d.addErrback(self.cbShutdown)
def fetchUserInfoSuccess(self, response):
finished = Deferred()
response.deliverBody(BeginningPrinter(finished))
finished.addCallback(self.onUserInfoRecv)
finished.addErrback(self.cbShutdown)
return finished
def onUserInfoRecv(self, result):
content = json.loads(result)['result']
self.onUserInfo(content)
def onUserInfo(self, result):
pass
def cbShutdown(self, reason):
logger.info("Something went wrong.")
print 'cbShutdown: ', reason
def checkTokenForAvatar(self, data, ext):
#print 'checkTokenForAvatar'
if int(time.time()) <= self.expire_token and self.access_token != None:
self.putAvatar(data, ext)
self.__loopingcall.stop()
def checkTokenForUserInfo(self, uin):
if int(time.time()) <= self.expire_token and self.access_token != None:
self.fetchUserInfo(uin)
self.__loopingcall.stop()
def getToken(self):
self.requestToken()
def uploadAvatar(self, data, ext):
if int(time.time()) <= self.expire_token and self.access_token != None:
self.putAvatar(data, ext)
else:
self.requestToken()
self.__loopingcall = task.LoopingCall(self.checkTokenForAvatar, data, ext)
self.__loopingcall.start(1.0)
def getUserInfo(self, uin):
if int(time.time()) <= self.expire_token and self.access_token != None:
self.fetchUserInfo(uin)
else:
self.requestToken()
self.__loopingcall = task.LoopingCall(self.checkTokenForUserInfo, uin)
self.__loopingcall.start(1.0)
#if check_requirements() == True:
# gg = GG_Oauth(4634020, 'xxxxxx')
#data = open('avatar.png', 'r').read()
#ext = mimetypes.guess_extension(mimetypes.guess_type('avatar.png')[0])
#gg.uploadAvatar(data, ext)
# gg.getUserInfo('5120225')
#else:
# print 'GG_oAuth_API: Requirements related with Gadu-Gadu oAuth API support not fullfilled. You need twisted-core, twisted-web in version 9.0.0 or greater and python-oauth.'
#log.startLogging(sys.stdout)
#reactor.run()
|