This repository has been archived by the owner on Mar 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
handlers.py
399 lines (351 loc) · 13.7 KB
/
handlers.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import logging
from pprint import pprint, pformat
import tornado.auth
import tornado.web
from tornado.web import HTTPError
from tornado_utils.routes import route
#from tornado_utils.decorators import login_required
from tornado.escape import json_decode, json_encode
#import settings
class BaseHandler(tornado.web.RequestHandler):
def write_json(self, struct, javascript=False):
self.set_header("Content-Type", "application/json; charset=UTF-8")
self.write(tornado.escape.json_encode(struct))
def write_jsonp(self, callback, struct):
self.set_header("Content-Type", "text/javascript; charset=UTF-8")
self.write('%s(%s)' % (callback, tornado.escape.json_encode(struct)))
def get_current_user(self):
username = self.get_secure_cookie('user')
if username:
return unicode(username, 'utf8')
@property
def redis(self):
return self.application.redis
@route('/')
class HomeHandler(BaseHandler):
def get(self):
options = {
'page_title': 'Too Cool for Me?',
}
user = self.get_current_user()
if user:
# check that we still have the access token
key = 'access_tokens:%s' % user
if not self.redis.get(key):
user = None
if user:
url = '/static/bookmarklet.js'
url = '%s://%s%s' % (self.request.protocol,
self.request.host,
url)
options['full_bookmarklet_url'] = url
options['user'] = user
self.render('home.html', **options)
@route('/json', name='json')
@route('/jsonp', name='jsonp')
class FollowsHandler(BaseHandler, tornado.auth.TwitterMixin):
@tornado.web.asynchronous
def get(self):
jsonp = 'jsonp' in self.request.path
if (self.get_argument('username', None) and
not self.get_argument('usernames', None)):
usernames = self.get_arguments('username')
else:
usernames = self.get_arguments('usernames')
if isinstance(usernames, basestring):
usernames = [usernames]
elif (isinstance(usernames, list)
and len(usernames) == 1
and ',' in usernames[0]):
usernames = [x.strip() for x in
usernames[0].split(',')
if x.strip()]
# make sure it's a unique list
usernames = set(usernames)
if jsonp:
self.jsonp = self.get_argument('callback', 'callback')
else:
self.jsonp = False
if not usernames:
msg = {'ERROR': 'No usernames asked for'}
if jsonp:
self.write_jsonp(self.jsonp, msg)
else:
self.write_json(msg)
self.finish()
return
#print "USERNAMES"
#print usernames
# All of this is commented out until I can figure out why cookie
# headers aren't sent from bookmarklet's AJAX code
this_username = self.get_argument('you', self.get_current_user())
# this_username = self.get_current_user()
# #print "THIS_USERNAME", repr(this_username)
# you = self.get_argument('you', None) # optional
# #print "YOU", repr(you)
# if you:
# print "THIS_USERNAME", repr(this_username)
# if this_username != you:
# self.write_json({
# 'ERROR': "Logged in on %s as '%s'" % this_username
# })
# return
# if you in usernames:
# usernames.remove(you)
access_token = self.redis.get('access_tokens:%s' % this_username)
if access_token:
access_token = json_decode(access_token)
if not access_token:
msg = {'ERROR': ('Not authorized. Go to http://%s and sign in' %
self.request.host)}
if self.jsonp:
self.write_jsonp(self.jsonp, msg)
else:
self.write_json(msg)
self.finish()
return
#print "USERNAMES"
#pprint(usernames)
#print
results = {}
# pick some up already from the cache
_drop = set()
for username in usernames:
key = 'follows:%s:%s' % (this_username, username)
value = self.redis.get(key)
if value is not None:
#print repr(username)
#print "\t", repr(value)
results[username] = bool(int(value))
_drop.add(username)
usernames -= _drop
if len(usernames) == 1:
username = list(usernames)[0]
# See https://dev.twitter.com/docs/api/1/get/friendships/show
self.twitter_request(
"/friendships/show",
source_screen_name=this_username,
target_screen_name=username,
access_token=access_token,
callback=self.async_callback(
lambda x: self._on_show(x, this_username, username, results)
),
)
elif usernames:
# See https://dev.twitter.com/docs/api/1/get/friendships/lookup
self.twitter_request(
"/friendships/lookup",
screen_name=','.join(usernames),
access_token=access_token,
callback=self.async_callback(
lambda x: self._on_lookup(x, this_username, results)
),
)
else:
# all usernames were lookup'able by cache
if self.jsonp:
self.write_jsonp(self.jsonp, results)
else:
self.write_json(results)
#print "RETURNING"
#pprint(results)
self.finish()
def _on_lookup(self, result, this_username, data):
#print "RESULT"
#pprint(result)
for each in result:
if 'followed_by' in each['connections']:
data[each['screen_name']] = True
else:
data[each['screen_name']] = False
key = 'follows:%s:%s' % (this_username, each['screen_name'])
self.redis.setex(key, int(data[each['screen_name']]), 60)
if self.jsonp:
self.write_jsonp(self.jsonp, data)
else:
self.write_json(data)
#print "RETURNING"
#pprint(data)
self.finish()
def _on_show(self, result, this_username, username, data):
#print "RESULT"
#pprint(result)
target_follows = None
if result and 'relationship' in result:
target_follows = result['relationship']['target']['following']
key = 'follows:%s:%s' % (this_username, username)
if target_follows is not None:
self.redis.setex(key, int(bool(target_follows)), 60)
data[username] = target_follows
if self.jsonp:
self.write_jsonp(self.jsonp, data)
else:
self.write_json(data)
#print "RETURNING"
#pprint(data)
self.finish()
class BaseAuthHandler(BaseHandler):
def get_next_url(self):
return '/'
@route('/auth/twitter/', name='auth_twitter')
class TwitterAuthHandler(BaseAuthHandler, tornado.auth.TwitterMixin):
@tornado.web.asynchronous
def get(self):
if self.get_argument("oauth_token", None):
self.get_authenticated_user(self.async_callback(self._on_auth))
return
self.authenticate_redirect()
def _on_auth(self, user_struct):
if not user_struct:
raise HTTPError(500, "Twitter auth failed")
username = user_struct.get('username')
self.redis.rpush('usernames', username)
#first_name = user_struct.get('first_name', user_struct.get('name'))
#last_name = user_struct.get('last_name')
#email = user_struct.get('email')
access_token = user_struct['access_token']
assert access_token
self.redis.set('access_tokens:%s' % username, json_encode(access_token))
#profile_image_url = user_struct.get('profile_image_url', None)
self.set_secure_cookie("user",
username.encode('utf8'),
expires_days=30, path='/')
self.redirect('/')
@route(r'/auth/logout/', name='logout')
class AuthLogoutHandler(BaseAuthHandler):
def get(self):
self.clear_all_cookies()
self.redirect(self.get_next_url())
@route(r'/test', name='test')
class TestServiceHandler(BaseHandler):
def get(self):
options = {}
user = self.get_current_user()
if not user:
self.redirect('/auth/twitter/')
return
options['user'] = user
options['page_title'] = "Test the service"
self.render('test.html', **options)
@route('/following/(\w+)', name='following')
class FollowingHandler(BaseHandler, tornado.auth.TwitterMixin):
@tornado.web.asynchronous
def get(self, username):
options = {'username': username}
this_username = self.get_current_user()
if not this_username:
self.redirect(self.reverse_url('auth_twitter'))
return
options['this_username'] = this_username
options['follows'] = None
key = 'follows:%s:%s' % (this_username, username)
value = self.redis.get(key)
if value is None:
access_token = self.redis.get('access_tokens:%s' % this_username)
if not access_token:
self.write('ERROR: Not authorized with Twitter for %s' %
self.request.host)
self.finish()
return
access_token = json_decode(access_token)
self.twitter_request(
"/friendships/show",
source_screen_name=this_username,
target_screen_name=username,
access_token=access_token,
callback=self.async_callback(
lambda x: self._on_friendship(x, key, options)
),
)
else:
self._on_friendship(bool(int(value)), None, options)
#options['follows'] = bool(int(value))
#self._fetch_info(options)
def _on_friendship(self, result, key, options):
#print "(_on_friendship)RESULT"
#pprint(result)
if isinstance(result, bool):
value = result
else:
logging.info("Result (%r): %r" % (key, result))
if result and 'relationship' in result:
value = result['relationship']['target']['following']
if key and value is not None:
self.redis.setex(key, int(bool(value)), 60)
options['follows'] = value
self._fetch_info(options)
def _fetch_info(self, options, username=None):
if username is None:
username = options['username']
key = 'info:%s' % username
value = self.redis.get(key)
if value is None:
access_token = self.redis.get('access_tokens:%s' %
options['this_username'])
access_token = json_decode(access_token)
self.twitter_request(
"/users/show",
screen_name=username,
access_token=access_token,
callback=self.async_callback(
lambda x: self._on_info(x, key, options)
),
)
else:
self._on_info(json_decode(value), None, options)
#value = json_decode(value)
#options['info'] = value
#pprint(value)
#self._render(options)
def _on_info(self, result, key, options):
if isinstance(result, basestring):
result = json_decode(result)
#print "(_on_info)RESULT"
#pprint(result)
if key:
assert result
self.redis.setex(key, json_encode(result), 60 * 60)
if 'info' not in options:
options['info'] = {options['username']: result}
self._fetch_info(options, username=options['this_username'])
else:
options['info'][options['this_username']] = result
self._render(options)
def _render(self, options):
if options['follows']:
page_title = '%s follows me'
else:
page_title = '%s is too cool for me'
options['page_title'] = page_title % options['username']
#options['info_print'] = pformat(options['info'])
#_followers = options['info']['followers_count']
#_following = options['info']['friends_count']
#options['ratios'][options['username']] =
self._set_ratio(options, 'username')
self._set_ratio(options, 'this_username')
self.render('following.html', **options)
def _set_ratio(self, options, key):
value = options[key]
followers = options['info'][value]['followers_count']
following = options['info'][value]['friends_count']
ratio = 1.0 * followers / following
options['info'][value]['ratio'] = '%.1f' % ratio
self.redis.sadd('allusernames', value)
key = 'ratios'
self.redis.zadd(key, **{value: ratio})
_usernames = self.redis.zrange(key, 0, -1, withscores=False)
_usernames.reverse()
options['info'][value]['rank'] = _usernames.index(value)
@route(r'/coolest')
class CoolestHandler(BaseHandler):
def get(self):
options = {}
user = self.get_current_user()
key = 'ratios'
ratios = self.redis.zrange(key, 0, -1, withscores=True)
ratios.reverse()
options['ratios'] = ratios
options['user'] = user
options['page_title'] = \
"Coolest in the world! ...on Twitter ...using this site"
self.render('coolest.html', **options)