-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
527 lines (412 loc) · 13 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
from flask import Flask, request, redirect, jsonify, render_template
from flask_cors import CORS, cross_origin
# from twilio.twiml.messaging_response import MessagingResponse
from scrape import extendToken
from scrapeNEW import sendSMS, sendReminderSMS, sendDebriefSMS
import random
import threading
import datetime
import re
# from twilio.rest import Client
from string import punctuation
import requests
import datetime
from flask_sqlalchemy import SQLAlchemy
import os
from flask import Flask
from flask_mail import Mail, Message
from mailcreds import mailpassword
import time
app = Flask(__name__)
mail = Mail(app)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
# database config
app.config.from_object(os.environ['APP_SETTINGS'])
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# mail config
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'teamcommitapp@gmail.com'
app.config['MAIL_PASSWORD'] = mailpassword
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
from models import User
currentUser = 0
@app.route("/")
def hello():
out = ''
try:
name = 'TEAM COMM!T'
return render_template('login.html', refname=name, refcode=0)
except:
out = ' FIX MEEEEEEEEEEEEEEEEEEEEEE!!!!.'
return out
@app.route("/mail", methods=["POST"])
def sendit():
if request.method == 'POST':
mail_params = request.get_json()
userId = mail_params['user']
user = User.query.get(userId)
referring_user = User.query.get(user.referringUser)
if user.email != '':
msg = Message('Hello from TEAM COMM!T', sender = 'teamcommitapp@gmail.com', recipients = [user.email])
msg.html = render_template('COMM!T Template.html', name=user.name, referring_user=referring_user.name, ref_link='https://www.commit.vote/r/' + str(user.id))
mail.send(msg)
return "Sent"
def sendReminderEmail(userId,refname):
#userId = mail_params['user']
user = User.query.get(userId)
#referring_user = User.query.get(user.referringUser)
if user.email != '':
msg = Message('Hello from TEAM COMM!T', sender = 'teamcommitapp@gmail.com', recipients = [user.email])
msg.html = render_template('COMM!T Template.html', name=user.name, referring_user=refname, ref_link='https://www.commit.vote/r/' + str(user.id))
mail.send(msg)
return "Sent"
@app.route("/mail/links")
def sendlinks():
users = User.query.filter_by(distFromPoll=None).all()
emailed_users = set([])
if len(users) != 0:
with mail.connect() as conn:
for user in users:
if user.email not in emailed_users:
referring_user = User.query.get(user.referringUser)
subject = "COMM!T: Check in time"
msg = Message(recipients=[user.email], subject=subject, sender='teamcommitapp@gmail.com')
msg.html = render_template('COMM!T check-in.html', name=user.name, referring_user=referring_user.name, checkin_link='https://www.commit.vote/checkin/' + str(referring_user.id) + 'A' + str(user.id))
# if user.phone != None:
# try:
# sendReminderSMS(user.phone,referring_user.name,str(referring_user.id),str(user.id))
# except Exception as e:
# print(e)
try:
conn.send(msg)
emailed_users.add(user.email)
except:
emailed_users.add(user.email)
print(user.email)
#time.sleep(5)
return "Sent"
@app.route("/sms/links")
def sendSMSlinks():
users = User.query.filter_by(distFromPoll=None).all()
sent_users = set([])
#print(users)
if len(users) != 0:
for user in users:
#print('attempting user')
#print(user.id)
if user.phone not in sent_users:
try:
referring_user = User.query.get(user.referringUser)
except:
referring_user = User.query.get('0')
print('GETTING REFERRING USER FAILED')
#print('attempting a phone')
#print(user.phone)
#print(user.name)
if user.phone != None:
try:
sent_users.add(user.phone)
sendReminderSMS(user.phone,referring_user.name,str(referring_user.id),str(user.id))
except Exception as e:
print('sendReminderSMS route failed')
print(e)
sent_users.add(user.phone)
else:
#print('call to sendReminderSMS worked')
print(user.phone)
return "Sent"
@app.route("/mail/debriefs")
def senddebriefs():
users = User.query.all()
emailed_users = set([])
succeeded = []
failed = []
count = 0
if len(users) != 0:
with mail.connect() as conn:
for user in users:
print(user.name)
referrals = User.query.filter_by(referringUser=str(user.id)).all()
# referrals = []
# for tmpuser in users:
# if tmpuser.referringUser == str(user.id):
# referrals.append(tmpuser)
wins = []
fails = []
for referral in referrals:
if referral.distFromPoll != None:
wins.append(referral.name + ' (distance from poll: ' + referral.distFromPoll + ' )')
else:
fails.append(referral.name)
print('email is ')
print(user.email)
print('referrals are ')
print(referrals)
if user.email == None:
continue
voted = user.distFromPoll
if user.email not in emailed_users and len(referrals) != 0 and user.referringUser != None:
count += 1
print(count)
subject = "COMM!T: Election Day Debrief"
referring_user = User.query.get(user.referringUser)
msg = Message(recipients=['jimmoffet@gmail.com'], subject=subject, sender='teamcommitapp@gmail.com')
msg.html = render_template('COMM!T Debrief.html', voted=voted, name=user.name, wins=wins, fails=fails, referring_user=referring_user.name)
try:
conn.send(msg)
print('message sent')
emailed_users.add(user.email)
except:
emailed_users.add(user.email)
print('message failed'+user.email)
failed.append(user.email)
else:
succeeded.append(user.email)
print('succeeded')
print(succeeded)
print('failed')
print(failed)
return "Sent"
@app.route("/sms/debriefs")
def sendSMSdebriefs():
users = User.query.all()
sent_users = set([])
succeeded = []
failed = []
count = 0
if len(users) != 0:
for user in users:
print(user.name)
referrals = User.query.filter_by(referringUser=str(user.id)).all()
if len(referrals) == 0:
print('no referrals')
continue
wins = []
fails = []
for referral in referrals:
if referral.distFromPoll != None:
wins.append(referral.name + ' (distance from poll: ' + referral.distFromPoll + ' )')
else:
fails.append(referral.name)
# print('phone is ')
# print(user.phone)
# print('referrals are ')
# print(referrals)
if user.phone == None:
print('no phone')
continue
voted = user.distFromPoll
if user.phone not in sent_users and len(referrals) != 0 and user.referringUser != None:
count += 1
#print(count)
referring_user = User.query.get(user.referringUser)
if voted == None:
voted = 'didnt'
try:
print(user.phone,referring_user.name,user.name,wins,fails,voted)
sendDebriefSMS("7733541500",referring_user.name,user.name,wins,fails,voted)
print('message sent')
sent_users.add(user.phone)
except Exception as e:
sent_users.add(user.phone)
print('message failed '+user.phone)
print(e)
failed.append(user.phone)
else:
succeeded.append(user.phone)
print('succeeded')
print(succeeded)
print('failed')
print(failed)
return "Sent"
@app.route("/initialize", methods=["POST", "GET"])
def initdb():
user = User('TEAM COMM!T')
user.email = 'jimmoffet@gmail.com'
db.session.add(user)
db.session.commit()
return 'success'
@app.route("/emaillist")
def emaillist():
users = User.query.all()
emails = []
for user in users:
emails.append(user.email)
print_to_screen = ', '.join(emails)
return print_to_screen
@app.route("/r/<string:refcode>", methods=["POST", "GET"])
def renderLogin(refcode):
if refcode:
refcode = refcode
refname = User.query.get(refcode).name
else:
refcode = 0
return render_template('login.html', refcode=refcode, refname=refname)
@app.route("/commit/<string:refcode>", methods=["POST", "GET"])
def renderCommit(refcode):
if refcode:
data = refcode.split('A')
refcode = data[0]
userId = data[1]
name = User.query.get(refcode).name
else:
name = "TEAM COMM!T"
refcode = 0
userId = 0
return render_template('commit.html', referring_user=name, refcode=refcode, current_user=userId)
@app.route("/share/<string:refcode>", methods=["POST", "GET"])
def renderShare(refcode):
if refcode:
data = refcode.split('A')
refcode = data[0]
userId = data[1]
name = User.query.get(refcode).name
else:
name = "TEAM COMM!T"
return render_template('share.html', referring_user=name, refcode=refcode, current_user=userId)
@app.route("/checkin/<string:refcode>", methods=["POST", "GET"])
def renderCheckin(refcode):
if refcode:
data = refcode.split('A')
refcode = data[0]
userId = data[1]
name = User.query.get(refcode).name
else:
name = "TEAM COMM!T"
return render_template('checkin.html', referring_user=name, refcode=refcode, current_user=userId)
@app.route("/checkedin/<string:refcode>", methods=["POST", "GET"])
def renderCheckedin(refcode):
if refcode:
data = refcode.split('A')
refcode = data[0]
userId = data[1]
dist = data[2]
name = User.query.get(refcode).name
currentUser = User.query.get(userId)
print(currentUser.name)
print(dist)
currentUser.distFromPoll = dist
db.session.commit()
else:
name = "TEAM COMM!T"
return render_template('checkedin.html', referring_user=name, refcode=refcode, current_user=userId)
@app.route("/privacy", methods=["POST", "GET"])
def renderPrivacy(refcode):
return render_template('privacy.html')
# @app.route('/<string:page_name>/')
# def render_static(page_name):
# return render_template('%s.html' % page_name)
@app.route("/positive/<string:message>", methods=["POST", "GET"])
def writePosMessage(message):
resp = writeMessageToDB(message)
return 'Success!'
@app.route("/negative/<string:message>", methods=["POST", "GET"])
def writeNegMessage(message):
resp = writeMessageToDB2(message)
return 'Success!'
@app.route("/writeuser/<string:message>", methods=["POST", "GET"])
def writeUser(message):
resp = writeUserToDB(message)
return 'Success!'
@app.route("/pm", methods=["POST"])
def pm():
if request.method == "POST":
update_dict = request.get_json()
userId = update_dict['user']
positiveMessage = update_dict['positiveMessage']
user = User.query.get(userId)
user.positiveMessage = positiveMessage
db.session.commit()
return 'Success!'
@app.route("/nm", methods=["POST"])
def nm():
if request.method == "POST":
update_dict = request.get_json()
userId = update_dict['user']
negativeMessage = update_dict['negativeMessage']
user = User.query.get(userId)
user.negativeMessage = negativeMessage
db.session.commit()
return 'Success!'
@app.route('/createuser', methods=["POST"])
def createUser():
if request.method == "POST":
json_dict = request.get_json(force=True)
print(json_dict)
email = json_dict['email']
sms = json_dict['phone']
name = json_dict['name']
user = None
new = False
if email == '':
email = '99999999999999999'
if sms == '':
sms = '99999999999999999'
users = User.query.all()
for temp_user in users:
print('username')
print(temp_user.name)
print(email)
print(sms)
print(temp_user.email)
print(temp_user.phone)
if email == temp_user.email or sms == temp_user.phone:
user = temp_user
new = False
print('this is an existing user')
break
else:
new = True
print('this is a new user')
if new == True:
user = User(name)
db.session.add(user)
print('add new user')
user.name = json_dict['name']
user.email = json_dict['email']
user.phone = json_dict['phone']
user.fbId = json_dict['fbId']
user.twId = json_dict['twId']
user.twToken = json_dict['twToken']
user.referringUser = json_dict['referringUser']
user.fbToken = ''
if json_dict['referringUser'] != '':
refname = User.query.get(json_dict['referringUser']).name
if json_dict['fbToken'] != '':
user.fbToken = extendToken(json_dict['fbToken'])
user.positiveMessage = "COMM!Tbot says, " + name + " just showed up at the polls. Score one more for democracy!"
user.negativeMessage = "COMM!Tbot says, Oh No! " + name + " didn't show up at the polls today."
user.date = datetime.datetime.now()
user.triggerDate = datetime.datetime(2018, 11, 7, 7, 00)
db.session.commit()
#yessena 3472682813 sendReminderEmail(userId,refname)
idval = ''
try:
idval = str(user.id)
except Exception as e:
print(e)
try:
if json_dict['phone'] != '':
phone = json_dict['phone']
if phone[0] != 1:
phone = '1'+phone
sendSMS(phone,refname,idval)
#sendReminderSMS(phone,refname,str(json_dict['referringUser']),idval)
except Exception as e:
print("sms failed")
print(e)
try:
if json_dict['email'] != '':
email = json_dict['email']
# sendReminderEmail(str(user.id),refname)
except Exception as e:
print("email failed")
print(e)
return str(user.id)
if __name__ == "__main__":
app.run(debug=False)