forked from jharia/datame
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exampleapp.py
251 lines (190 loc) · 8.11 KB
/
exampleapp.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
# -*- coding: utf-8 -*-
import base64
import os
import os.path
import urllib
import hmac
import json
import hashlib
from base64 import urlsafe_b64decode, urlsafe_b64encode
import requests
from flask import Flask, request, redirect, render_template, url_for
from flask_googlemaps import GoogleMaps, Map
FB_APP_ID = os.environ.get('FACEBOOK_APP_ID')
requests = requests.session()
app_url = 'https://graph.facebook.com/{0}'.format(FB_APP_ID)
FB_APP_NAME = json.loads(requests.get(app_url).content).get('name')
FB_APP_SECRET = os.environ.get('FACEBOOK_SECRET')
def oauth_login_url(preserve_path=True, next_url=None):
fb_login_uri = ("https://www.facebook.com/dialog/oauth"
"?client_id=%s&redirect_uri=%s" %
(app.config['FB_APP_ID'], get_home()))
if app.config['FBAPI_SCOPE']:
fb_login_uri += "&scope=%s" % ",".join(app.config['FBAPI_SCOPE'])
return fb_login_uri
def simple_dict_serialisation(params):
return "&".join(map(lambda k: "%s=%s" % (k, params[k]), params.keys()))
def base64_url_encode(data):
return base64.urlsafe_b64encode(data).rstrip('=')
def fbapi_get_string(path,
domain=u'graph', params=None, access_token=None,
encode_func=urllib.urlencode):
"""Make an API call"""
if not params:
params = {}
params[u'method'] = u'GET'
if access_token:
params[u'access_token'] = access_token
for k, v in params.iteritems():
if hasattr(v, 'encode'):
params[k] = v.encode('utf-8')
url = u'https://' + domain + u'.facebook.com' + path
params_encoded = encode_func(params)
url = url + params_encoded
result = requests.get(url).content
return result
def fbapi_auth(code):
params = {'client_id': app.config['FB_APP_ID'],
'redirect_uri': get_home(),
'client_secret': app.config['FB_APP_SECRET'],
'code': code}
result = fbapi_get_string(path=u"/oauth/access_token?", params=params,
encode_func=simple_dict_serialisation)
pairs = result.split("&", 1)
result_dict = {}
for pair in pairs:
(key, value) = pair.split("=")
result_dict[key] = value
return (result_dict["access_token"], result_dict["expires"])
def fbapi_get_application_access_token(id):
token = fbapi_get_string(
path=u"/oauth/access_token",
params=dict(grant_type=u'client_credentials', client_id=id,
client_secret=app.config['FB_APP_SECRET']),
domain=u'graph')
token = token.split('=')[-1]
if not str(id) in token:
print 'Token mismatch: %s not in %s' % (id, token)
return token
def fql(fql, token, args=None):
if not args:
args = {}
args["query"], args["format"], args["access_token"] = fql, "json", token
url = "https://api.facebook.com/method/fql.query"
r = requests.get(url, params=args)
return json.loads(r.content)
def fb_call(call, args=None):
url = "https://graph.facebook.com/{0}".format(call)
r = requests.get(url, params=args)
return json.loads(r.content)
def get_home():
return 'https://' + request.host + '/'
def get_token():
if request.args.get('code', None):
return fbapi_auth(request.args.get('code'))[0]
cookie_key = 'fbsr_{0}'.format(FB_APP_ID)
if cookie_key in request.cookies:
c = request.cookies.get(cookie_key)
encoded_data = c.split('.', 2)
sig = encoded_data[0]
data = json.loads(urlsafe_b64decode(str(encoded_data[1]) +
(64-len(encoded_data[1])%64)*"="))
if not data['algorithm'].upper() == 'HMAC-SHA256':
raise ValueError('unknown algorithm {0}'.format(data['algorithm']))
h = hmac.new(FB_APP_SECRET, digestmod=hashlib.sha256)
h.update(encoded_data[1])
expected_sig = urlsafe_b64encode(h.digest()).replace('=', '')
if sig != expected_sig:
raise ValueError('bad signature')
code = data['code']
params = {
'client_id': FB_APP_ID,
'client_secret': FB_APP_SECRET,
'redirect_uri': '',
'code': data['code']
}
from urlparse import parse_qs
r = requests.get('https://graph.facebook.com/oauth/access_token', params=params)
token = parse_qs(r.content).get('access_token')
return token
app = Flask(__name__)
GoogleMaps(app)
app.config.from_object(__name__)
app.config.from_object('conf.Config')
@app.route('/', methods=['GET', 'POST'])
def index():
# print get_home()
access_token = get_token()
channel_url = url_for('get_channel', _external=True)
channel_url = channel_url.replace('http:', '').replace('https:', '')
if access_token:
me = fb_call('me', args={'access_token': access_token})
fb_app = fb_call(FB_APP_ID, args={'access_token': access_token})
likes = fb_call('me/likes',
args={'access_token': access_token, 'limit': 4})
statuses = fb_call('me/statuses',
args={'access_token': access_token, 'limit': 4})
photos = fb_call('me/photos',
args={'access_token': access_token, 'limit': 16})
redir = get_home() + 'close/'
POST_TO_WALL = ("https://www.facebook.com/dialog/feed?redirect_uri=%s&"
"display=popup&app_id=%s" % (redir, FB_APP_ID))
app_friends = fql(
"SELECT uid, name, is_app_user, pic_square "
"FROM user "
"WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND "
" is_app_user = 1", access_token)
SEND_TO = ('https://www.facebook.com/dialog/send?'
'redirect_uri=%s&display=popup&app_id=%s&link=%s'
% (redir, FB_APP_ID, get_home()))
url = request.url
return render_template(
'index.html', app_id=FB_APP_ID, token=access_token, likes=likes,
statuses=statuses, photos=photos, app_friends=app_friends, app=fb_app,
me=me, POST_TO_WALL=POST_TO_WALL, SEND_TO=SEND_TO, url=url,
channel_url=channel_url, name=FB_APP_NAME)
else:
return render_template('login.html', app_id=FB_APP_ID, token=access_token, url=request.url, channel_url=channel_url, name=FB_APP_NAME)
@app.route('/channel.html', methods=['GET', 'POST'])
def get_channel():
return render_template('channel.html')
@app.route('/close/', methods=['GET', 'POST'])
def close():
return render_template('close.html')
@app.route('/fb_status_locations', methods=['GET'])
def get_fb_status_locations():
access_token = get_token()
if access_token:
me = fb_call('me', args={'access_token': access_token})
fb_app = fb_call(FB_APP_ID, args={'access_token': access_token})
statuses = fb_call('me/statuses',
args={'access_token': access_token, 'limit': 10})
mymap = Map(
identifier="view-side",
lat=37.4419,
lng=-122.1419,
markers=[(37.4419, -122.1419)]
)
sndmap = Map(
identifier="sndmap",
lat=37.4419,
lng=-122.1419,
markers={'http://maps.google.com/mapfiles/ms/icons/green-dot.png':[(37.4419, -122.1419)],
'http://maps.google.com/mapfiles/ms/icons/blue-dot.png':[(37.4300, -122.1400)]}
)
status_markers = []
app.logger.info(statuses)
for status in statuses['data']:
try:
status_markers.append((status['place']['location']['latitude'], status['place']['location']['longitude']))
except KeyError:
app.logger.warn('no location for status ', status['id'])
app.logger.info('status markers are '+str(status_markers))
return render_template('fb_status_locations.html',
me=me,statuses=statuses,mymap=mymap,sndmap=sndmap,status_markers=status_markers)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
if app.config.get('FB_APP_ID') and app.config.get('FB_APP_SECRET'):
app.run(host='0.0.0.0', port=port, debug=True)
else:
print 'Cannot start application without Facebook App Id and Secret set'