-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.py
660 lines (550 loc) · 18 KB
/
routes.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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
from flask import (
Flask,
request,
make_response,
redirect,
url_for,
jsonify,
)
from flask import render_template, session
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
import os
import pytz
import datetime
from display import (
allRooms,
allFavoriteRooms,
addFavorite,
removeFavorite,
getFavoriteRooms,
db_session,
getUserGroups,
addNewGroup,
deleteGroup,
editGroupInfo,
addRoomToGroup,
removeRoomFromGroup,
getUserGroupsJSON,
clearRoomStatuses,
)
from CASClient import CASClient
from sqlalchemy.orm import scoped_session, sessionmaker
import json
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from json import dumps
import json
import collections
from updateavailable import checkRooms, changeRoomPdf
from api_access import check_is_undergrad
from collections import defaultdict
from display import db_session, Reviews, Room
import time
import config
app = Flask(__name__)
def get_time_string_from_utc_dt(utc_dt):
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(
tz=pytz.timezone("America/New_York")
)
local_dt_string = local_dt.strftime("%b %d, %Y")
return local_dt_string
app.jinja_env.globals.update(get_time_string_from_utc_dt=get_time_string_from_utc_dt)
# Generated by os.urandom(16)
# This is needed for the CAS login
app.secret_key = b"\xe7\xa3\x1c\xf2\n\xe9\xb6\xd0\xcd\xbcI\xa9\x14\x8a\x91\x86"
# app.config['SECRET_KEY'] = 'secret'
# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DATABASE_URL")
# db = create_engine(os.environ.get("DATABASE_URL"))
# db = SQLAlchemy(app)
# investigate conn pooling
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
@app.route("/get_reviews", methods=["GET", "POST"])
def get_reviews():
# CASClient().authenticate()
building_name = request.args.get("building_name")
room_number = request.args.get("room_no")
reviews = (
db_session.query(Reviews)
.filter(
Reviews.building_name == building_name, Reviews.room_number == room_number
)
.order_by(Reviews.date.desc())
.all()
)
html = render_template(
"reviews_body.html",
reviews=reviews,
building_name=building_name,
room_number=room_number,
)
response = make_response(html)
return response
@app.route("/")
def index():
if CASClient().is_logged_in():
return redirect("/rooms")
return make_response(render_template("index.html"))
@app.route("/rooms", methods=["GET", "POST"])
def getRooms():
username = CASClient().authenticate()
username = username.lower().strip()
total_reviews = db_session.query(Reviews).count()
total_rooms = db_session.query(Room).count()
return make_response(
render_template(
"availablerooms.html",
username=username,
total_reviews=total_reviews,
total_rooms=total_rooms,
)
)
@app.route("/faq")
def faq():
# CASClient().authenticate()
return make_response(render_template("faq.html"))
@app.route("/queryrooms", methods=["GET", "POST"])
def queryRooms():
username = CASClient().authenticate()
username = username.lower().strip()
college = request.args.get("college", default="")
occupancy = request.args.get("occupancy", default="")
building = request.args.get("building", default="")
data = allRooms(
username,
college,
"",
"",
occupancy,
building,
"",
)
roomids = []
# averaging code
rankings = collections.defaultdict(list)
rankmap = collections.defaultdict(int)
seen = set()
for room in data:
if room.DrawTime is not None:
rankings[room.Room.room_id].append(room.DrawTime.draw_time)
else:
rankings[room.Room.room_id].append(float("inf"))
for room in data:
if room.Room.room_id not in seen:
mean = sum(rankings[room.Room.room_id]) / len(rankings[room.Room.room_id])
rankmap[room.Room.room_id] = mean
seen.add(room.Room.room_id)
data.sort(key=lambda x: rankmap[x.Room.room_id])
roomsList = []
i = 1
# if not year:
# i = max(0, int(firstranking) - 1)
for room in data:
if i > len(data):
break
# deduplication
if room.Room.room_id in roomids:
continue
roomids.append(room.Room.room_id)
# only continue if ranking permits
if i - 1 < 0:
i += 1
continue
if occupancy:
if occupancy != str(room.Room.occupancy):
i += 1
continue
if building:
if building != room.Room.building:
# print(room.Room.building)
i += 1
continue
review_count = (
db_session.query(Reviews)
.filter(
Reviews.room_number == room.Room.room_no,
Reviews.building_name == room.Room.building,
)
.count()
)
if room.DrawTime is None:
roomDict = {
"res_college": room.Room.res_college,
"building": room.Room.building,
"room_no": room.Room.room_no,
"occupancy": room.Room.occupancy,
"sq_footage": room.Room.sq_footage,
"favorite": room[2],
"room_id": room.Room.room_id,
"taken": room.Room.taken,
"number_of_reviews": review_count,
}
roomsList.append(roomDict)
else:
roomDict = {
"res_college": room.Room.res_college,
"building": room.Room.building,
"room_no": room.Room.room_no,
"occupancy": room.Room.occupancy,
"sq_footage": room.Room.sq_footage,
"favorite": room[2],
"room_id": room.Room.room_id,
"taken": room.Room.taken,
"number_of_reviews": review_count,
}
roomsList.append(roomDict)
i += 1
response = {
"recordsTotal": len(data),
"recordsFiltered": len(data),
"draw": 1,
"data": roomsList,
}
return jsonify(response)
@app.route("/queryfavorites", methods=["GET", "POST"])
def queryFavorites():
username = CASClient().authenticate()
username = username.lower().strip()
data = getFavoriteRooms(username)
roomsList = []
for room in data:
roomDict = {
"res_college": room.Room.res_college,
"building": room.Room.building,
"room_no": room.Room.room_no,
"occupancy": room.Room.occupancy,
"sq_footage": room.Room.sq_footage,
"favorite": room[2],
"room_id": room.Room.room_id,
"taken": room.Room.taken,
}
roomsList.append(roomDict)
response = {
"recordsTotal": len(data),
"recordsFiltered": len(data),
"draw": 1,
"data": roomsList,
}
return jsonify(response)
@app.route("/addtofavorites", methods=["GET", "POST"])
def addToFavorites():
# we should probably just pass this from the client rather than continually authenticating
# TODO
# and fix this in other places too.
username = CASClient().authenticate()
username = username.lower().strip()
room_id = request.args.get("room_id")
# ajax to add favorite
if request.method == "POST":
addFavorite(json.loads(request.get_data()), username)
else:
addFavorite(room_id, username)
# TODO - should this actually return something meaningful?
return "success"
@app.route("/removefromfavorites", methods=["GET", "POST"])
def removeFromFravorites():
# we should probably just pass this from the client rather than continually authenticating
# TODO
# and fix this in other places too.
username = CASClient().authenticate()
username = username.lower().strip()
room_id = request.args.get("room_id")
# ajax to remove favorite
if request.method == "POST":
removeFavorite(json.loads(request.get_data()), username)
else:
removeFavorite(room_id, username)
# TODO - should this actually return something meaningful?
return "success"
@app.route("/favorites", methods=["GET"])
def favorites():
username = CASClient().authenticate()
username = username.lower().strip()
# get all of the user's favorite
fav = allFavoriteRooms(username)
fav_headings = (
"BUILDING",
"ROOM NO.",
"OCCUPANCY",
"SQ. FOOTAGE",
"FAVORITE",
)
return render_template("favorites.html", headings=fav_headings, data=fav)
@app.route("/map")
def map():
# CASClient().authenticate()
allrank = defaultdict(int)
buildingrank = defaultdict(list)
maxrank = defaultdict(int)
minrank = defaultdict(int)
nolaundry = [
"Foulke",
]
dorms = [
"Butler College",
"Forbes College",
"Mathey College",
"Rockefeller College",
"Whitman College",
"First College",
"Upperclass",
]
for i in dorms:
data = allRooms("", i, "", "", "", "", "2019")
for room in data:
building = room.Room.building
buildingrank[building].append(int(room.DrawTime.draw_time))
for building in buildingrank:
allrank[building] = sum(buildingrank[building]) / len(buildingrank[building])
maxrank[building] = max(buildingrank[building])
minrank[building] = min(buildingrank[building])
# hardcoded colors for ncw and yeh, assuming buildings closer
# to the rest of campus are better. (we have no pick data for them)
# NCW
allrank["ADDY"] = 90
allrank["KANJI"] = 140
allrank["JONES"] = 240
allrank["FELICIANO"] = 290
# YEH
allrank["HARIRI"] = 90
allrank["FU"] = 140
allrank["GROUSBECK"] = 240
allrank["MANNION"] = 290
return make_response(
render_template(
"map.html",
allrank=allrank,
maxrank=maxrank,
minrank=minrank,
)
)
@app.route("/addgroup", methods=["GET", "POST"])
def addGroup():
data = json.loads(request.get_data())
username = data[2].strip()
data[0].append(username)
# add to groups
if request.method == "POST":
addNewGroup(data[0], data[1])
else:
addNewGroup(data[0], data[1])
# TODO - should this actually return something meaningful?
return "success"
@app.route("/logout", methods=["GET"])
def logout():
casClient = CASClient()
casClient.authenticate()
casClient.logout()
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
@app.route("/populategroups", methods=["GET"])
def populategroups():
username = CASClient().authenticate()
username = username.lower().strip()
groups = getUserGroups(username)
room_id = request.args.get("room_id", default="")
# need to return group name and list of rooms
groups_list = []
if groups != False:
for g_id, group_dict in groups.items():
data = {}
data["group_id"] = g_id
data["name"] = group_dict["name"]
room_ids_list = [r.room_id for r in group_dict["rooms"]]
data["favorited"] = True if int(room_id) in room_ids_list else False
groups_list.append(data)
return jsonify({"data": groups_list})
@app.route("/groups", methods=["GET", "POST"])
def groups():
username = CASClient().authenticate()
username = username.lower().strip()
groups = getUserGroups(username)
has_groups = True
if not groups:
has_groups = False
return make_response(
render_template("groups.html", has_groups=has_groups, groups=groups)
)
@app.route("/addroomtogroup", methods=["POST"])
def addroomtogroup():
data = json.loads(request.get_data())
room_id = data["room_id"]
group_id = data["group_id"]
username = data["username"]
addRoomToGroup(
username,
json.loads(request.get_data())["room_id"],
json.loads(request.get_data())["group_id"],
)
# TODO - should this actually return something meaningful?
return "yay"
@app.route("/removeroomfromgroup", methods=["POST"])
def removeroomfromgroup():
# we should probably just pass this from the client rather than continually authenticating
# TODO
# and fix this in other places too.
username = CASClient().authenticate()
username = username.lower().strip()
room_id = request.args.get("room_id")
group_id = request.args.get("group_id")
# ajax to add favorite
if request.method == "POST":
removeRoomFromGroup(
username,
json.loads(request.get_data())["room_id"],
json.loads(request.get_data())["group_id"],
)
else:
removeRoomFromGroup(username, room_id, group_id)
# TODO - should this actually return something meaningful?
return "yay"
@app.route("/deletegroup", methods=["GET"])
def deletegroup():
group_id = request.args.get("group_id")
success = deleteGroup(group_id)
# error handling? TODO
if success:
return "true!"
else:
return "true"
# @app.route("/update")
# def update():
# response = render_template("housing.html")
# return make_response(response)
# checks for 3 minutes after start is pressed
# @app.route("/start", methods=['GET'])
# def startRoomDraw():
# clearRoomStatuses()
# i = 0
# while i < 18:
# print("checking")
# checkRooms()
# i += 1
# time.sleep(10)
# print("done")
# return "success"
# @app.route("/checkonce", methods=['GET'])
# def checkOnce():
# print("here")
# checkRooms()
# print("here")
# return "success"
# @app.route("/changerooms", methods=['GET'])
# def changeHowRoomsDrew():
# status = request.args.get('status')
# changeRoomPdf(status)
# return "success"
# @app.route("/clearrooms", methods=['GET'])
# def clearRooms():
# os.remove("static/pdfs/howroomsdrew.pdf")
# clearRoomStatuses()
# changeRoomPdf("reset")
# return "success"
@app.route("/isuserstudent", methods=["GET"])
def isuserstudent():
username = request.args.get("username")
if username is None:
return "False"
is_student = check_is_undergrad(username)
if is_student:
return "True"
return "False"
@app.route("/editgroup", methods=["POST"])
def editGroup():
data = json.loads(request.get_data())
group_id = data["group_id"]
group_name = data["group_name"]
members = data["members"]
editGroupInfo(group_id, group_name, members)
return "True"
@app.route("/getgroupsjson", methods=["GET"])
def getGroupsJSON():
username = CASClient().authenticate()
username = username.lower().strip()
groups = getUserGroupsJSON(username)
username = username.strip()
has_groups = True
if len(groups) == 0:
has_groups = False
return jsonify(
{
"groups": groups,
"has_groups": has_groups,
"username": username,
}
)
@app.route("/submitReview", methods=["POST"])
def submit_review():
# username = "proxy"
username = CASClient().authenticate()
valid_ratings = ["0", "1", "2", "3", "4", "5"]
building_name = request.form["building-name"]
room_no = request.form["room-number"]
overall_rating = request.form["overall-rating"]
written_review = request.form["written-review"]
override = request.form["override"]
# first_checkbox = request.form.getlist('submission-check-1')
second_checkbox = request.form.getlist("submission-check-2")
if overall_rating not in valid_ratings:
message = (
"Your review rating was not between 0 and 5. Please submit again with"
" a valid rating."
)
return jsonify(message=message), 400
if written_review.strip() == "":
message = "You cannot leave your review empty. Please submit a review with a minimum length of 100 characters."
return jsonify(message=message), 400
if len(written_review) < 100:
message = "Please submit a review with a minimum length of 100 characters."
return jsonify(message=message), 400
if len(written_review) > 5000:
message = "Please submit a review with a length of less than 5000 characters."
return jsonify(message=message), 400
if len(second_checkbox) == 0:
message = (
"Be sure to check the condition that your Princeton netID"
" will be shown alongside your review."
)
return jsonify(message=message), 400
if clean_html(written_review):
message = "Your review contains HTML tags. Please remove them before submitting your review again."
return jsonify(message=message), 400
# restrict user to one review per room
user_search = db_session.query(Reviews).filter(
Reviews.building_name == building_name,
Reviews.room_number == room_no,
Reviews.net_id == username,
)
if user_search.first() and override == "no":
message = "override"
return jsonify(message=message), 400
if user_search.first() and override == "yes":
user_search.update(
{
"date": datetime.datetime.utcnow(),
"rating": int(overall_rating),
"content": written_review,
},
synchronize_session=False,
)
db_session.commit()
message = "Your review was successfully overridden!"
return jsonify(message=message), 200
review = Reviews(
building_name=building_name,
room_number=room_no,
rating=int(overall_rating),
content=written_review,
net_id=username,
)
db_session.add(review)
db_session.commit()
message = "Your review was successfully submitted!"
return jsonify(message=message), 200
def clean_html(raw_html):
import re
html_tags = re.findall("<.*?>", raw_html)
return html_tags