generated from Code-Institute-Org/gitpod-full-template
/
app.py
583 lines (490 loc) · 23.9 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
572
573
574
575
576
577
578
579
580
581
582
583
import os
import datetime
import googlemaps
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import date
from datetime import datetime
from datetime import timedelta
from helpers import determine_user_level
if os.path.exists("env.py"):
import env
app = Flask(__name__)
app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME")
app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
app.secret_key = os.environ.get("SECRET_KEY")
mongo = PyMongo(app)
gmaps = googlemaps.Client(key="AIzaSyAh2mLYzYzAmAWbN_OUY9CksCHUJm82WWg")
timestamp = datetime.now()
createdon = timestamp.strftime("%d/%m/%Y, %H:%M:%S")
createdondate = timestamp.strftime("%d/%m/%Y")
days_in_year = 365.2425
@app.route("/")
@app.route("/register", methods=["GET", "POST"])
def register():
""" renders register page with input for e-mail address, a choose password input,
and a confirm password input """
if request.method == "POST":
existing_user = mongo.db.users.find_one(
{"email": request.form.get("email").lower()})
if existing_user:
flash("That e-mail address is already in use!",
"registeremailerror")
return redirect(url_for("register"))
password1 = request.form.get("password1")
password2 = request.form.get("password2")
if password1 != password2:
flash("Passwords do not match!", "registerpassworderror")
return redirect(url_for("register"))
register = {
"email": request.form.get("email").lower(),
"password": generate_password_hash(request.form.get("password1")),
"membersince": createdondate
}
mongo.db.users.insert_one(register)
session["user"] = request.form.get("email").lower()
flash("Please fill out the form below so we can provide you with an optimal application experience.",
"completeprofilemessage")
return redirect(url_for("edit_profile", user=session["user"]))
return render_template("register.html", isRegister=True)
@app.route("/login", methods=["GET", "POST"])
def login():
""" renders login page with input to fill in login credentials """
if request.method == "POST":
existing_user = mongo.db.users.find_one(
{"email": request.form.get("email").lower()})
if existing_user:
if check_password_hash(
existing_user["password"], request.form.get("password1")):
session["user"] = request.form.get("email").lower()
return redirect(url_for("show_map", user=session["user"]))
else:
flash("The password is not correct!", "loginpassworderror")
return redirect(url_for("login"))
else:
flash("This e-mail address has not been registered yet!",
"loginemailerror")
return redirect(url_for("login"))
return render_template("login.html", isLogin=True)
@app.route("/map")
def show_map():
""" renders map with future runs based on users location and
checks if current user is found in participantlist of each run """
try:
if session["user"]:
user = mongo.db.users.find_one({"email": session['user']})
runs = list(mongo.db.runs.find({
"$and": [
{"city": user['location']},
{"timestamp": {
"$gte": datetime.today()}}
]
}).sort("timestamp", 1))
for run in runs:
for participant in run['participants']:
if session['user'] == participant['email']:
run['isCurrentUser'] = True
if 'isCurrentUser' not in run:
run['isCurrentUser'] = False
return render_template("map.html", runs=runs, user=user)
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/search", methods=["GET", "POST"])
def search():
""" renders map and runs based on search criteria """
try:
if session["user"]:
if request.method == "POST":
querylocation = request.form.get("location")
formmindate = request.form.get("mindate")
querymindate = datetime.strptime(formmindate, "%Y-%m-%d")
formmaxdate = request.form.get("maxdate")
querymaxdate = datetime.strptime(
formmaxdate, "%Y-%m-%d") + timedelta(days=1)
querymindistance = int(request.form.get("mindistance"))
querymaxdistance = int(request.form.get("maxdistance"))
runs = list(mongo.db.runs.find({
"$and": [
{"city": querylocation},
{"$and": [{"timestamp": {"$gte": querymindate}},
{"timestamp": {"$lte": querymaxdate}}]},
{"$and": [{"intdistance": {"$gte": querymindistance}},
{"intdistance": {"$lte": querymaxdistance}}]}
]
}).sort("timestamp", 1))
if len(runs) == 0:
flash("No runs found with such criteria",
"mainwindowmessage")
return redirect(url_for("show_map", user=session["user"]))
else:
user = mongo.db.users.find_one({"email": session['user']})
flash("Filter Active", "mainwindowmessage")
return render_template("searchresults.html", runs=runs,
user=user, isActiveFilter=True)
user = mongo.db.users.find_one({"email": session['user']})
runs = list(mongo.db.runs.find({
"$and": [
{"city": user['location']},
{"timestamp": {
"$gte": datetime.today()}}
]
}).sort("timestamp", 1))
return render_template("search.html", runs=runs, user=user,
isActiveFilter=False)
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/add_run", methods=["GET", "POST"])
def add_run():
""" renders add run form, adds a run to the database based on inputform
& translates the location to coordinates for use on the map """
try:
if session["user"]:
if request.method == "POST":
levelrestriction = "on" if request.form.get(
"levelrestriction") else "off"
formrundate = request.form.get("date")
rundate = datetime.strptime(formrundate, "%Y-%m-%d")
rundatestring = rundate.strftime("%d-%m-%Y")
formruntime = "{}:{}".format(request.form.get(
"hour"), request.form.get("minute"))
runtime = datetime.strptime(formruntime, "%H:%M")
runtimestring = runtime.strftime("%H:%M")
runtimestamp = datetime.strptime(
rundatestring + ", " + runtimestring, "%d-%m-%Y, %H:%M")
runcity = request.form.get("city")
runcity_geocode_result = gmaps.geocode(runcity)
runcitylat = runcity_geocode_result[0]["geometry"]["location"]["lat"]
runcitylng = runcity_geocode_result[0]["geometry"]["location"]["lng"]
meetingpoint = request.form.get(
"location") + ", " + request.form.get("city")
meetingpoint_geocode_result = gmaps.geocode(meetingpoint)
meetingpointlat = meetingpoint_geocode_result[0]["geometry"]["location"]["lat"]
meetingpointlng = meetingpoint_geocode_result[0]["geometry"]["location"]["lng"]
participant = mongo.db.users.find_one({"email": session['user']}, {
"_id": 1,
"firstname": 1,
"lastname": 1,
"initials": 1,
"email": 1})
creatorrunninglevel = mongo.db.users.find_one(
{"email": session['user']}).get('userlevel')
distance = int(request.form.get("distance")[:2])
run = {
"level": creatorrunninglevel,
"formrundate": formrundate,
"date": rundatestring,
"time": runtimestring,
"hour": request.form.get("hour"),
"minute": request.form.get("minute"),
"timestamp": runtimestamp,
"location": request.form.get("location"),
"city": request.form.get("city"),
"runcitylat": runcitylat,
"runcitylng": runcitylng,
"meetingpointlat": meetingpointlat,
"meetingpointlng": meetingpointlng,
"distance": request.form.get("distance"),
"intdistance": distance,
"levelrestriction": levelrestriction,
"createdby": session["user"],
"createdon": createdon,
"participants": [participant]
}
if runtimestamp.date() < date.today():
flash("Please make sure your run is in the future",
"mainwindowmessage")
return redirect(url_for("add_run"))
mongo.db.runs.insert_one(run)
flash("Run added succesfully", "mainwindowmessage")
return redirect(url_for("show_map"))
user = mongo.db.users.find_one({"email": session['user']})
runs = list(mongo.db.runs.find({
"$and": [
{"city": user['location']},
{"timestamp": {
"$gte": datetime.today()}}
]
}).sort("timestamp", 1))
return render_template("addrun.html", runs=runs, user=user)
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/expandrun/<run_id>", methods=["GET", "POST"])
def expand_run(run_id):
""" renders expand run which is used to dipslay run details on mobile version """
run = mongo.db.runs.find_one({"_id": ObjectId(run_id)})
id = run.get('_id')
user = mongo.db.users.find_one({"email": session['user']})
runs = list(mongo.db.runs.find({
"$and": [
{"city": user['location']},
{"timestamp": {"$gte": datetime.today()}}
]
}).sort("timestamp", 1))
for participant in run['participants']:
if session['user'] == participant['email']:
run['isCurrentUser'] = True
if 'isCurrentUser' not in run:
run['isCurrentUser'] = False
return render_template("expandrun.html", run=run, id=id, runs=runs, user=user)
@app.route("/join_run/<run_id>", methods=["GET", "POST"])
def join_run(run_id):
""" adds user to particular run, checks for level restriction, compares
active user to the particular run level if level restriction is active """
try:
if session["user"]:
participant = mongo.db.users.find_one({"email": session['user']}, {
"_id": 1,
"firstname": 1,
"lastname": 1,
"initials": 1,
"email": 1,
"userlevel": 1})
run = mongo.db.runs.find_one({"_id": ObjectId(run_id)})
if run['levelrestriction'] == "on":
if run['level'] == participant['userlevel']:
flash("You have been added to the participtantslist",
"mainwindowmessage")
mongo.db.runs.update_one(
{"_id": ObjectId(run_id)},
{"$push": {"participants": participant}})
else:
flash("Only people from the same level can attend this run",
"mainwindowmessage")
return redirect(url_for("show_map"))
else:
flash("You have been added to the participtantlist",
"mainwindowmessage")
mongo.db.runs.update_one(
{"_id": ObjectId(run_id)},
{"$push": {"participants": participant}})
return redirect(url_for("show_map"))
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/leave_run/<run_id>", methods=["GET", "POST"])
def leave_run(run_id):
""" removes a user from a runs participant list """
try:
if session["user"]:
participant = mongo.db.users.find_one({"email": session['user']}, {
"_id": 1,
"firstname": 1,
"lastname": 1,
"initials": 1,
"email": 1})
mongo.db.runs.update_one(
{"_id": ObjectId(run_id)},
{"$pull": {"participants": participant}}
)
flash("You have been removed from the participtantlist",
"mainwindowmessage")
return redirect(url_for("show_map"))
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/edit_run/<run_id>", methods=["GET", "POST"])
def edit_run(run_id):
""" edits a run based on the input of the edit run form,
parses text time into actual timestamp & translates the locations
to coordinates for use on the map """
try:
if session["user"]:
if request.method == "POST":
levelrestriction = "on" if request.form.get(
"levelrestriction") else "off"
formrundate = request.form.get("date")
rundate = datetime.strptime(formrundate, "%Y-%m-%d")
rundatestring = rundate.strftime("%d-%m-%Y")
formruntime = "{}:{}".format(request.form.get(
"hour"), request.form.get("minute"))
runtime = datetime.strptime(formruntime, "%H:%M")
runtimestring = runtime.strftime("%H:%M")
runtimestamp = datetime.strptime(
rundatestring + ", " + runtimestring, "%d-%m-%Y, %H:%M")
runcity = request.form.get("city")
runcity_geocode_result = gmaps.geocode(runcity)
runcitylat = runcity_geocode_result[0]["geometry"]["location"]["lat"]
runcitylng = runcity_geocode_result[0]["geometry"]["location"]["lng"]
meetingpoint = request.form.get(
"location") + ", " + request.form.get("city")
geocode_result = gmaps.geocode(meetingpoint)
meetingpointlat = geocode_result[0]["geometry"]["location"]["lat"]
meetingpointlng = geocode_result[0]["geometry"]["location"]["lng"]
participant = mongo.db.users.find_one({"email": session['user']}, {
"_id": 1,
"firstname": 1,
"lastname": 1,
"initials": 1,
"email": 1})
creatorrunninglevel = mongo.db.users.find_one(
{"email": session['user']}).get('userlevel')
distance = int(request.form.get("distance")[:2])
editrun = {
"level": creatorrunninglevel,
"formrundate": formrundate,
"date": rundatestring,
"time": runtimestring,
"hour": request.form.get("hour"),
"minute": request.form.get("minute"),
"timestamp": runtimestamp,
"location": request.form.get("location"),
"city": request.form.get("city"),
"runcitylat": runcitylat,
"runcitylng": runcitylng,
"meetingpointlat": meetingpointlat,
"meetingpointlng": meetingpointlng,
"distance": request.form.get("distance"),
"intdistance": distance,
"levelrestriction": levelrestriction,
"createdby": session["user"],
"createdon": createdon,
"participants": [participant]
}
if runtimestamp.date() < date.today():
flash("Please make sure your run is scheduled in the future",
"mainwindowmessage")
return redirect(url_for("edit_run", run_id=run_id))
mongo.db.runs.update({"_id": ObjectId(run_id)}, editrun)
flash("Run was succesfully updated", "mainwindowmessage")
return redirect(url_for("show_map"))
user = mongo.db.users.find_one({"email": session['user']})
run = mongo.db.runs.find_one({"_id": ObjectId(run_id)})
runs = list(mongo.db.runs.find({
"$and": [
{"city": user['location']},
{"timestamp": {
"$gte": datetime.today()}}
]
}).sort("timestamp", 1))
return render_template("editrun.html", run=run, runs=runs, user=user)
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/delete_run/<run_id>")
def delete_run(run_id):
""" renders a remove confirmation for that particular run """
try:
if session["user"]:
run = mongo.db.runs.find_one({"_id": ObjectId(run_id)})
runs = list(mongo.db.runs.find(
{"timestamp": {"$gte": datetime.today()}}).sort("timestamp", 1))
user = mongo.db.users.find_one({"email": session['user']})
return render_template("deleterun.html", run=run, runs=runs, user=user)
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/permanently_delete_run/<run_id>")
def permanently_delete_run(run_id):
""" permanently deletes a run """
try:
if session["user"]:
mongo.db.runs.remove({"_id": ObjectId(run_id)})
flash("Run was removed permanently", "mainwindowmessage")
return redirect(url_for("show_map"))
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/profile/<user>", methods=["GET", "POST"])
def profile(user):
""" renders active user profile """
try:
if session["user"] == user:
genders = mongo.db.genders.find()
user = mongo.db.users.find_one({"email": user})
return render_template("profile.html",
user=user, genders=genders)
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/edit_profile/<user>", methods=["GET", "POST"])
def edit_profile(user):
""" renders edit profile page, updates the user in the database,
translates user location to coordinates to set map location """
try:
if session["user"] == user:
if request.method == "POST":
formdob = "{}-{}-{}".format(request.form.get("birthday"), request.form.get(
"birthmonth"), request.form.get("birthyear"))
dob = datetime.strptime(formdob, "%d-%m-%Y")
dobstring = dob.strftime("%d/%m/%Y")
age = int((date.today() - dob.date()).days / days_in_year)
formbesttime = "{}:{}:{}".format(
request.form.get("hours"),
request.form.get("minutes"),
request.form.get("seconds"))
besttime = datetime.strptime(formbesttime, "%H:%M:%S")
besttimestring = besttime.strftime("%H:%M:%S")
userlevel = determine_user_level(age, besttime)
initials = request.form.get("firstname")[
0] + request.form.get("lastname")[0]
userlocation = request.form.get("location")
geocode_result = gmaps.geocode(userlocation)
userlocationlat = geocode_result[0]["geometry"]["location"]["lat"]
userlocationlng = geocode_result[0]["geometry"]["location"]["lng"]
completeprofile = {
"firstname": request.form.get("firstname"),
"lastname": request.form.get("lastname"),
"initials": initials,
"dateofbirth": dobstring,
"birthday": request.form.get("birthday"),
"birthmonth": request.form.get("birthmonth"),
"birthyear": request.form.get("birthyear"),
"gender": request.form.get("gender"),
"location": request.form.get("location"),
"userlocationlat": userlocationlat,
"userlocationlng": userlocationlng,
"besttime": besttimestring,
"hours": request.form.get("hours"),
"minutes": request.form.get("minutes"),
"seconds": request.form.get("seconds"),
"userlevel": userlevel,
}
mongo.db.users.update_one(
{"email": user}, {"$set": completeprofile})
flash("Your profile was successfully updated",
"mainwindowmessage")
return redirect(url_for("show_map", user=session["user"]))
genders = mongo.db.genders.find()
user = mongo.db.users.find_one({"email": user})
return render_template("editprofile.html",
user=user, genders=genders)
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/delete_profile/<user>")
def delete_profile(user):
""" renders a template to confirm user deletion """
try:
if session["user"] == user:
user = mongo.db.users.find_one({"email": user})
return render_template("deleteprofile.html",
user=user)
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/permanently_delete_profile/<user>")
def permanently_delete_profile(user):
""" permanently deletes the user from the database """
try:
if session["user"] == user:
mongo.db.users.remove({"email": user})
return redirect(url_for("register"))
except:
return render_template("login.html", isLogin=True)
return render_template("login.html", isLogin=True)
@app.route("/logout")
def logout():
""" logs out the active user """
session.pop("user")
return redirect(url_for("login"))
if __name__ == "__main__":
app.run(host=os.environ.get("IP"),
port=int(os.environ.get("PORT")),
debug=False)