-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
571 lines (540 loc) · 15.8 KB
/
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
from flask import Flask, request, redirect, url_for, flash, render_template, json, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
from flask_heroku import Heroku
import string
import random
from datetime import datetime, timedelta
import time
import os
from twilio.rest import TwilioRestClient
import twilio.twiml
app = Flask(__name__)
heroku = Heroku(app)
db = SQLAlchemy(app)
universal = os.environ['UNIVERSAL_API']
account_sid = "AC32798c5f8600bb6d158e63181eb705e1"
auth_token = "3ba6672b64fb89178bfeaef60ce34061"
def id_generator(size=32, chars=(string.ascii_uppercase + string.ascii_lowercase
+ string.digits)):
return ''.join(random.choice(chars) for x in range(size))
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
fbid = db.Column(db.String, unique=True)
name = db.Column(db.String(128)) # user's name on Facebook
mobile = db.Column(db.String(16)) # consecutive digits, no dashes / parens
apikey = db.Column(db.String(32), unique=True)
university_id = db.Column(db.Integer, db.ForeignKey('university.id'))
verified = db.Column(db.Boolean, default=False)
def events():
return Event.query.filter_by(or_(initiator=self.id, partner=self.id))
def __init__(self, fbid, name, apikey, university_id):
self.fbid = fbid
self.name = name
self.apikey = apikey
self.university_id = university_id
class University(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True)
users = db.relationship('Person', backref='university', lazy='dynamic')
def __init__(self, name):
self.name = name
class Event(db.Model):
id = db.Column(db.Integer, primary_key=True)
category = db.Column(db.String(32))
init_id = db.Column(db.Integer, db.ForeignKey('person.id'))
proposer_id = db.Column(db.Integer, db.ForeignKey('person.id'), nullable=True)
partner_id = db.Column(db.Integer, db.ForeignKey('person.id'), nullable=True)
university_id = db.Column(db.Integer, db.ForeignKey('university.id'))
startdate = db.Column(db.DateTime)
enddate = db.Column(db.DateTime)
messagedate = db.Column(db.DateTime, nullable=True)
def __init__(self, category, init_id, university_id, startdate, enddate):
self.category = category
self.init_id = init_id
self.university_id = university_id
self.startdate = startdate
self.enddate = enddate
@app.route('/')
def index():
return render_template('index.html')
#returns empty string if there is a db error, or api is wrong
@app.route('/person/new', methods=['POST'])
def create_user():
data = request.json
checkapi = data["apikey"]
if not checkapi == universal:
data = {
"error" : "could not authenticate API key"
}
resp = jsonify(data)
resp.status_code = 500
return resp
fbid = data["fbid"]
uni = University.query.filter_by(name=data["university"]).first()
if uni is None:
data = {
"error" : "could not find University"
}
resp = jsonify(data)
resp.status_code = 500
return resp
apikey = id_generator()
user = Person(fbid, data["name"], apikey, uni.id)
db.session.add(user)
try:
db.session.commit()
data = {
"apikey" : apikey,
"error" : ""
}
resp = jsonify(data)
resp.status_code = 200
return resp
except:
data = {
"error" : "could not create user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
# grabs user based on API key
@app.route('/person/<apikey>', methods=['GET'])
def get_user(apikey):
#data = request.json
#apikey = data["apikey"]
user = Person.query.filter_by(apikey=apikey).first()
if user is None:
data = {
"error" : "could not find user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
jsondict = {}
jsondict["id"] = str(user.id)
jsondict["fbid"] = user.fbid
jsondict["name"] = user.name
jsondict["mobile"] = user.mobile
jsondict["university_id"] = str(user.university_id)
jsondict["verified"] = str(user.verified)
resp = jsonify(jsondict)
resp.status_code = 200
return resp
#updates a user's phone number
@app.route('/person/mobile', methods=['POST'])
def update_mobile():
data = request.json
apikey = data["apikey"]
num = data["mobile"]
user = Person.query.filter_by(apikey=apikey).first()
if user is None:
data = {
"error" : "could not find user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
user.mobile = num
db.session.add(user)
try:
db.session.commit()
data = {
"error" : ""
}
resp = jsonify(data)
resp.status_code = 200
client = TwilioRestClient(account_sid, auth_token)
message = client.sms.messages.create(body="Welcome to Merge! Please text back 'Yes' to confirm", to=num,
from_="+15616669720")
return resp
except:
data = {
"error" : "could not update mobile"
}
resp = jsonify(data)
resp.status_code = 500
return resp
#used for twilio confirmation
@app.route('/person/twilio', methods=['POST'])
def receive_confirmation():
print 'here'
from_number = request.values.get('From', None)
print 'here2'
user = Person.query.filter_by(mobile=from_number).first()
if user is None:
data = {
"error" : "could not verify number"
}
resp = jsonify(data)
resp.status_code = 500
return resp
body = request.values.get('Body', None)
if not body == "Yes":
data = {
"error" : "could not verify number"
}
resp = jsonify(data)
resp.status_code = 500
return resp
user.verified = True
db.session.add(user)
try:
db.session.commit()
message = "Confirmed! We hope you enjoy our service!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
except:
data = {
"error" : "could not update number"
}
resp = jsonify(data)
resp.status_code = 500
return resp
@app.route('/person/verified/<apikey>', methods=['GET'])
def check_confirmation(apikey):
#data = request.json
#apikey = data["apikey"]
user = Person.query.filter_by(apikey=apikey).first()
if user is None:
data = {
"error" : "could not authenticate user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
if user.verified == True:
data = {
"error" : ""
}
resp = jsonify(data)
resp.status_code = 500
return resp
data = {
"error" : "user is not verified"
}
resp = jsonify(data)
resp.status_code = 500
return resp
#returns empty string if you get a db error
#TODO: add app API authentication. DONE
@app.route('/university/new', methods=['POST'])
def create_uni():
data = request.json
checkapi = data["apikey"]
if not checkapi == universal:
data = {
"error" : "could not authenticate API key"
}
resp = jsonify(data)
resp.status_code = 500
return resp
name = data["name"]
uni = University(name)
db.session.add(uni)
try:
db.session.commit()
data = {
"error" : ""
}
resp = jsonify(data)
resp.status_code = 200
return resp
except:
data = {
"error" : "could not create university"
}
resp = jsonify(data)
resp.status_code = 500
return resp
@app.route('/university/all/<apikey>', methods=['GET'])
def all_unis(apikey):
#data = request.json
checkapi = apikey
if not checkapi == universal:
data = {
"error" : "could not authenticate API key"
}
resp = jsonify(data)
resp.status_code = 500
return resp
unis = University.query.all()
jsondict = {}
jsondict["unis"] = []
for uni in unis:
unijson = {}
unijson["name"] = uni.name
unijson["id"] = str(uni.id)
jsondict["unis"].append(unijson);
resp = jsonify(jsondict)
resp.status_code = 200
return resp
# creates a new event for a given user
# TODO: fix start and end dates to cooperate
@app.route('/event/new', methods=['POST'])
def create_event():
data = request.json
apikey = data["apikey"]
initiator = Person.query.filter_by(apikey=apikey).first()
if initiator is None:
data = {
"error" : "Could not authenticate user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
category = data["category"]
start = datetime.fromtimestamp(int(data["startdate"]))
end = datetime.fromtimestamp(int(data["enddate"]))
event = Event(category, initiator.id, initiator.university_id, start, end)
db.session.add(event)
try:
db.session.commit()
data = {
"error" : ""
}
resp = jsonify(data)
resp.status_code = 200
return resp
except:
data = {
"error" : "could not create event"
}
resp = jsonify(data)
resp.status_code = 500
return resp
# the current user proposes to join an event
@app.route('/event/propose', methods=['POST'])
def propose_join():
data = request.json
apikey = data["apikey"]
user = Person.query.filter_by(apikey=apikey).first()
if user is None:
data = {
"error" : "Could not authenticate user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
event = Event.query.filter_by(id=int(data["event_id"])).first()
if event is None:
data = {
"error" : "Could not find event"
}
resp = jsonify(data)
resp.status_code = 500
return resp
event.proposer_id = user.id
db.session.add(event)
try:
db.session.commit()
data = {
"error" : ""
}
resp = jsonify(data)
resp.status_code = 200
return resp
except:
data = {
"error" : "could not add proposed user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
# the current user joins an event
@app.route('/event/join', methods=['POST'])
def join_event():
data = request.json
apikey = data["apikey"]
user = Person.query.filter_by(apikey=apikey).first()
if user is None:
data = {
"error" : "Could not authenticate user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
event = Event.query.filter_by(id=int(data["event_id"])).first()
if event is None:
data = {
"error" : "Could not find event"
}
resp = jsonify(data)
resp.status_code = 500
return resp
event.partner_id = user.id
event.proposer_id = None
db.session.add(event)
try:
db.session.commit()
data = {
"error" : ""
}
resp = jsonify(data)
resp.status_code = 200
return resp
except:
data = {
"error" : "could not join event"
}
resp = jsonify(data)
resp.status_code = 500
return resp
# grabs all events currently going on from the user's university in a given category
@app.route('/event/<apikey>/<category>', methods=['GET'])
def get_events(apikey, category):
#data = request.args # data = request.json
#apikey = data['apikey']
user = Person.query.filter_by(apikey=apikey).first()
if user is None:
data = {
"error" : "Could not authenticate user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
#category = data["category"]
events = Event.query.filter_by(university_id=user.university_id, category=category).filter(Event.partner_id == None, Event.enddate > datetime.now())
jsondict = {}
jsondict["events"] = []
for event in events:
eventjson = {}
eventjson["id"] = str(event.id)
eventjson["category"] = event.category
initiator = Person.query.filter_by(id = event.init_id).first()
print "about to initialize"
initjson = {}
print "initialized"
initjson["id"] = str(initiator.id)
initjson["name"] = initiator.name
initjson["fbid"] = initiator.fbid
initjson["mobile"] = initiator.mobile
initjson["university_id"] = str(initiator.university_id)
initjson["verified"] = str(initiator.verified)
eventjson["initiator"] = initjson
eventjson["startdate"] = time.mktime(event.startdate.timetuple())
eventjson["enddate"] = time.mktime(event.enddate.timetuple())
if event.messagedate:
eventjson["messagedate"] = time.mktime(event.messagedate.timetuple())
jsondict["events"].append(eventjson);
resp = jsonify(jsondict)
resp.status_code = 200
return resp
# our participant text messaged the event host
@app.route('/event/text', methods=['POST'])
def event_text():
data = request.json
apikey = data["apikey"]
event = Event.query.filter_by(id=int(data["event_id"])).first()
if event is None or event.proposer_id is None:
data = {
"error" : "Could not find event"
}
resp = jsonify(data)
resp.status_code = 500
return resp
user = Person.query.filter_by(apikey=apikey, id=int(event.proposer_id)).first()
if user is None:
data = {
"error" : "Could not authenticate user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
event.messagedate = datetime.now()
db.session.add(event)
try:
db.session.commit()
data = {
"error" : ""
}
resp = jsonify(data)
resp.status_code = 200
return resp
except:
data = {
"error" : "could not add message info"
}
resp = jsonify(data)
resp.status_code = 500
return resp
# return a hash of all events for which a user must be prompted on
@app.route('/event/prompt/<apikey>', methods=['GET'])
def prompt_on_event(apikey):
#data = request.json
#apikey = data["apikey"]
user = Person.query.filter_by(apikey=apikey).first()
if user is None:
data = {
"error" : "Could not authenticate user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
events = Event.query.filter(Event.partner_id==user.id, Event.messagedate < datetime.now() - timedelta(minutes=5)) # remind if prompted > 5 minutes ago
jsondict = {}
jsondict["events"] = []
for event in events:
eventjson = {}
eventjson["category"] = event.category
initiator = Person.query.filter_by(id = event.init_id).first()
eventjson["init"] = initiator.fbid
partner = Person.query.filter_by(id=event.partner_id).first()
if partner:
eventjson["partner"] = partner.fbid
eventjson["startdate"] = time.mktime(event.startdate.timetuple())
eventjson["enddate"] = time.mktime(event.enddate.timetuple())
if event.messagedate:
eventjson["messagedate"] = time.mktime(event.messagedate.timetuple())
jsondict["events"].append(eventjson);
resp = jsonify(jsondict)
resp.status_code = 200
return resp
#get news feed
@app.route('/event/newsfeed/<apikey>', methods=['GET'])
def newsfeed():
#data = request.json
#apikey = data["apikey"]
user = Person.query.filter_by(apikey=apikey).first()
if user is None:
data = {
"error" : "Could not authenticate user"
}
resp = jsonify(data)
resp.status_code = 500
return resp
events = Event.query.filter_by(university_id=user.university_id).filter(Event.partner_id != None).order_by(Event.enddate.desc()).limit(10).all()
jsondict = {}
jsondict["events"] = []
for event in events:
eventjson = {}
eventjson["category"] = event.category
initiator = Person.query.filter_by(id = event.init_id).first()
initjson = {}
initjson["id"] = str(initiator.id)
initjson["name"] = initiator.name
initjson["fbid"] = initiator.fbid
initjson["mobile"] = initiator.mobile
initjson["university_id"] = str(initiator.university_id)
initjson["verified"] = str(initiator.verified)
eventjson["initiator"] = initjson
partner = Person.query.filter_by(id=event.partner_id).first()
if partner:
partjson = {}
partjson["id"] = str(partner.id)
partjson["name"] = partner.name
partjson["fbid"] = partner.fbid
partjson["mobile"] = partner.mobile
partjson["university_id"] = str(partner.university_id)
partjson["verified"] = str(partner.verified)
eventjson["partner"] = partJSON
eventjson["startdate"] = time.mktime(event.startdate.timetuple())
eventjson["enddate"] = time.mktime(event.enddate.timetuple())
if event.messagedate:
eventjson["messagedate"] = time.mktime(event.messagedate.timetuple())
jsondict["events"].append(eventjson);
resp = jsonify(jsondict)
resp.status_code = 200
return resp
if __name__ == '__main__':
app.run(debug=True)