-
Notifications
You must be signed in to change notification settings - Fork 1
/
sample_app.py
502 lines (363 loc) · 15.4 KB
/
sample_app.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
#'DIRS': [os.path.join(BASE_DIR, 'templates')],
import sys
from sys import argv
import bottle
import beaker.middleware
import urllib
import cStringIO
from bottle import get, route, redirect, post, run, request, hook, static_file, template
from bottle.ext import sqlite
from instagram import client, subscriptions
#bottle.debug(True)
session_opts = {
'session.type': 'file',
'session.data_dir': './session/',
'session.auto': True,
}
app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
#plugin = sqlite.Plugin(dbfile='/Users/mikecap/Sites/hackbushwick2014/test.db')
#app.install(plugin)
#@app.route('/show/:item')
#def show(item, db):
# row = db.execute('SELECT * from items where name=?', item).fetchone()
# if row:
# return template('showitem', page=row)
# return HTTPError(404, "Page not found")
local_host = os.environ.get("LOCALHOST")
local_port = os.environ.get("PORT", 5000)
CONFIG = {
'client_id': os.environ.get('INSTAGRAM_CLIENT_ID'),
'client_secret': os.environ.get('INSTAGRAM_CLIENT_SECRET'),
'redirect_uri': 'http://' + local_host + '/oauth_callback'
}
bw_latitude = "40.6962141"
bw_longitude = "-73.9178114"
unauthenticated_api = client.InstagramAPI(**CONFIG)
def img2txt(imgname):
from PIL import Image
clr = False
maxLen = 100.0 # default maxlen: 100px
fontSize = 7
try:
img = Image.open(imgname)
except IOError:
exit("File not found: " + imgname)
# resize to: the max of the img is maxLen
width, height = img.size
rate = maxLen / max(width, height)
width = int(rate * width) # cast to int
height = int(rate * height)
img = img.resize((width, height))
# get pixels
pixel = img.load()
# grayscale
color = "MNHQ$OC?7>!:-;. "
string = ""
# first go through the height, otherwise will rotate
for h in xrange(height):
for w in xrange(width):
rgb = pixel[w, h]
if (clr):
string += "<span style=\"color:rgb" + str(rgb) + ";\">▇</span>"
else:
string += "<span style=\"font-family: 'Courier New', monospace; display:inline-block;\">" + color[int(sum(rgb) / 3.0 / 256.0 * 16)] + "</span>"
string += "\n"
# wrap with html
template = """<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href='http://fonts.googleapis.com/css?family=Cousine' rel='stylesheet' type='text/css'>
<style type="text/css" media="all">
body {background: black; color: white;}
h1, h2, li {font: 12px monospace;}
a, a:visited, a:hover {color:green;}
pre {
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
font-family: 'Cousine', 'Consolas'!important;
line-height: 1.0;
font-size: %dpx;
}
body {background: black; color white;}
</style>
</head>
<body><div id="container">
<pre>%s</pre></div>
</body>
</html>
"""
html = template % (fontSize, string)
return html
@hook('before_request')
def setup_request():
request.session = request.environ['beaker.session']
def process_tag_update(update):
print(update)
reactor = subscriptions.SubscriptionsReactor()
reactor.register_callback(subscriptions.SubscriptionType.TAG, process_tag_update)
@get('/<filename:re:.*\.js>')
def javascripts(filename):
return static_file(filename, root='static/js')
@get('/<filename:re:.*\.css>')
def stylesheets(filename):
return static_file(filename, root='static/css')
@get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
return static_file(filename, root='static/img')
@get('/<filename:re:.*\.(eot|ttf|woff|svg)>')
def fonts(filename):
return static_file(filename, root='static/fonts')
@route('/static/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root='./static/')
@route('/')
def home():
try:
url = unauthenticated_api.get_authorize_url(scope=["likes","comments"])
return template("index")
except Exception as e:
print(e)
@route('/instagram')
def instagram():
try:
url = unauthenticated_api.get_authorize_url(scope=["likes","comments"])
return '<body style="background: black; color: white"><h1 style="font: 25px monospace;"><a href="%s">[Co]nnect with Instant-GRAM</a></h1>' % url
except Exception as e:
print(e)
def get_nav():
nav_menu = ("<body style='background: black; color: white'><h1 style='font: 25px monospace;'>Bushwick Internet '85</h1>"
"<ol>"
# "<li><a href='/recent'>User Recent Media</a> Calls user_recent_media - Get a list of a user's most recent media</li>"
# "<li><a href='/user_media_feed'>User Media Feed</a> Calls user_media_feed - Get the currently authenticated user's media feed uses pagination</li>"
# "<li><a href='/location_recent_media'>Location Recent Media</a> Calls location_recent_media - Get a list of recent media at a given location, in this case, Bushwick</li>"
"<li style='font: 25px monospace;'><a href='/media_search'>Lat / Long [S]earch</a></li>"
# "<li><a href='/media_popular'>Popular Media</a> Calls media_popular - Get a list of the overall most popular media items</li>"
# "<li><a href='/user_search'>User Search</a> Calls user_search - Search for users on instagram, by name or username</li>"
# "<li><a href='/user_follows'>User Follows</a> Get the followers of @instagram uses pagination</li>"
# "<li><a href='/location_search'>Location Search</a> Calls location_search - Search for a location by lat/lng</li>"
"<li style='font: 25px monospace;'><a href='/tag_search'>[B]ushwick Tag Search</a></li>"
"</ol>")
return nav_menu
@route('/oauth_callback')
def on_callback():
code = request.GET.get("code")
if not code:
return 'Missing code'
try:
access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code)
if not access_token:
return 'Could not get access token'
api = client.InstagramAPI(access_token=access_token)
request.session['access_token'] = access_token
print ("access token=" + access_token)
except Exception as e:
print(e)
return get_nav()
@route('/recent')
def on_recent():
content = "<h2>User Recent Media</h2>"
access_token = request.session['access_token']
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
recent_media, next = api.user_recent_media()
photos = []
for media in recent_media:
photos.append('<div style="float:left;">')
if(media.type == 'video'):
photos.append('<video controls width height="150"><source type="video/mp4" src="%s"/></video>' % (media.get_standard_resolution_url()))
else:
photos.append('<img src="%s"/>' % (media.get_low_resolution_url()))
print(media)
photos.append("<br/> <a href='/media_like/%s'>Like</a> <a href='/media_unlike/%s'>Un-Like</a> LikesCount=%s</div>" % (media.id, media.id, media.like_count))
content += ''.join(photos)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(), content, api.x_ratelimit_remaining, api.x_ratelimit)
@route('/media_like/<id>')
def media_like(id):
access_token = request.session['access_token']
api = client.InstagramAPI(access_token=access_token)
api.like_media(media_id=id)
redirect("/recent")
@route('/media_unlike/<id>')
def media_unlike(id):
access_token = request.session['access_token']
api = client.InstagramAPI(access_token=access_token)
api.unlike_media(media_id=id)
redirect("/recent")
@route('/user_media_feed')
def on_user_media_feed():
access_token = request.session['access_token']
content = "<h2>User Media Feed</h2>"
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
media_feed, next = api.user_media_feed()
photos = []
for media in media_feed:
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
counter = 1
while next and counter < 3:
media_feed, next = api.user_media_feed(with_next_url=next)
for media in media_feed:
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
counter += 1
content += ''.join(photos)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(), content, api.x_ratelimit_remaining, api.x_ratelimit)
@route('/location_recent_media')
def location_recent_media():
access_token = request.session['access_token']
content = "<h2>Location Recent Media</h2>"
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
recent_media, next = api.location_recent_media(location_id=514276)
photos = []
for media in recent_media:
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
content += ''.join(photos)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(), content, api.x_ratelimit_remaining, api.x_ratelimit)
@route('/media_search')
def media_search():
access_token = request.session['access_token']
content = "<h2>Media Search</h2>"
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
media_search = api.media_search(lat=bw_latitude, lng=bw_longitude, distance=1000)
ascii_photos = []
for media in media_search:
# Fetch the actual image
if (media.get_standard_resolution_url().endswith(".mp4")):
continue
else:
image_file = cStringIO.StringIO(urllib.urlopen(media.get_standard_resolution_url()).read())
ascii_photos.append(img2txt(image_file))
content += '<br/>'.join(ascii_photos)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
@route('/media_popular')
def media_popular():
access_token = request.session['access_token']
content = "<h2>Popular Media</h2>"
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
media_search = api.media_popular()
photos = []
for media in media_search:
photos.append('<img src="%s"/>' % media.get_standard_resolution_url())
content += ''.join(photos)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(), content, api.x_ratelimit_remaining, api.x_ratelimit)
@route('/user_search')
def user_search():
access_token = request.session['access_token']
content = "<h2>User Search</h2>"
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
user_search = api.user_search(q="Instagram")
users = []
for user in user_search:
users.append('<li><img src="%s">%s</li>' % (user.profile_picture, user.username))
content += ''.join(users)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(), content, api.x_ratelimit_remaining, api.x_ratelimit)
@route('/user_follows')
def user_follows():
access_token = request.session['access_token']
content = "<h2>User Follows</h2>"
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
# 25025320 is http://instagram.com/instagram
user_follows, next = api.user_follows('25025320')
users = []
for user in user_follows:
users.append('<li><img src="%s">%s</li>' % (user.profile_picture, user.username))
while next:
user_follows, next = api.user_follows(with_next_url=next)
for user in user_follows:
users.append('<li><img src="%s">%s</li>' % (user.profile_picture, user.username))
content += ''.join(users)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(), content, api.x_ratelimit_remaining, api.x_ratelimit)
@route('/location_search')
def location_search():
access_token = request.session['access_token']
content = "<h2>Location Search</h2>"
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
location_search = api.location_search(lat=bw_latitude, lng=bw_longitude, distance=1000)
locations = []
for location in location_search:
locations.append('<li>%s <a href="https://www.google.com/maps/preview/@%s,%s,19z">Map</a> </li>' % (location.name, location.point.latitude, location.point.longitude))
content += ''.join(locations)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(), content, api.x_ratelimit_remaining, api.x_ratelimit)
@route('/tag_search')
def tag_search():
access_token = request.session['access_token']
content = "<h2>Tag Search</h2>"
if not access_token:
return 'Missing Access Token'
try:
api = client.InstagramAPI(access_token=access_token)
tag_search, next_tag = api.tag_search(q="bushwick")
tag_recent_media, next = api.tag_recent_media(tag_name=tag_search[0].name)
ascii_photos = []
for tag_media in tag_recent_media:
# Fetch the actual image
if (tag_media.get_standard_resolution_url().endswith(".mp4")):
continue
else:
image_file = cStringIO.StringIO(urllib.urlopen(tag_media.get_standard_resolution_url()).read())
ascii_photos.append(img2txt(image_file))
content += '<br/>'.join(ascii_photos)
except Exception as e:
print(e)
return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(), content, api.x_ratelimit_remaining, api.x_ratelimit)
@route('/realtime_callback')
@post('/realtime_callback')
def on_realtime_callback():
mode = request.GET.get("hub.mode")
challenge = request.GET.get("hub.challenge")
verify_token = request.GET.get("hub.verify_token")
if challenge:
return challenge
else:
x_hub_signature = request.header.get('X-Hub-Signature')
raw_response = request.body.read()
try:
reactor.process(CONFIG['client_secret'], raw_response, x_hub_signature)
except subscriptions.SubscriptionVerifyError:
print("Signature mismatch")