forked from ptarjan/fb-hackathon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
264 lines (210 loc) · 7.33 KB
/
main.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
#!/usr/bin/env python
from datetime import datetime
import collections
import logging
import os
import sys
import urllib, urllib2, urlparse
import re
from django.utils import simplejson as json
try:
from secret import Facebook
except:
print """You need to setup the application secret.
cp secret.py.sample secret.py
Then put in your application id and secret."""
sys.exit()
import wsgiref.handlers
import facebook
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class UserHandler(webapp.RequestHandler):
def getFBGraph(self):
user = facebook.get_user_from_cookie(self.request.cookies, Facebook.appId, Facebook.secret)
if user:
graph = facebook.GraphAPI(user["access_token"])
try :
me = graph.get_object("me")
except Exception, e:
return None
return graph
def getFriends(self):
graph = self.getFBGraph()
if graph:
friends = graph.get_connections("me", "friends")['data']
def getName(friend) :
if friend.has_key('name'):
return friend['name']
return ''
return sorted(friends, key=getName)
return []
def getMe(self):
graph = self.getFBGraph()
if graph:
return graph.get_object("me")
return {}
def getID(self):
return self.getMe()['id']
def isAttending(self, eid):
graph = self.getFBGraph()
if graph:
attending = graph.get_connections(eid, 'attending')['data']
my_id = self.getID()
for person in attending:
if person['id'] == my_id:
return True
return False
class AppHandler(webapp.RequestHandler):
def fetch(self, url, isJson=True, cached=60): # 1 minute
logging.info('fetching: '+url)
if cached:
if memcache.get(url):
return memcache.get(url)
logging.info('cache miss: '+url)
try:
result = urllib2.urlopen(url)
except urllib2.HTTPError, e:
print '\n\n', e.geturl()
raise e
if isJson:
ret = json.loads(result.read())
else :
ret = result.read()
if cached:
memcache.add(url, ret, cached)
return ret
def getAppOAuthToken(self):
response = self.fetch('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode({
'grant_type': 'client_credentials',
'client_id': Facebook.appId,
'client_secret': Facebook.secret}), isJson=False)
for piece in response.split('&') :
k,v = piece.split('=')
if k == 'access_token':
return v
def getEvents(self, page_id):
events = self.fetch('https://graph.facebook.com/'+page_id+'/events?access_token='+self.getAppOAuthToken())['data']
for event in events:
# too slow...
# event['count'] = self.getHackCount(event['id'])
event['start_time'] = datetime.strptime(event['start_time'], "%Y-%m-%dT%H:%M:%S")
event['end_time'] = datetime.strptime(event['end_time'], "%Y-%m-%dT%H:%M:%S")
return events
def getEvent(self, eid):
return self.fetch('https://graph.facebook.com/'+eid+'?access_token='+self.getAppOAuthToken())
def getRawHacks(self, eid):
data = []
url = 'https://graph.facebook.com/'+str(eid)+'/feed?access_token='+self.getAppOAuthToken()
# print "\n\n"+url
while 1:
feed = self.fetch(url)
data += feed['data']
if feed.has_key('paging'):
if url == feed['paging']['next']:
# bug in facebook
break
url = feed['paging']['next']
else:
break
return data
def getHacks(self, eid):
hacks = []
for hack in self.getRawHacks(eid):
hacks.append(hack)
ret = []
for hack in hacks:
if not hack.has_key('application') or hack['application']['id'] != Facebook.appId:
continue
if not hack.has_key('picture'):
## non-structrued format
if not hack.has_key('message'):
continue
message = hack.get('message')
boom = message.split('\n', 1)
if len(boom) != 2:
continue
title, description = boom
description = re.sub('Image:.*', '', description)
description = re.sub('Link:.*', '', description)
search = re.search('Image: (.*)', message)
if not search:
continue
screenshot = search.group(1)
search = re.search('Link: (.*)', message)
if not search:
continue
link = search.group(1)
other_eid, fbid = hack['id'].split('_')
ret.append({
'description' : description,
'link' : 'http://www.facebook.com/permalink.php?id='+eid+'&story_fbid='+fbid,
'likes' : hack.get('likes', {'count' : 0}).get('count'),
'screenshot' : screenshot,
'screenshot_raw' : link,
'title' : title,
})
if not hack.has_key('picture') or not hack.has_key('to') or not hack['to'].has_key('data') or not hack.has_key('id'):
continue
people = filter(lambda x: x and x.has_key('id') and x['id'] != eid, hack['to']['data'])
other_eid, fbid = hack['id'].split('_')
# print '\n\n', hack
ret.append({
'description' : hack.get('description'),
'link' : 'http://www.facebook.com/permalink.php?id='+eid+'&story_fbid='+fbid,
'likes' : hack.get('likes', {'count' : 0}).get('count'),
'people' : people,
'screenshot' : hack.get('picture'),
'screenshot_raw' : hack.get('link'),
'title' : hack.get('name'),
})
return ret
def getHackCount(self, eid):
return len(self.getHacks(eid))
class IndexHandler(AppHandler):
def get(self):
template_values = {
'events' : self.getEvents('167580640987') + self.getEvents('114869201895800')
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
def post(self):
return self.get()
class EventHandler(AppHandler):
def get(self, eid):
template_values = {
'hacks' : self.getHacks(eid),
'eid' : eid,
'event' : self.getEvent(eid),
}
path = os.path.join(os.path.dirname(__file__), 'event.html')
self.response.out.write(template.render(path, template_values))
def post(self, eid):
return self.get(eid)
class EventRedirectHandler(webapp.RequestHandler):
def get(self, eid):
self.redirect('http://www.facebook.com/event.php?eid='+eid)
def post(self, eid):
return self.get(eid)
class EventSubmissionHandler(AppHandler, UserHandler):
def post(self, eid):
return self.get(eid)
def get(self, eid):
template_values = {
'eid' : eid,
'event' : self.getEvent(eid),
'friends' : self.getFriends(),
'me' : self.getMe(),
'isAttending' : self.isAttending(eid),
}
path = os.path.join(os.path.dirname(__file__), 'event_submit.html')
self.response.out.write(template.render(path, template_values))
def main():
application = webapp.WSGIApplication([('/+', IndexHandler),
('/+([0-9]*)/*', EventHandler),
('/+([0-9]*)/+event', EventRedirectHandler),
('/+([0-9]*)/+submit', EventSubmissionHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()