forked from LancelotGT/Pin-GT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PinGT.py
280 lines (252 loc) · 9.64 KB
/
PinGT.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
# -*- coding: utf-8 -*-
import re, time, datetime, pytz, smtplib
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, jsonify
from database import init_db, add_user, add_activity, select_activity, \
get_activity, update_activity, delete_activity, add_notification, \
get_notification, delete_notification
from crawler import *
# create our little application :)
app = Flask(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DEBUG=True,
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default',
MYSQL_DATABASE_HOST='52.91.229.69',
MYSQL_DATABASE_PORT=3306,
MYSQL_DATABASE_USER='root',
MYSQL_DATABASE_PASSWORD='CS6400',
MYSQL_DATABASE_DB='PIN'
))
app.config.from_object(__name__)
db_handler = init_db(app)
server = smtplib.SMTP( "smtp.gmail.com", 587 )
server.starttls()
server.login('[email protected]', 'CS6400PASSWORD')
@app.route('/')
def show_entries():
return render_template('show_entries.html')
'''
conduct heavy lifting work for events-related db communication
'''
@app.route('/events', methods=['GET', 'POST', 'UPDATE', 'DELETE'])
def events():
error = None
if request.method == "GET":
startDate = request.args.get('startDate', type=str)
endDate = request.args.get('endDate', type=str)
tag = request.args.get('tag', type=str)
entries = select_activity(db_handler, startDate, endDate, tag)
return jsonify(events=entries)
elif request.method == "POST":
name = request.json['name']
date = request.json['date']
time = request.json['time']
tags = request.json['tags']
location = request.json['location']
latlon = request.json['latlon']
description = request.json['description']
gtID = session['username']
# some input checking
if len(name) == 0 or len(date) == 0 or len(time) == 0 or len(tags) == 0 \
or len(location) == 0 or (not isinstance(latlon, dict)) \
or len(description) == 0 or len(gtID) == 0:
return "Bad request", 400
try:
int(gtID)
except:
return "Bad request", 400
if not isinstance(tags, list):
return "Bad request", 400
r = re.compile('.{4}-.{2}-.{2}')
if not (len(date) == 10):
return "Bad request", 400
else:
if not r.match(date):
return "Bad request", 400
add_activity(db_handler, name, gtID, location, latlon['lat'], latlon['lon'], \
date, time, description, tags)
return "OK"
elif request.method == "UPDATE":
activityID = long(request.json['activityID'])
name = request.json['name']
date = request.json['date']
time = request.json['time']
tags = request.json['tags']
description = request.json['description']
# some input checking
if len(name) == 0 or len(date) == 0 or len(time) == 0 or len(tags) == 0 \
or len(description) == 0:
return "Bad request", 400
if not isinstance(tags, list):
return "Bad request", 400
r = re.compile('.{4}-.{2}-.{2}')
if not (len(date) == 10):
return "Bad request", 400
else:
if not r.match(date):
return "Bad request", 400
act = get_activity(db_handler, activityID)
creatorID = act[2]
gtID = long(session['username'])
if gtID == creatorID:
update_activity(db_handler, activityID, name, date, time, tags, description)
return "OK"
else:
return "Not authorized", 403
elif request.method == "DELETE":
activityID = long(request.json['activityID'])
act = get_activity(db_handler, activityID)
creatorID = act[2]
gtID = long(session['username'])
if gtID == creatorID:
delete_notification(db_handler, activityID, gtID)
delete_activity(db_handler, activityID)
return "OK"
else:
return "Not authorized", 403
return redirect(url_for('/'))
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
key_pairs = {}
for row in db_handler.get_all_records(db_handler.user_tb):
key_pairs[row[0]] = row[1]
if int(request.form['username']) not in key_pairs.keys():
error = 'Invalid username'
elif request.form['password'] != key_pairs[int(request.form['username'])]:
error = 'Invalid password'
else:
session['username'] = request.form['username']
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error=error)
@app.route('/notification', methods=['GET', 'POST'])
def notification():
error = None
if request.method == "GET": # check whether there is upcoming events
gtID = session['username']
events = get_notification(db_handler, gtID)
key_pairs = {}
for row in db_handler.get_all_records(db_handler.user_tb):
key_pairs[row[0]] = row[1:]
user = key_pairs[long(gtID)]
pendingEvents = []
for e in events:
minutes = calculateTimeLeft(e)
if minutes < 120:
pushNotification(user, e, minutes)
delete_notification(db_handler, e[0], gtID)
d = {
'ActivityId': e[0],
'Name': e[1],
'CreatorId': e[2],
'Location': e[3],
'Date': str(e[4]),
'Time': e[5],
'LeftTime': minutes
}
pendingEvents.append(d)
if len(pendingEvents) > 0:
return jsonify(events=pendingEvents)
return "OK"
elif request.method == "POST": # subscribe an event
activityID = request.json['activityID']
gtID = session['username']
# some input checking
if len(gtID) == 0:
return "Not authorized", 403
try:
int(gtID)
except:
return "Bad request", 400
add_notification(db_handler, gtID, activityID)
return "OK"
@app.route('/register', methods=['GET', 'POST'])
def register():
error = None
if request.method == 'GET':
return render_template('register.html', error=error)
if request.method == 'POST':
if len(request.form['id']) == 0:
error = "GT ID cannot be empty"
return render_template('register.html', error=error)
if len(request.form['major']) == 0:
error = "Major cannot be empty"
return render_template('register.html', error=error)
if len(request.form['password']) == 0:
error = "Password cannot be empty"
return render_template('register.html', error=error)
if len(request.form['name']) == 0:
error = "Name cannot be empty"
return render_template('register.html', error=error)
if len(request.form['email']) == 0:
error = "Email cannot be empty"
return render_template('register.html', error=error)
if len(request.form['number']) == 0:
error = "Phone number cannot be empty"
return render_template('register.html', error=error)
id = request.form['id']
password = request.form['password']
grade = request.form['grade']
major = request.form['major']
gender = request.form['gender']
name = request.form['name']
number = request.form['number']
email = request.form['email']
# populate user info into user table
add_user(db_handler, id, name, password, gender == "male", major, \
grade == "undergraduate", number, email)
print "current user table: "
for row in db_handler.get_all_records(db_handler.user_tb):
print row
session['username'] = id
session['logged_in'] = True
return redirect(url_for('show_entries'))
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('show_entries'))
def calculateTimeLeft(e):
if e[5] == 'All day':
today_date = str(time.strftime("%Y-%m-%d"))
if today_date == str(e[4]):
return 0
start_time = e[5].strip().split('-')[0]
HH, MM = start_time.split(':')
MM = MM[0:2]
if start_time[5:] == 'pm':
HH = HH + 12
start_time = str(HH) + '-' + MM
start_date_string = str(e[4]) + "-" + start_time
start_date = datetime.datetime.strptime(start_date_string, "%Y-%m-%d-%H-%M")
today = datetime.datetime.now()
diff = start_date - today
minutes = diff.seconds / 60
return minutes
def pushNotification(user, event, minutes):
email = user[5]
phoneNumber = user[6]
eventName = event[1]
eventLoc = event[3]
msg = "Hello from Pin@GT! The event %s you subscribe is upcoming! It will happen at %s in %s minutes." \
% (eventName, eventLoc, minutes)
server.sendmail('PIN', [phoneNumber + '@tmomail.net'], msg)
server.sendmail('PIN', [email], msg)
def populateData(start_date, end_date):
events = crawler(start_date, end_date)
events = processGeoInfo(events)
# populate data into db
for e in events:
try:
add_activity(db_handler, e['Name'], e['CreatorId'], e['Location'], e['latlon']['lat'], \
e['latlon']['lng'], e['Date'], e['Time'], e['Description'], e['Tag'])
except:
continue
if __name__ == '__main__':
app.run()