forked from hupili/sina-automator
/
wauto.py
351 lines (298 loc) · 11.2 KB
/
wauto.py
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
351
# -*- coding: utf-8 -*-
import sys
sys.path.append('snsapi')
from functools import wraps
import json
import snsapi
from snsapi.snspocket import SNSPocket
from snsapi.snslog import SNSLog as logger
from lbucket import *
try:
_wauto_conf = json.loads(open('conf/wauto.json').read())
except Exception, e:
logger.warning("Load conf error: %s. Use default", e)
_wauto_conf = {}
_wauto_conf['priority'] = {
'update': 5,
'home_timeline': 4,
'forward': 3,
'reply': 3
}
logger.debug("conf: %s", _wauto_conf)
'''
Make the invokation from Python interpreter more convenient.
Use synchronous calls.
'''
def _dummy_decorator_generator(*args, **kwargs):
def _dummy_decorator(func):
return func
return _dummy_decorator
if __name__ == '__main__':
rate_limit = _dummy_decorator_generator
def cal_bucket(upperbound, period):
'''
Do conservative calculation to generate a bucket for SinaWeibo
The limit is represented as ``x/y`` in the doc.
:param upperbound: x (in original scale)
:param period: y (in seconds)
'''
# for safety
ratio_capacity = 0.9
ratio_init = 0.3
upperbound = float(upperbound)
period = float(period)
fill_rate = upperbound / period
tokens_max = upperbound * ratio_capacity
tokens_init = upperbound * ratio_init
return LeakyBucket(tokens_max, tokens_init, fill_rate)
class WeiboAutomator(object):
'''Wrap common operations with rate limit facility
'''
# Most buckets are derived from Sina's offcial description [1].
# The additional one 'wauto_snsapi' limits SNSAPI request rate globally
# (avoid lower layer failure).
#
# Ref:
# * [1] http://open.weibo.com/wiki/Rate-limiting
SINA_BUCKETS = [
('wauto_snsapi', LeakyBucket(1, 0, 0.5)),
('ip.hour.test_auth', cal_bucket(1000, 60*60)),
('user.hour.test_auth.total', cal_bucket(150, 60*60)),
('user.hour.test_auth.update', cal_bucket(30, 60*60)),
('user.hour.test_auth.reply', cal_bucket(60, 60*60)),
('user.hour.test_auth.follow', cal_bucket(60, 60*60)),
('user.day.test_auth.follow', cal_bucket(100, 60*60*24)),
]
POLICY_GROUP = {}
POLICY_GROUP['general'] = {
'wauto_snsapi': 1,
'ip.hour.test_auth': 1,
'user.hour.test_auth.total': 1
}
POLICY_GROUP['update'] = dict(POLICY_GROUP['general'],
**{'user.hour.test_auth.update': 1})
POLICY_GROUP['reply'] = dict(POLICY_GROUP['general'],
**{'user.hour.test_auth.reply': 1})
POLICY_GROUP['follow'] = dict(POLICY_GROUP['general'],
**{'user.hour.test_auth.follow': 1, 'user.day.test_auth.follow': 1})
_log = lambda x: logger.debug('ret: %s', x)
def __init__(self):
super(WeiboAutomator, self).__init__()
self.sp = SNSPocket()
self.sp.load_config()
self.sp.auth()
# assign 'channel_name' as automator
self.weibo = self.sp['automator']
self.rlq = RateLimitQueue()
map(lambda t: self.rlq.add_bucket(t[0], t[1]), self.SINA_BUCKETS)
# This implementation of dumps and loads are too simple.
# They do not work with some callback functions.
# I switch to 'dill'
#def dumps(self):
# r = copy.deepcopy(self.rlq)
# for t in r._tasks:
# # First arg should be 'self' if do not operate our RLQ directly.
# t.args = list(t.args)
# t.args.pop(0)
# t.func = marshal.dumps(t.func.func_code)
# t.callback = marshal.dumps(t.callback.func_code)
# return pickle.dumps(r)
#def loads(self, s):
# r = pickle.loads(s)
# for t in r._tasks:
# t.args.insert(0, self)
# t.args = tuple(t.args)
# code_func = marshal.loads(t.func)
# t.func = types.FunctionType(code_func, globals())
# code_callback = marshal.loads(t.callback)
# t.callback = types.FunctionType(code_callback, globals())
# self.rlq = r
#Original 'loads' 2
# #self.rlq._buckets = r._buckets
# #for t in r._tasks:
# # code = marshal.loads(t.callback)
# # t.callback = types.FunctionType(code, globals())
# # t.args.insert(0, self)
# # t.args = tuple(t.args)
# # t.kwargs['callback'] = t.callback
# # f = getattr(WeiboAutomator, t.func)
# # # Execute the wrapped class method again to insert task
# # f(*t.args, **t.kwargs)
def run(self):
return self.rlq.run()
def clear_tasks(self):
return self.rlq.clear_tasks()
def _tounicode(self, text):
if isinstance(text, unicode):
return text
else:
return text.decode('utf-8')
def get_uid(self):
if hasattr(self, '_uid'):
return self._uid
else:
ret = self.weibo.weibo_request('account/get_uid',
'GET',
{})
return ret['uid']
uid = property(get_uid)
def rate_limit_status(self):
ret = self.weibo.weibo_request('account/rate_limit_status',
'GET',
{})
return ret
@rate_limit(buckets=POLICY_GROUP['follow'], callback=_log)
def follow(self, uid):
ret = self.weibo.weibo_request('friendships/create',
'POST',
{'uid': uid})
return ret
@rate_limit(buckets=POLICY_GROUP['follow'], callback=_log)
def follow_by_name(self, screen_name):
ret = self.weibo.weibo_request('friendships/create',
'POST',
{'screen_name': screen_name})
return ret
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log,
priority=_wauto_conf['priority']['home_timeline'])
def home_timeline(self, count=20):
return self.weibo.home_timeline(count)
@rate_limit(buckets=POLICY_GROUP['update'], callback=_log,
priority=_wauto_conf['priority']['update'])
def update(self, text):
return self.weibo.update(self._tounicode(text))
@rate_limit(buckets=POLICY_GROUP['reply'], callback=_log,
priority=_wauto_conf['priority']['reply'])
def reply(self, status, text):
if isinstance(status, snsapi.snstype.Message):
statusID = status.ID
else:
statusID = status
return self.weibo.reply(statusID, self._tounicode(text))
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log,
priority=_wauto_conf['priority']['forward'])
def forward(self, status, text):
return self.weibo.forward(status, self._tounicode(text))
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log)
def show(self, uid = None, screen_name = None):
params = {}
if not uid is None:
params['uid'] = uid
elif not screen_name is None:
params['screen_name'] = screen_name
else:
params['uid'] = self.uid
ret = self.weibo.weibo_request('users/show',
'GET',
params)
return ret
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log)
def domain_show(self, url):
'''Lookup user by personal url.
We will match and remove common weibo prefix.
:param url:
e.g. 'http://weibo.com/xiena' --> url='xiena'
'''
import re
pattern = re.compile('^http:\/\/.*weibo.com\/')
url = re.sub(pattern, '', url)
ret = self.weibo.weibo_request('users/domain_show',
'GET',
{'domain': url})
return ret
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log)
def get_friends(self, uid=None, screen_name=None, count=200, cursor=None):
params = {'count': count}
if not uid is None:
params['uid'] = uid
elif not screen_name is None:
params['screen_name'] = screen_name
else:
params['uid'] = self.uid
if not cursor is None:
params['cursor'] = cursor
ret = self.weibo.weibo_request('friendships/friends',
'GET',
params)
return ret
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log)
def get_friends_ids(self, uid=None, screen_name=None, count=5000, cursor=None):
params = {'count': count}
if not uid is None:
params['uid'] = uid
elif not screen_name is None:
params['screen_name'] = screen_name
else:
params['uid'] = self.uid
if not cursor is None:
params['cursor'] = cursor
ret = self.weibo.weibo_request('friendships/friends/ids',
'GET',
params)
return ret
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log)
def get_followers(self, uid=None, screen_name=None, count=200, cursor=None):
params = {'count': count}
if not uid is None:
params['uid'] = uid
elif not screen_name is None:
params['screen_name'] = screen_name
else:
params['uid'] = self.uid
if not cursor is None:
params['cursor'] = cursor
ret = self.weibo.weibo_request('friendships/followers',
'GET',
params)
return ret
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log)
def get_followers_ids(self, uid=None, screen_name=None, count=5000, cursor=None):
params = {'count': count}
if not uid is None:
params['uid'] = uid
elif not screen_name is None:
params['screen_name'] = screen_name
else:
params['uid'] = self.uid
if not cursor is None:
params['cursor'] = cursor
ret = self.weibo.weibo_request('friendships/followers/ids',
'GET',
params)
return ret
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log)
def get_followers_active(self, uid=None, screen_name=None, count=200, cursor=None):
params = {'count': count}
if not uid is None:
params['uid'] = uid
elif not screen_name is None:
params['screen_name'] = screen_name
else:
params['uid'] = self.uid
if not cursor is None:
params['cursor'] = cursor
ret = self.weibo.weibo_request('friendships/followers/active',
'GET',
params)
return ret
# This Api is only for advanced app permission
@rate_limit(buckets=POLICY_GROUP['general'], callback=_log)
def search_topics(self, q, count=50, page=None):
params = {'count': count}
if not page is None:
params['page'] = page
ret = self.weibo.weibo_request('search/topics',
'GET',
params)
return ret
if __name__ == '__main__':
wa = WeiboAutomator()
# Previous tests to check the rate limit rules.
#if __name__ == '__main__':
# from time import sleep
# import pprint
# pp = pprint.PrettyPrinter(indent=4)
# wa = WeiboAutomator()
# pp.pprint(wa.rlq.get_buckets_info())
# sleep(0.6)
# pp.pprint(wa.rlq.get_buckets_info())