-
Notifications
You must be signed in to change notification settings - Fork 0
/
webapp.py
1063 lines (824 loc) · 34.5 KB
/
webapp.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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from RequestCalendar import app
import time,os.path, sqlite3, datetime, calendar, re
from flask import Flask, render_template, request, redirect, url_for, session, g, jsonify
from werkzeug import check_password_hash, generate_password_hash
from jinja2 import evalcontextfilter, Markup, escape
if app.config['USE_EMAIL']:
from flask.ext.mail import Mail, Message
from RequestCalendar import mail
MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
MONTHLEN = [31,28,31,30,31,30,31,31,30,31,30,31]
WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
## months go 0-11, and index directly the other data
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
## days[] is an array of fixed length 42, including all the days of the current month,
## as well as buffers from other months to make up 42, can can be made using
## month length and start day
#### ## ## ######## ######## ## ##
## ### ## ## ## ## ## ##
## #### ## ## ## ## ## ##
## ## ## ## ## ## ###### ###
## ## #### ## ## ## ## ##
## ## ### ## ## ## ## ##
#### ## ## ######## ######## ## ##
@app.route('/', methods=['POST', 'GET'])
def index():
today = datetime.date.today()
if 'month' in session:
month = session.get('month')
else:
month = today.month-1
session['month'] = month
if 'year' in session:
year = session.get('year')
else:
year = today.year
session['year'] = year
monthName = MONTHS[month]
days = genDays(month, year)
if month == today.month-1 and year == today.year:
todayDate = today.day
else:
todayDate = None
login = getLogin()
## events is then a dict, containing list of dates with pending and list of those with confirm
return render_template("index.html", year=year, month=monthName, days=days, today=todayDate, events=get_monthEvents(month, year), login=login)
#{'pend':[20, 22, 23, 30], 'conf':[1, 12, 17, 19, 21]}
######## ### ## ## #### ## ## ######## #######
## ## ## ## ## ## ## ### ## ## ## ##
## ## ## ## #### ## #### ## ## ## ##
## ## ## ## ## ## ## ## ## ###### ## ##
## ## ######### ## ## ## #### ## ## ##
## ## ## ## ## ## ## ### ## ## ##
######## ## ## ## #### ## ## ## #######
@app.route('/dayInfo', methods=['POST', 'GET'])
def dayInfo():
showInfo = None
if request.method == 'POST':
print ">>> dayInfo loading from POST"
## Request dict comes as {'dayMon': day#month}
showInfo = request.form.get('dayMon').split('#')
print ">>> dayInfo: 'showInfo' = ", showInfo
session['dayInfo'] = showInfo
##also store most request requst into session for resuming
elif "dayInfo" in session:
print ">>> dayInfo loading from session"
showInfo = session['dayInfo']
print "DAY INFO"
if showInfo is not None:
year = int(session.get('year', datetime.date.today().year))
day, month = showInfo
day = int(day)
monthNum = MONTHS.index(month)
print ">>> DayInfo, y{}, m{}, d{}".format(year, monthNum, day)
##monthnum+1 used as months are handled 0-11 here but 1-12 in datetime
date = datetime.date(year, monthNum+1, day)
weekday = WEEKDAYS[date.weekday()]
past = date < datetime.date.today()
if session.get('logged_in', 0):
login = (1, session.get('username', "NAMENOTFOUND"))
else:
login = (0, None)
dayData = get_dayData(day, monthNum, year)
#(eventClaimer, eventDescription, eventConfirms, eventDenies)
##init template vars to None
claimer = None
if dayData is not None:
##the username of the claimer, the description of the event
##and two lists of usernames of those confirmed and denied
# and only others from userList will be "pending"
##there should be no overlap between confirm and deny lists
# should be checked when status is changed.
# but confirm takes presidence if there is overlap
claimer, eventDescription, eventConfirms, eventDenies = dayData
eventConfirms = eventConfirms.split(',')
eventDenies = eventDenies.split(',')
userStati = [] #preserve stati for overall status calculation
## Get a list of users
if hasattr(g, 'userList'):
userList = g.userList
else:
userList = get_userList()
g.userList = userList
##remove creator and admin from list
for name in [claimer, 'Admin']:
try:
userList.remove(name)
except ValueError:
print "user list removal value error"
print userList
## special condition if claimer is logged in, claimer = "You", can be tested for in template jinja
## if creator isnt logged in, remove that user from userlist too and create special storage for that
user = None
if login[0]:
if login[1] == claimer: ## login check already occurred
claimer = "You"
elif login[1] != "Admin":
userList.remove(login[1])
if login[1] in eventDenies:
user = ("Denied", -1)
userStati.append(-1)
elif login[1] in eventConfirms:
user = ("Confirmed", 1)
userStati.append(1)
else:
user = ("Pending", 0)
userStati.append(0)
## Now edit this list of those that have confirmed
confNameList = []
for name in userList:
if name in eventDenies:
status = -1
elif name in eventConfirms:
status = 1
else:
status = 0
confNameList.append((name, status))
userStati.append(status)
## the overall status of the event,
# if 1 or more denied, status = -1, denied
# elif 1 or more pending, status = 0, pending
# elif all confirmed, status = 1, confirmed
if -1 in userStati:
requestStatus = ("Denied", -1)
elif 0 in userStati:
requestStatus = ("Pending", 0)
else:
requestStatus = ("Confirmed", 1)
updateEventStatus(day, monthNum, year, requestStatus[1])
dayData = eventDescription, confNameList, user, requestStatus
## template uses claimer=="You" to check if request is selfmade or not but can just use {{ claimer }}
return render_template("dayInfo.html", day=day, month=(monthNum, month), year=year, weekday=weekday, claimer=claimer, dayData=dayData, login=login, past=past)
return redirect(url_for("index"))
@app.route('/dayInfo_show/<year>/<month>/<day>')
def dayInfo_show(year, month, day):
##because dayInfo uses post or a varsaved in session to get day month and year,
##so load this into session and then redirect to dayInfo
print ">>> dayInfo_show: d{}, m{}, y{}".format(day, month, year)
showInfo = [day, month]
session['dayInfo'] = showInfo
session['year'] = year
return redirect(url_for('dayInfo'))
@app.route('/dayInfoUpdate/<year>/<month>/<day>/<user>/<status>')
def dayInfoUpdate(year, month, day, user, status):
print "DayInfoUpdate", year, month, day, user, status
##check event isnt in the past:
past = datetime.date(int(year), int(month), int(day)) < datetime.date.today()
if past:
print ">>> dayInfoUpdate: update request made for past date, ignoring"
else:
updateUserEventStatus(day, month, year, user, status)
return redirect(url_for('dayInfo'))
######## ######## ###### #### ## ## ######## #######
## ## ## ## ## ## ### ## ## ## ##
## ## ## ## ## #### ## ## ## ##
######## ###### ###### ## ## ## ## ###### ## ##
## ## ## ## ## ## #### ## ## ##
## ## ## ## ## ## ## ### ## ## ##
## ## ######## ###### #### ## ## ## #######
@app.route('/resInfo')
def resInfo():
##resource info, serves page with customised info on the shared resource
image = app.config.get('IMAGE_FILENAME', None)
descFile = app.config.get('RES_DESCRIPTION')
fileLocation = os.path.join(os.getcwd(), "RequestCalendar", "static", "resource", descFile)
print ">>> resInfo, fileLocation: ", fileLocation
try:
print ">>> resInfo, file is real, reading"
desc = ""
with app.open_resource('static/resource/'+ descFile, "r") as f:
for line in f:
#desc += "<p>" + line + "</p>"
desc += line + "\n"
print ">>> resInfo, desc: ", desc
except Exception as e:
desc = None
print ">>> resInfo, no description, E: ", e
return render_template('resInfo.html', login=getLogin(), image=image, desc=desc)
@app.template_filter()
@evalcontextfilter
def nl2br(eval_ctx, value):
result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n')) \
for p in _paragraph_re.split(escape(value)))
if eval_ctx.autoescape:
result = Markup(result)
return result
## ## ####### ## ## ######## ## ## ## ## ### ## ##
### ### ## ## ### ## ## ## ## ### ## ## ## ## ##
#### #### ## ## #### ## ## ## ## #### ## ## ## ## ##
## ### ## ## ## ## ## ## ## ######### ####### ## ## ## ## ## ## ##
## ## ## ## ## #### ## ## ## ## #### ######### ## ##
## ## ## ## ## ### ## ## ## ## ### ## ## ## ##
## ## ####### ## ## ## ## ## ## ## ## ## ###
@app.route('/prevMonth')
def prevMonth():
prevMonth = session.get('month', datetime.date.today().month-1) -1
if prevMonth < 0: ##wrap
prevMonth += 12
prevYear = session.get('year', datetime.date.today().year) - 1
print ">>> previous year: ", prevYear
session['year'] = prevYear
session['month'] = prevMonth
return redirect(url_for('index'))
@app.route('/nextMonth')
def nextMonth():
nextMonth = session.get('month', datetime.date.today().month-1) + 1
if nextMonth > 11: ##wrap
nextMonth -= 12
nextYear = session.get('year', datetime.date.today().year) + 1
print ">>> nextYear ", nextYear
session['year'] = nextYear
session['month'] = nextMonth
return redirect(url_for('index'))
@app.route('/currMonth')
def currMonth():
##return to current month
currentMonth = datetime.date.today().month - 1
currentYear = datetime.date.today().year
session['month'] = currentMonth
session['year'] = currentYear
return redirect(url_for('index'))
@app.route('/addRequest', methods=["POST", "GET"])
def addRequest():
login = getLogin()
if request.method == "POST" and login[0] and \
"dmy" in request.form and 'desc' in request.form:
day, month, year = request.form.get('dmy').split('#')
desc = request.form.get('desc')
print ">>> d:{} m:{} y:{} \nDescription: {}".format(day, month, year, desc)
add_MonthEvent(day, month, year, login[1], desc)
print ">>> EVENT SHOULD HAVE BEEN ADDED"
return redirect(url_for('dayInfo'))
@app.route('/deleteRequest/<year>/<month>/<day>', methods=["POST", "GET"])
def deleteRequest(year, month, day):
login = getLogin()
if login[0] and login[1] == "Admin":
print ">>> deleteRequest: deleteing on y{} m{} d{}".format(year, month, day)
delete_Request(year, month, day)
return redirect(url_for('dayInfo'))
######## ### ## ## ######## ## ######
## ## ## ## ### ## ## ## ## ##
## ## ## ## #### ## ## ## ##
######## ## ## ## ## ## ###### ## ######
## ######### ## #### ## ## ##
## ## ## ## ### ## ## ## ##
## ## ## ## ## ######## ######## ######
@app.route('/userPanel', methods=['GET', 'POST'])
def userPanel():
login = getLogin()
if login[0] == 0:
return redirect(url_for('index'))
## only logged in from this point
email = get_userSettings(login[1])
if email is None:
notifSettings = ""
else:
email, notifSettings = email
##user can customise notification settings if email is entered,
# and change name and password - maybe not name, that may cause issues though
if request.method == "GET":
return render_template('userPanel.html', login=login, notifSettings=notifSettings, email=email)
elif request.method == "POST":
print ">>> userPanel", request.form
if "email" in request.form:
email = request.form.get('email')
set_userEmail(email, login[1])
elif "notificationSettings" in request.form:
notifSettings = "".join(request.form.getlist('notif'))
set_userNotifSetting(notifSettings, login[1])
elif "password" in request.form:
password = request.form.get('password')
change_Password(login[1], password)
return render_template('userPanel.html', login=login, notifSettings=notifSettings, email=email)
## ## ## ## ######## ######## ####### ## ## ######## ###### ######## ######
### ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#### #### #### ## ## ## ## ## ## ## ## ## ## ##
## ### ## ## ######## ###### ## ## ## ## ###### ###### ## ######
## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ######## ##### ## ####### ######## ###### ## ######
@app.route('/userPanel/myRequests')
def myRequests():
## A page to show all requests by user. Will be split into a hidden list of past requests and a visible list of
## future/present ones, each with links so said dayInfo
login = getLogin()
if login[0] == 0:
return redirect(url_for('index'))
userRequests = get_userRequests(login[1])
#[(dayNum, monthNum, yearNum, eventStatus), ...]
today = datetime.date.today()
## now filter for past events
pastRequests = []
futureRequests = []
for request in userRequests:
##YEAR
## if year < this year, must be in past
if request[2] < today.year:
past = True
## if year > this year, must be in future
elif request[2] < today.year:
past = False
##now it must be this year, we can check using months now
##MONTH
# today.month must be -1 to account for 1-12 or 0-11 difference
## and earlier month in this year
elif request[1] < today.month-1:
past = True
# a later month in this year
elif request[1] > today.month-1:
past = False
##now it must be this month, check finaly to days
##DAY
## just check if day is less than current, so is in past
elif request[0] < today.day:
past = True
## finally drop it to future
else:
past = False
#now add to split lists modify month and status to strings
status = ['Denied', 'Pending', 'Confirmed'][request[3]+1]
request = [request[0], MONTHS[request[1]], request[2], (request[3], status)]
if past:
pastRequests.append(request)
else:
futureRequests.append(request)
##We now have two lists of events
return render_template('myRequests.html',login=login,pastRequests=pastRequests,futureRequests=futureRequests)
@app.route('/helpPanel')
def helpPanel():
login = getLogin()
return render_template('helpPanel.html', login=login, adminEmail=app.config.get("ADMIN_EMAIL", None))
@app.route('/adminPanel', methods=['GET', 'POST'])
def adminPanel():
## can only access if logged in as admin
if session.get('logged_in') and session.get('username') == "Admin":
error = None
message = None
## List of users, with ability to delete or add
## And password change ability (maybe)
userList = get_userList()
##
if request.method == "POST":
print request.form
## posted admin function:
# add User, delete user, change user password
# request form comes as: {'addUser': Random string, ...(function specific entries) }
# or: {'deleteUser': Random String, ...(function specific entries) }
funct = request.form.keys()
if 'addUser' in funct:
print "\nADD USER FORM SUBMIT\n"
newUser = request.form.get('newUser')
if newUser == "":
error = "Username cannot be blank"
else:
newUser = newUser[0].upper() + newUser[1:]
if len(newUser.split(' ')) > 1:
error = "Username cannot have spaces"
elif newUser in userList:
error = "User already Exists"
else:
newPass = request.form.get('newPass')
if newPass == "":
error = "Password cannot be blank"
else:
print "\nAdding user: ", newUser, " with password: ", newPass, "\n"
message = add_User(newUser, newPass) #also checks for user duplication but that's fine
userList = get_userList()
elif 'delUser' in funct:
delUser = request.form.get('delUser')
if delUser not in userList:
error = "user not found in userList, something went wrong"
elif delUser == "Admin":
error = "Cannot delete Admin account"
else:
message = del_User(delUser)
userList = get_userList()
elif 'changePass' in funct:
changeUser = request.form.get('changePass')
newPass = request.form.get('newPass')
if newPass == "":
error = "Password cannot be blank"
else:
print "user: ", changeUser, "new password: ", newPass
message = change_Password(changeUser, newPass)
userList.remove("Admin") ##final removal of admin, does not need to be sent into template, already hard coded
return render_template('adminPanel.html', error=error, message=message, userList=userList, login=(1, session.get('username', "NAMENOTFOUND")))
else:
return redirect(url_for('index'))
## ####### ###### #### ## ##
## ## ## ## ## ## ### ##
## ## ## ## ## #### ##
## ## ## ## #### ## ## ## ##
## ## ## ## ## ## ## ####
## ## ## ## ## ## ## ###
######## ####### ###### #### ## ##
@app.route('/login', methods=['GET', 'POST'])
def login():
print "Login page"
issue = None
logged_in = None
user = None #stores the previous attempted name for if password is incorrect
if session.get("logged_in"):
logged_in = session.get('username', "USERNAME NOT FOUND")
if request.method == 'POST':
print "LOGIN POST"
userDict = get_userDict()
#{user:passhash}
user = request.form['username']
user = user[0].upper() + user[1:]
password = request.form['password']
if user in userDict.keys():
if check_password_hash(userDict[user], password):
print "logged in"
session['logged_in'] = True
session['username'] = user
return redirect(url_for('index'))
else:
issue = "Password Incorrect"
else:
issue = "Username Not Found"
return render_template('loginPage.html', error=issue, logged_in=logged_in, prevName=user)
@app.route('/logout')
def logout():
session.pop('logged_in', None)
session['username'] = None
return redirect(url_for('index'))
def getLogin():
if session.get('logged_in', 0):
return (1, session.get('username', "NAMENOTFOUND"))
else:
return (0, None)
#
# mMm mMm m
# mMmMm mMmMm m
# mMm mMm mMm mMm m
# mMm mMm mMm mMm m
# mMm mMmMm mMm M m M
# mMm mMm mMm M m M
# mMm mMm M m M
# mMm mMm M
# Mobile functionality has been posponed and layout has been tweaked to work well on mobile browsers instead of via a custom app
# This may be added in the future
# ## MOBILE INTERFACE FUNCTIONS
# @app.route('/m/dayInfo', methods=["POST"])
# def DayInfo_M():
# print ">>> DayInfo_M", request.form
# day = int(request.form.get('day'))
# month = int(request.form.get('month'))
# year = int(request.form.get('year'))
# dayData = get_dayData(day, month, year)
# #(eventClaimer, eventDescription, eventConfirms, eventDenies)
# if dayData is None:
# return jsonify(day=None)
# else:
# ## split confirms and denies to lists, filter out any "" strings from stray commas
# print dayData[2]
# confirms = filter(lambda a: a!="", dayData[2].split(","))
# print confirms
# denies = filter(lambda a: a!="", dayData[3].split(","))
# ## return all the information the app needs to form the page
# return jsonify({
# "claimer": dayData[0],
# "description": dayData[1],
# "confirms": confirms,
# "denies": denies
# })
def genDays(month, year):
## correct with month+1 as datetime uses 1-12 not 0-11
print">>> genDays: m{} - y{}".format(month, year)
firstDay = datetime.date(int(year), int(month)+1, 1).weekday()
days = range(1, MONTHLEN[month]+1)
if firstDay != 0:
prevMon = range(1, MONTHLEN[month-1]+1)[-firstDay:] #truncated list of end of previous month
days = prevMon + days
## now add trailing next month
days += range(1, 43-len(days))
return days
######## ## ## ### #### ##
## ### ### ## ## ## ##
## #### #### ## ## ## ##
###### ## ### ## ## ## ## ##
## ## ## ######### ## ##
## ## ## ## ## ## ##
######## ## ## ## ## #### ########
def notifyAll(typeChar, day, month, year, description, specialUser=None, status=None):
##special user is used for B and C, for the user whose request has changed
## or who created a request
## status is used for A and B, as the new status of a request
## descript
##A and B are intrinsically linked, Calling this with A is pointless
if typeChar == "A":
print ">>> notifyAll this function shouldnt really be called with 'A'"
## Both shouldnt be none, since there is an overlap, Alert if they are
if specialUser is None and status is None:
print ">>> notifyAll: specialUser and status are None, this should not be the case"
if status is not None:
print ">>> notifyAll Status assignment, status=", status
status = ['Denied', 'Pending', 'Confirmed'][status+1]
SUBJECTS = {
'A': "[Req Cal] Your Request Changed Status",
'B': "[Req Cal] A Request Changed Status",
'C': "[Req Cal] A Request Has Been Created"
}
if not app.config.get('USE_EMAIL'):
print "\nEMAIL NOT ENABLED\n"
return
validUserList = get_allUserEmails()
print ">>> notifyAll, initial list: ", validUserList
## This block extracts the "A" case from a B search, so i can be called with custom email settings
# and check if the setting is ticked, because it is different
special_A = None
if typeChar == "B":
for item in validUserList:
if item[0] == specialUser:
validUserList.remove(item)
if 'A' in item[1]:
special_A = item
#returns [(user, notificationSettings, email), (...), ...]
## filter for only users with specified notification setting
validUserList = [item for item in validUserList if typeChar in item[1]]
print ">>> notifyAll, list post filter: ", validUserList
subject = SUBJECTS[typeChar]
data = {
'day': day,
'month': MONTHS[int(month)],
'year': year,
'description': description,
'status': status,
'specialUser': specialUser
}
if len(validUserList) > 0:
msg = Message(subject,
sender=app.config['MAIL_USERNAME'],
recipients=[item[2] for item in validUserList],
body=render_template('email{}.txt'.format(typeChar), data=data)
)
mail.send(msg)
if special_A is not None:
msg = Message(SUBJECTS['A'],
sender=app.config['MAIL_USERNAME'],
recipients=[special_A[2]],
body=render_template('email{}.txt'.format('A'), data=data)
)
mail.send(msg)
#
# dDDDDDDb db
# dDb dDDb db
# dDb dDb db
# dDb dDb db
# dDb dDb db
# dDb dDb db
# dDb dDb db
# dDb dDb dD db dD
# dDb dDb dD db dD
# dDb dDDb dDdbdD
# dDDDDDDb dDDb
## DATABASE SHIT
def connect_db():
"""Connects to the specific database."""
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
## init_db, ab, and ac are called externally for database control
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
for name in ['Admin', 'Jonty', 'Bob', 'Clive']:
add_User(name, "password")
print db.execute("SELECT username from users").fetchall()
add_MonthEvent(22, 8, 2014, "Jonty", "Test Request\n1337")
print "new Database initialised"
def ab():
## initialise the userdb with debug users
##and add debug event
with app.app_context():
#add_MonthEvent()
for name in ['Admin', 'Jonty', 'Bob', 'Clive']:
add_User(name, "password")
def ac():
with app.app_context():
db = get_db()
v
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
print " Teardown "
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
if hasattr(g, 'user_db'):
g.user_db.close()
######## ## ## ######## ######## ### ######## ########
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ##
## ## ####### ## ## ######## ## ## ## ## ## ######
## ## ## ## ## ## ## ######### ## ##
## ## ## ## ## ## ## ## ## ## ##
######## ####### ## ######## ## ## ## ########
def updateEventStatus(day, month, year, status):
##updates the overall status of event
## checks first if status will change, if so will change and fire notification
print "\n**UPDATING EVENT STATUS, d{} - m{} - y{} to status: {}".format(day, month, year, status)
db = get_db()
##get current status, and also creater user for notifyAll is it is called
currData = db.execute("SELECT eventStatus, eventClaim, eventDesc from events where dayNum=? and monthNum=? and yearNum=?", (day, month, year)).fetchone()
print ">>> updateEventStatus currStatus: ", currData
if currData[0] == status:
print ">>> updateEventStatus: status does not change"
return
else:
notifyAll('B', day, month, year, currData[2], status=currData[0], specialUser=currData[1])
cursor = db.execute("UPDATE events SET eventStatus=? WHERE dayNum=? and monthNum=? and yearNum=?", (status, day, month, year))
db.commit()
def updateUserEventStatus(day, month, year, user, status):
## like updateEventStatus, but for a single user
status = int(status)
db = get_db()
cursor = db.execute('SELECT eventConfirms, eventDenies from events where yearNum=? and monthNum=? and dayNum=?', (year, month, day))
cD = cursor.fetchone()
print ">>> updateUserEventStatus1 : cD = {} - {} {} {}".format(cD, year, month, day)
eventConfirms = str(cD[0]).split(',')
eventDenies = str(cD[1]).split(',')
print ">>> updateUserEventStatus2 conf{} den{}".format(eventConfirms, eventDenies)
if user in eventConfirms:
eventConfirms.remove(user)
if user in eventDenies:
eventDenies.remove(user)
print type(status)
if status == 0:
pass
elif status == -1:
eventDenies.append(user)
elif status == 1:
eventConfirms.append(user)
print ">>> updateUserEventStatus3 conf{} den{}".format(eventConfirms, eventDenies)
eventConfirms = ','.join(map(str, eventConfirms))
eventDenies = ','.join(map(str, eventDenies))
print ">>> updateUserEventStatus4 conf{} den{}".format(eventConfirms, eventDenies)
db.execute("UPDATE events set eventConfirms=?, eventDenies=? where yearNum=? and monthNum=? and dayNum=?", (eventConfirms, eventDenies, year, month, day))
db.commit()
def filterEvents(eventList):
##filters daynum from list of tups with [(daynum, status), (...,...), ...]
confL, pendL, denL = [], [], []
print ">>> filterEvents,", eventList
for item in eventList:
if item[1] == 1:
confL.append(item[0])
elif item[1] == -1:
denL.append(item[0])
else:
pendL.append(item[0])
return confL, pendL, denL
######## ###### ######## ########
## ## ## ## ## ##
## ## ## ## ##
## ## ####### ## #### ###### ##
## ## ## ## ## ##
## ## ## ## ## ##
######## ###### ######## ##
def get_monthEvents(month, year):
#month is 0-11, same in db
print ">>> get_monthEvents"
db = get_db()
cursor = db.execute("SELECT dayNum, eventStatus FROM events where yearNum=? and monthNum=?", (year, month))
#confL, pendL, denL
f = filterEvents(cursor.fetchall())
#print {'pend': [x[0]for x in pendEv], 'conf': [x[0] for x in confEv]}
return {'conf': f[0], 'pend': f[1], 'den': f[2]}
def get_dayData(day, month, year):
#claimer, eventDescription, eventConfirms, eventDenies = dayData
## debug return
#return "Jonty", "This is a sample request description", "NiceBarry,NiceClive,Bob", "EvilBarry,EvilClive"
db = get_db()
cursor = db.execute('SELECT eventClaim, eventDesc, eventConfirms, eventDenies from events where yearNum=? and monthNum=? and dayNum=?', (year, month, day))
cD = cursor.fetchone()
print cD
if cD is None:
return None
else:
if len(cD) == 4:
print "extracting ROW"
eventClaim = str(cD[0])
eventDesc = str(cD[1])
eventConfirms = str(cD[2])
eventDenies = str(cD[3])
return eventClaim, eventDesc, eventConfirms, eventDenies
else:
print "Row wrong length: ", len(cD)
return None
def get_userList():
#['username',]
print "get user list"
db = get_db()
cursor = db.execute("SELECT username from users")
output = cursor.fetchall()
print output
return [x[0] for x in output]
def get_userDict():
#{user:passhash,}
print "get user dict"
db = get_db()
output = db.execute("SELECT username, passHash from users").fetchall()
return {k[0]:k[1] for k in output}
def get_userRequests(user):
print ">>> get_userEvents"
db = get_db()
events = db.execute("SELECT dayNum, monthNum, yearNum, eventStatus from events where eventClaim=?", (user,)).fetchall()
print ">>> get_userEvents selection: ", events
return events
def get_userSettings(user):
print ">>> get_userSettings for {}".format(user)
db = get_db()
output = db.execute("SELECT email, notificationSettings from users where username=?", (user,)).fetchone()
print output
if output[0] == None:
return None
else:
return output
def get_allUserEmails():
db = get_db()
cursor = db.execute("SELECT username, notificationSettings, email from users where email is not null")
return cursor.fetchall()
######## ### ######## ########
## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ##
## ## ####### ## ## ## ## ## ##
## ## ######### ## ## ## ##
## ## ## ## ## ## ## ##
######## ## ## ######## ########
def add_MonthEvent(day, month, year, claimer, description):
notifyAll('C', day, month, year, description, specialUser=claimer)
db = get_db()
db.execute('INSERT into events (dayNum, monthNum, yearNum, eventStatus, eventClaim, eventDesc, eventConfirms, eventDenies) values (?, ?, ?, ?, ?, ?, ?, ?)',
(day, month, year, 0, claimer, description, "", ""))
db.commit()
def add_User(user, password):
userList = get_userList()
## usernames always start with a capital letter
user = user[0].upper() + user[1:]
if user in userList:
print "Username already taken"
return
db = get_db()
db.execute('INSERT into users (username, passHash, notificationSettings) values (?, ?, ?)',(user, generate_password_hash(password), "") )
db.commit()
######## ###### ######## ########
## ## ## ## ## ##
## ## ## ## ##
## ## ####### ###### ###### ##
## ## ## ## ##
## ## ## ## ## ##
######## ###### ######## ##