-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
2362 lines (1927 loc) · 83.7 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
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
#================================================== Imports
#Flask
from flask import Flask, render_template, flash, redirect, url_for, request, make_response, jsonify, send_file,abort
#For decorator
from functools import wraps
#Passlib
from passlib.hash import sha256_crypt
#Date time
import datetime
#OS
import os
#Uuid = for unique random id
import uuid
#Model for DB
from model import Model
#Controls
from control import *
#Configs
from config import ProductionConfig, DevelopmentConfig
#Bleepy module
from bleepy.bleepy import VideoFile, AudioFile, MediaFile, SpeechToText, ProfanityExtractor, ProfanityBlocker
#================================================== Configs
app = Flask(__name__)
app.config.from_object(ProductionConfig if app.config["ENV"] == "production" else DevelopmentConfig)
#================================================== Objects
db = Model(
app.config["DB_HOST"],
app.config["DB_USER"],
app.config["DB_PWD"],
app.config["DB_NAME"]
)
tokenControl = TokenControls(app.secret_key)
basicControl = BasicControls()
pagingControl = PagingControl()
processControl = ProcessControl()
sendEmailControl = SendEmailControl()
class BleepyControl():
def customBleepVideo(self,bleepsound:AudioFile, video:VideoFile, lang:str, model:str):
#Set up
stt = SpeechToText(model)
extractor = ProfanityExtractor(lang)
blocker = ProfanityBlocker()
blocker.setClipsDirectory("static/media/Trash/Videos")
blocker.setSaveDirectory("static/media/Storage/Videos/Processed")
#run stt
stt.run(video)
#run profanity extractor
extractor.setProfanities([]) #Reset Profanities
extractor.run(stt.getResults())
profanities = extractor.getProfanities()
#run blocker if has profanity
block_directory = ''
if len(profanities) > 0:
blocker.run(video,bleepsound,profanities)
block_directory = blocker.getFileLocation()
#return bleepvideo directory and profanities
return {"profanities":profanities,"block_directory":block_directory}
def englishBleepVideo(self,bleepsound:AudioFile, video:VideoFile):
return self.customBleepVideo(bleepsound,video,"english","stt-language-models/"+app.config['DEFAULT_STT_MODEL_ENG'])
def tagalogBleepVideo(self,bleepsound:AudioFile, video:VideoFile):
return self.customBleepVideo(bleepsound,video,"tagalog","stt-language-models/"+app.config['DEFAULT_STT_MODEL_TAG'])
#================================================== App Control Methods
def getIdViaAuth():
try:
cookies = request.cookies
token = cookies.get(app.config["AUTH_TOKEN_NAME"])
tokenvalues = tokenControl.getTokenValues(token)
return str(tokenvalues["authid"])
except:
return None
def getEmailViaAuth():
try:
return db.selectAccountViaId(getIdViaAuth()).get("email")
except:
return None
def setAuth(response,**kwargs):
"""
set acc_id and max_age
example setAuth(render_template("home.html"),acc_id=acc_id,max_age=max_age)
if the acc_id and max_age is not set auth will set no value with expire 0
"""
#set response
res = make_response(response)
#set cookie token
if kwargs.get("acc_id") and kwargs.get("max_age"):
res.set_cookie(app.config["AUTH_TOKEN_NAME"],
value = tokenControl.generateToken(authid=kwargs.get("acc_id"),validuntil=kwargs.get("max_age")),
max_age = kwargs.get("max_age")
)
else:
res.set_cookie(app.config["AUTH_TOKEN_NAME"],
value = "",
expires=0
)
return res
def setVerification(response,**kwargs):
"""
for forgot password for now
set verification token
email, fullcode, max_age
"""
#set response
res = make_response(response)
#set cookie token
if kwargs.get("email") and kwargs.get("fullcode") and kwargs.get("max_age"):
res.set_cookie(app.config["DEFAULT_TOKEN_VER"],
value = tokenControl.generateToken(email=kwargs.get("email"),code = kwargs.get("fullcode"),validuntil=kwargs.get("max_age")),
max_age = kwargs.get("max_age")
)
else:
res.set_cookie(app.config["DEFAULT_TOKEN_VER"],
value = "",
expires=0
)
return res
def viewData(**kwargs:str):
"""
This method will pass constant data that will be use by the templates
In rendering templates, always include this
Example: render_template("index.html", viewdata = viewData())
Another example: render_template("index.html", viewdata = viewData( somedata = "data"))
To add active class to cardnav, use nameOfRoute=True
Example: dashboard=True
"""
viewdata = {
"auth_token":app.config["AUTH_TOKEN_NAME"]
}
#Paging
page = request.args.get("page")
if not page:
page = '1'
viewdata["active_page"] = {
page:True
}
#If the user is logged in
if getIdViaAuth():
acc_id = getIdViaAuth()
data = db.selectAccountViaId(acc_id)
if data:
fullname = str(data.get("fname")+" "+data.get("lname")).title()
photo = data.get("photo")
role_id = data.get("role_id")
#User widget
viewdata["uw_fullname"] = fullname
viewdata["uw_photo"] = photo
viewdata["uw_videoscount"] = db.countVideosUploadedByAcc(acc_id).get("count")
viewdata["uw_bleepedvideoscount"] = db.countBleepVideosUploadedByAcc(acc_id).get("count")
viewdata["uw_role"] = db.selectAccRole(acc_id).get("name")
#Navigation
viewdata["navigations"] = db.selectNavOfRole(role_id)
viewdata["page_name"] = db.selectNavByLocation(request.path).get('name') if db.selectNavByLocation(request.path) else ""
viewdata.update(**kwargs)
return viewdata
def allowedVideoFileSize(filesize) ->bool:
return float(filesize) <= app.config['MAX_VIDEO_FILESIZE']
def allowedAudioFileSize(filesize) ->bool:
return float(filesize) <= app.config['MAX_AUDIO_FILESIZE']
def allowedPhotoFileSize(filesize) ->bool:
return float(filesize) <= basicControl.bytesToMb(app.config['MAX_PHOTO_FILESIZE'])
def flashPrintsforAdmin(msg,msgname=""):
acc_id = getIdViaAuth()
acc_role = db.selectAccRole(acc_id).get("name")
if acc_role.lower() == str(app.config["ROLE_ADMIN"]).lower():
flash(msgname+" Message: "+str(msg), 'info')
def generateLongBleepSound(audio:AudioFile):
savedirectory = "static/"+app.config['AUDIO_UPLOADS_LONG']
#Trim the audio
trimname = "trim"+str(uuid.uuid4()) +"."+audio.getFileExtension()
trimaudio = "ffmpeg -i {} -af \"silenceremove=start_periods=1:start_duration=1:start_threshold=-60dB:detection=peak,aformat=dblp,areverse,silenceremove=start_periods=1:start_duration=1:start_threshold=-60dB:detection=peak,aformat=dblp,areverse\" {}"
trimaudio = trimaudio.format(audio.getFile(),savedirectory+"/"+trimname)
processControl.runSubprocess(trimaudio)
#Save to text file
txtfilename = savedirectory+"/"+str(uuid.uuid4()) +".txt"
try:
f = open(txtfilename, "a")
for x in range(5):
f.write("file "+trimname+"\n")
finally:
f.close()
#Create long version
longname = "long"+str(uuid.uuid4()) +"."+audio.getFileExtension()
longaudio = "ffmpeg -safe 0 -f concat -i {} -c copy {}"
longaudio = longaudio.format(txtfilename,savedirectory+"/"+longname)
processControl.runSubprocess(longaudio)
#Delete trim version
if os.path.exists(savedirectory+"/"+trimname):
os.remove(savedirectory+"/"+trimname)
#Delete the text file
if os.path.exists(txtfilename):
os.remove(txtfilename)
#If the long version is created or not
if os.path.exists(savedirectory+"/"+longname):
flashPrintsforAdmin("Passed","Making long version of audio: ")
return longname
else:
flashPrintsforAdmin("Failed","Making long version of audio: ")
#Delete the audio file
if os.path.exists(audio.getFile()):
os.remove(audio.getFile())
return ''
def saveVideo(file,filename,uniquefilename,acc_id):
fileinfo = {
"filename":"NaN",
"filelocation":"NaN"
}
parent_folder = "static/"+app.config['VIDEO_UPLOADS']
folder = str(acc_id)
savefolder = app.config['VIDEO_UPLOADS']+"/"+folder
#Try to create folder if not exist
try:
path = os.path.join(parent_folder, folder)
os.mkdir(path)
except(FileExistsError):
pass
#SaveToDirectories
try:
file.save(os.path.join("static/"+savefolder, uniquefilename))
except Exception as e:
flashPrintsforAdmin(e,"Error in saving file: ")
#SaveToDB
filelocation = savefolder+"/"+uniquefilename
savedirectory = "static/"+filelocation
msg = db.insertVideo(filename,uniquefilename,filelocation,savedirectory)
flashPrintsforAdmin(msg,"Insert Video")
vid_id = db.selectVideoByUniqueFilename(uniquefilename).get("video_id")
msg = db.insertUploadedBy(vid_id,acc_id)
flashPrintsforAdmin(msg,"Insert Uploaded by")
fileinfo = db.selectVideoByAccountAndVidId(acc_id,vid_id)
return fileinfo
def saveBleepSound(file,title,uniquefilename):
# Save the file in directory
savefolder = app.config['AUDIO_UPLOADS_ORIG']
try:
file.save(os.path.join("static/"+savefolder, uniquefilename))
except Exception as e:
flashPrintsforAdmin(e,"Error in saving file: ")
audio = AudioFile()
audio.setFile("static/"+savefolder+"/"+uniquefilename)
# Make longer version of the file
longversion = generateLongBleepSound(audio)
if longversion:
# Save to db the data
filename = title
filelocation = app.config['AUDIO_UPLOADS_ORIG']+"/"+uniquefilename
longversion = app.config['AUDIO_UPLOADS_LONG']+"/"+longversion
msg = db.insertBleepSound(filename,uniquefilename,filelocation,longversion)
flashPrintsforAdmin(msg,"Insert Bleep sound")
return True
else:
flash('The audio file is not acceptable because the sound volume is too low, try to upload other audio file with higher sound volume', 'danger')
return False
def updateBleepSound(bleepsound_id,file,title,uniquefilename):
# Save the file in directory
savefolder = app.config['AUDIO_UPLOADS_ORIG']
try:
file.save(os.path.join("static/"+savefolder, uniquefilename))
except Exception as e:
flashPrintsforAdmin(e,"Error in saving file: ")
audio = AudioFile()
audio.setFile("static/"+savefolder+"/"+uniquefilename)
# Make longer version of the file
longversion = generateLongBleepSound(audio)
if longversion:
bleepsound_data = db.selectBleepSoundById(bleepsound_id)
#Delete the previous data
#Delete orig version
if os.path.exists("static/"+bleepsound_data.get("filelocation")):
os.remove("static/"+bleepsound_data.get("filelocation"))
flashPrintsforAdmin("Success","Deleted Previous original file: ")
#Delete long version
if os.path.exists("static/"+bleepsound_data.get("longversion")):
os.remove("static/"+bleepsound_data.get("longversion"))
flashPrintsforAdmin("Success","Deleted Previous longversion file: ")
# Save to db the data
filename = title
filelocation = app.config['AUDIO_UPLOADS_ORIG']+"/"+uniquefilename
longversion = app.config['AUDIO_UPLOADS_LONG']+"/"+longversion
msg = db.updateBleepSoundById(bleepsound_id,filename,uniquefilename,filelocation,longversion)
flashPrintsforAdmin(msg,"Update Bleep sound")
return True
else:
flash('The audio file is not acceptable because the sound volume is too low, try to upload other audio file with higher sound volume', 'danger')
return False
def saveBleepedVideo(bleepvideodict:dict,isrefilter:bool):
"""
Dictionary
- vid_id
- bleepsound_id
- pfilename
- pfilelocation
- psavedirectory
- profanities (list)
- stt_model_id
for refilter
"""
bleepedvideoinfo = {
"filename":"NaN",
"filelocation":"NaN"
}
try:
#insertbleepvideo if not isrefilter else insertrefiltervideo
msg = db.insertBleepedVideo(bleepvideodict) if not isrefilter else db.insertRefilterVideo(bleepvideodict)
flashPrintsforAdmin(msg,"Insert Bleeped Video" if not isrefilter else "Insert Refiltered Video")
bleepedvideoinfo = db.selectBleepVideoByFileName(bleepvideodict.get('pfilename'))
pvid_id = bleepedvideoinfo.get("pvideo_id")
vals = []
for profanity in bleepvideodict.get('profanities'):
lang_id = db.selectLangByLang(profanity.get("lang")).get("lang_id") if db.selectLangByLang(profanity.get("lang")) else 0
item = (profanity["word"],profanity["start"],profanity["end"],lang_id,profanity["conf"], profanity["predict_prob"], pvid_id)
vals.append(item)
msg = db.insertProfanities(vals)
flashPrintsforAdmin(msg,"Insert Profanities")
bleepedvideoinfo["profanitycount"] = db.countProfanityWordsByBleepedVideo(pvid_id).get("count")
bleepedvideoinfo["uniqueprofanitycount"] = db.countUniqueProfanityWordsByBleepedVideo(pvid_id).get("count")
mostfrequent = db.selectMostFrequentProfanityWordByVideo(pvid_id)
bleepedvideoinfo["mostfrequentword"] = mostfrequent.get("word")
bleepedvideoinfo["mostfrequentwordoccurence"] = mostfrequent.get("occurence")
bleepedvideoinfo["profanities"] = db.selectProfanitiesOfVideo(pvid_id) #list
bleepedvideoinfo["uniqueprofanities"] = db.selectUniqueProfanityWordsByVideo(pvid_id) #list
bleepedvideoinfo["top10profanities"] = db.selectTop10ProfanitiesByVideo(pvid_id)
bleepedvideoinfo["countperlang"] = db.selectCountPerLangOfBleepVideo(pvid_id)
bleepedvideoinfo["isrefilter"] = isrefilter
except Exception as e:
print (e)
bleepedvideoinfo["error"] = e
return bleepedvideoinfo
#================================================== Decorators
def testConn(f):
"""
Check if the db server is up | Decorator | from functools import wraps
Note: Include this wrapper in every route that requires dbms
Or Include this wrapper to all routes except for the error page
"""
@wraps(f)
def wrap(*args, **kwargs):
if db.hasConnection():
return f(*args, **kwargs)
else:
abort(500)
return wrap
def authentication(f):
"""
Check the authentication token of the user
if the token not exist, its expires or credentials not set yet
if the token not have values or has invalid secretkey, its invalid
if the token not have authid, its invalid
if the account is block
"""
@wraps(f)
def wrap(*args, **kwargs):
cookies = request.cookies
token = cookies.get(app.config["AUTH_TOKEN_NAME"])
#making sure there is no cookie left
# reserror = make_response(redirect(url_for('signin')))
# reserror = setAuth(redirect(url_for('signin')))
reserror = setAuth(redirect(url_for('signin')))
#set cookie token | expires = 0 to delete cookie
# reserror.set_cookie(app.config["AUTH_TOKEN_NAME"],
# value = "",
# expires=0
# )
if not token:
#The token not exist
flash("Invalid Authentication. Please try to login","warning")
return reserror
tokenvalues = tokenControl.getTokenValues(token)
if not tokenvalues:
#The token values is None
flash("Invalid Authentication","danger")
return reserror
try:
acc_id = tokenvalues.get("authid")
except:
#The token doenst contain authid
flash("Invalid Authentication","danger")
return reserror
# Query the acc_id
data = db.selectAccountViaId(acc_id)
if data == None:
flash("Invalid Authentication. User not found: "+str(data),"danger")
return reserror
try:
status_id = data.get("status_id")
if status_id == db.selectAccountStatusDefaultsViaStatus(app.config["DEFAULT_ACC_STATUS_BLOCKED"]).get("status_id"):
flash("The account is blocked!","danger")
return reserror
except Exception as e:
flash("Error: "+e,"danger")
return reserror
# if not exist return error
max_age = tokenvalues.get("validuntil")
if max_age == app.config["AUTH_MIN_AGE"]: #reset auth
res = setAuth(f(*args, **kwargs),acc_id=acc_id,max_age=max_age)
return res
return f(*args, **kwargs)
return wrap
def isAlreadyLoggedin(f):
"""
If the user is already logged in go to dashboard
Applicable to sign in and sign up page
"""
@wraps(f)
def wrap(*args, **kwargs):
cookies = request.cookies
token = cookies.get(app.config["AUTH_TOKEN_NAME"])
if token:
flash("You are already logged in","warning")
return redirect(url_for('dashboard'))
return f(*args, **kwargs)
return wrap
def isAdmin(f):
"""
Check if the role of the user is admin
"""
@wraps(f)
def wrap(*args, **kwargs):
acc_id = getIdViaAuth()
acc_role = db.selectAccRole(acc_id).get("name")
if acc_role != app.config["ROLE_ADMIN"]:
flash("You are not authorize to access this page","danger")
return redirect(url_for('dashboard'))
return f(*args, **kwargs)
return wrap
def isEditor(f):
"""
Check if the role of the user is editor or admin
"""
@wraps(f)
def wrap(*args, **kwargs):
acc_id = getIdViaAuth()
acc_role = db.selectAccRole(acc_id).get("name")
if not (acc_role == app.config["ROLE_ADMIN"] or acc_role == app.config["ROLE_EDITOR"]):
flash("You are not authorize to access this page","danger")
return redirect(url_for('dashboard'))
return f(*args, **kwargs)
return wrap
#================================================== Error handlers
@app.errorhandler(403)
def forbidden_error(error):
return render_template('error.html',error_msg = error, error_code = 403,error_status = "warning"), 403
@app.errorhandler(404)
def not_found_error(error):
return render_template('error.html',error_msg = error, error_code = 404,error_status = "danger"), 404
@app.errorhandler(405)
def method_not_allowed_error(error):
return render_template('error.html',error_msg = error, error_code = 405,error_status = "danger"), 405
@app.errorhandler(410)
def gone_error(error):
return render_template('error.html',error_msg = error, error_code = 410,error_status = "warning"), 410
@app.errorhandler(500)
def internal_server_error(error):
return render_template('error.html',error_msg = error, error_code = 500,error_status = "danger"), 500
#================================================== Routes
#Index Page
@app.route('/' )
@testConn
def index():
#create template folder
#inside of template folder is the home.html
return render_template('index.html', viewdata = viewData() )
#About Us Page
@app.route('/aboutus' )
@testConn
def aboutus():
return render_template('aboutus.html', viewdata = viewData() )
#Contact Us Page
@app.route('/contactus' )
@testConn
def contactus():
return render_template('contactus.html', viewdata = viewData() )
#Terms and Condition Page
@app.route('/termsandcondition' )
@app.route('/tandc' )
@testConn
def termsandcondition():
return render_template('termsandcondition.html', viewdata = viewData() )
#Privacy and Security Policy Page
@app.route('/privacyandsecuritypolicies' )
@app.route('/privacypolicies' )
@app.route('/securitypolicies' )
@testConn
def privacyandsecuritypolicies():
return render_template('privacyandsecuritypolicies.html', viewdata = viewData() )
#Help | FAQs Page
@app.route('/help' )
@app.route('/faqs' )
@testConn
def help():
return render_template('help.html', viewdata = viewData() )
#Bleep Sounds
@app.route('/bleepsoundlist')
@testConn
def bleepsoundlist():
page = request.args.get("page")
search = request.args.get("search") if request.args.get("search") else ""
hasaccess= False
acc_id = getIdViaAuth()
acc_role = db.selectAccRole(acc_id).get("name") if db.selectAccRole(acc_id) else ''
if acc_role == app.config["ROLE_EDITOR"] or acc_role == app.config["ROLE_ADMIN"]:
hasaccess= True
#Default
count = 0
limit = app.config['DEFAULT_MAX_LIMIT']
offset = 0
#Count first the search
count = db.countBleepSoundSearch(search).get('count') if db.countBleepSoundSearch(search) else 0
#Arrange the offset and limit
offset = pagingControl.generateOffset(page,count,limit)
#Query
bleepsounds = db.selectBleepSoundsSearchLimitOffset(search,limit,offset)
latest_bleepsound = db.selectLatestBleepSoundSearch(search)
resultbadge = pagingControl.generateResultBadge(count,limit,offset,search)
pagination = pagingControl.generatePagination(count,limit)
return render_template('bleepsoundlist.html',
viewdata = viewData(bleepsounds=bleepsounds,
latest_bleepsound = latest_bleepsound,
resultbadge=resultbadge,
pagination=pagination,
hasaccess=hasaccess
)
)
#Forgot Password Page
@app.route('/forgotpassword',methods=["POST",'GET'])
@testConn
@isAlreadyLoggedin
def forgotpassword():
if request.method == "POST":
email = basicControl.sanitizeEmail(request.form.get("email"))
ver_code = request.form.get("ver_code")
hasOTP = request.form.get("hasOTP")
if not email:
flash('Email field is empty ', 'warning')
return redirect(url_for('forgotpassword'))
account = db.selectAccountViaEmail(email)
if not account:
flash('Email not exist', 'warning')
return redirect(url_for('forgotpassword'))
if hasOTP:
#check if there is Cookies
if not ver_code:
flash('Verification code is empty ', 'warning')
return redirect(url_for('forgotpassword'))
cookies = request.cookies
token = cookies.get(app.config["DEFAULT_TOKEN_VER"])
if not token:
flash('Request expired. Make new request ', 'warning')
return redirect(url_for('forgotpassword'))
#Verify OTP
tokenvalues = tokenControl.getTokenValues(token)
if not tokenvalues:
#The token values is None
flash("Invalid Authentication. No values","danger")
return redirect(url_for('forgotpassword'))
tokenemail = tokenvalues.get("email")
tokencode = tokenvalues.get("code")
if not tokenemail and tokencode:
flash("Invalid Authentication","danger")
return redirect(url_for('forgotpassword'))
if email != tokenemail:
flash("Invalid Authentication. Wrong Email","danger")
return redirect(url_for('forgotpassword'))
if ver_code != tokencode[0:6]:
flash("Invalid Verification code","danger")
return redirect(url_for('forgotpassword'))
return render_template('forgotpassword.html', viewdata = viewData(ischangepassword = True,email =email))
else:
#Set OTP code
isOTP = True
fullOTP = str(uuid.uuid1())
uniqueOTP = fullOTP[0:6]
ver_time = app.config["DEFAULT_MIN_VER_TIME"]
max_age = ver_time + app.config["DEFAULT_SPARE_VER_TIME"]
if not sendEmailControl.sendForgotPwdVerification(uniqueOTP,email):
flash('Verification not sent ', 'danger')
return render_template('forgotpassword.html', viewdata = viewData() )
flash('Verification code has been sent!', 'success')
res = setVerification(render_template('forgotpassword.html',
viewdata = viewData(isOTP=isOTP, email=email,ver_time = ver_time)),
email=email,max_age=max_age,fullcode=fullOTP)
return res
return render_template('forgotpassword.html', viewdata = viewData())
#Change Password Page
@app.route('/changepassword',methods=["POST",'GET'])
@testConn
@isAlreadyLoggedin
def changepassword():
if request.method == 'POST':
email = basicControl.sanitizeEmail(request.form.get("email"))
newpwd = request.form.get("newpwd")
confirmpwd = request.form.get("confirmpwd")
if not newpwd and confirmpwd and email:
flash('Required fields are empty ', 'warning')
return redirect(url_for('forgotpassword'))
if not (newpwd == confirmpwd):
flash('New password and Confirm password not equal', 'warning')
return redirect(url_for('forgotpassword'))
account = db.selectAccountViaEmail(email)
if not account:
flash('Email not exist', 'warning')
return redirect(url_for('forgotpassword'))
acc_id = account.get("account_id")
# Reset Password process
#hash password
hash_pwd = sha256_crypt.encrypt(str(newpwd))
msg = db.updateAccPassword(acc_id,hash_pwd)
if msg:
flash('Password has been updated, try to log in!', 'success')
return redirect(url_for('signin'))
return redirect(url_for('forgotpassword'))
#Signup Page
@app.route('/signup', methods=["POST",'GET'])
@testConn
@isAlreadyLoggedin
def signup():
if request.method == "POST":
fname = request.form.get("fname").strip()
lname = request.form.get("lname").strip()
email = basicControl.sanitizeEmail(request.form.get("email"))
pwd = request.form.get("pwd")
confirmpwd = request.form.get("confirmpwd")
isagree = request.form.getlist("agreetandc")
#Validations
if fname == "" or lname == "" or email == "" or pwd == "" or confirmpwd == "":
flash('Please fill up all fields', 'danger')
return redirect(url_for('signup'))
if not isagree:
flash('Please check the Terms and Conditions', 'danger')
return redirect(url_for('signup'))
if pwd != confirmpwd:
flash('Password and Confirm password not match', 'danger')
return redirect(url_for('signup'))
if not (fname.replace(" ", "").isalpha() and lname.replace(" ", "").isalpha()):
flash('Invalid First Name of Last Name', 'danger')
return redirect(url_for('signup'))
checkemail = db.selectAccountViaEmail(email)
if checkemail:
if checkemail.get("email"):
flash('Email is already taken or used by other user', 'danger')
return redirect(url_for('signup'))
else:
flash('Error: '+checkemail.get("error"), 'danger')
return redirect(url_for('signup'))
#hash password
hash_pwd = sha256_crypt.encrypt(str(pwd))
#Save to db if valid
msg = db.insertUser(email,fname,lname,hash_pwd)
print(msg)
#validate to db if the account save
account = db.selectAccountViaEmail(email)
if not account:
flash('Sign up failed due to internal error. Account not save', 'danger')
return redirect(url_for('signup'))
acc_id = account.get("account_id")
if not acc_id:
flash('Sign up failed due to internal error', 'danger')
return redirect(url_for('signup'))
#set cookie
max_age = app.config["AUTH_MIN_AGE"]
res = setAuth(redirect(url_for('dashboard')),acc_id=acc_id,max_age=max_age)
flash('You are now logged in ', 'success')
return res
return render_template('signup.html', viewdata = viewData() )
#Signin Page
@app.route('/signin', methods=["POST",'GET'])
@testConn
@isAlreadyLoggedin
def signin():
if request.method == "POST":
email = basicControl.sanitizeEmail(request.form.get("email"))
pwd = request.form.get("pwd")
remember = request.form.getlist("remember")
#remember 30days or else remember for 5mins
max_age = app.config["AUTH_MAX_AGE"] if remember else app.config["AUTH_MIN_AGE"]
#Validation
if email == "" or pwd == "":
flash('Invalid! Email or Password should not be empty', 'danger')
return redirect(url_for('signin'))
#DB Model
account = db.selectAccountViaEmail(email)
if not account:
flash('Incorrect Email or Password', 'danger')
return redirect(url_for('signin'))
acc_pwd = account.get("pwd")
acc_id = account.get("account_id")
status_id = account.get("status_id")
if status_id == db.selectAccountStatusDefaultsViaStatus(app.config["DEFAULT_ACC_STATUS_BLOCKED"]).get("status_id"):
flash("The account is blocked!","danger")
return redirect(url_for('signin'))
if acc_pwd == None or acc_id == None:
flash('Internal Error', 'danger')
return redirect(url_for('signin'))
pwd_candidate = pwd
if not sha256_crypt.verify(pwd_candidate, acc_pwd):
flash('Incorrect Email or Password', 'danger')
return redirect(url_for('signin'))
# #set response
# res = make_response(redirect(url_for('dashboard')))
# #set cookie token
# res.set_cookie(app.config["AUTH_TOKEN_NAME"],
# value = generateToken(authid=acc_id,validuntil=max_age),
# max_age = max_age
# )
res = setAuth(redirect(url_for('dashboard')),acc_id=acc_id,max_age=max_age)
flash('You are now logged in ', 'success')
return res
return render_template('signin.html', viewdata = viewData())
#Log out route
@app.route('/logout')
@testConn
def logout():
"""
Log out does not need authentication, it just delete auth cache is exist
"""
res = setAuth(redirect(url_for('signin')))
flash('You are now logged out ', 'success')
return res
#Pages and routes that can only be access when logged in
#@authentication
#Settings Page
@app.route('/settings')
@testConn
@authentication
def settings():
return render_template('settings.html', viewdata = viewData())
#Dashboard Page
@app.route('/dashboard')
@testConn
@authentication
def dashboard():
acc_id = getIdViaAuth()
now = datetime.datetime.now()
acc_role = db.selectAccRole(acc_id).get("name")
widgets_data = {
"mostfrequentprofanities":db.selectUniqueProfanityWordsByAccount(acc_id),
"bleepedvideos":db.selectBleepedVideosByAccountSearchLimitOffset(acc_id,"",app.config['DEFAULT_ATLEAST_LIMIT'],0),
"datetoday":now.strftime("%B %d %Y")+", "+now.strftime("%A"),
"countperlang":db.selectCountPerLangOfAccount(acc_id)
}
feeds = db.selectFeeds(acc_id) if acc_role != app.config["ROLE_ADMIN"] else db.selectAdminFeeds()
latestbleep_data = db.selectLatestBleepSummaryDataSearch(acc_id,"")
admin_data = {}
editor_data = {}
if acc_role == app.config["ROLE_EDITOR"] or acc_role == app.config["ROLE_ADMIN"]:
#Set the data that the editor and admin can have
editor_data = {
"role":"editor",
"bleepsounds" : db.selectBleepSoundsSearchLimitOffset('',10,0),
"latest_bleepsound" : db.selectLatestBleepSoundSearch(''),
"bleepsoundcount": db.countBleepSoundSearch('').get('count') if db.countBleepSoundSearch('') else 0
}
if acc_role == app.config["ROLE_ADMIN"]:
#Set the data that the editor and admin can have
admin_data = {
"accountCounts":db.selectAccountCountsByRole(),
"latestusers":db.selectLatestActiveUsers(),
"trendfeeds":db.selectTrendFeed()
}
#Update widgets here
widgets_data["has_uploadedby"] = True
widgets_data["mostfrequentprofanities"]=db.selectTop10ProfanitiesAll()
widgets_data["bleepedvideos"]=db.selectBleepedVideosAllSearchLimitOffset("",app.config['DEFAULT_ATLEAST_LIMIT'],0)
widgets_data["countperlang"]=db.selectCountPerLangAll()
#Update latest bleep
latestbleep_data = db.selectLatestBleepSummaryDataAllSearch("")
return render_template('dashboard.html',
viewdata = viewData(
widgets_data=widgets_data,
admin_data=admin_data,
editor_data=editor_data,
feeds=feeds,
latestbleep_data=latestbleep_data
)
)
#Profanity Page
@app.route('/profanities')
@app.route('/uniqueprofanities')
def profanities():
return redirect(url_for('dashboard'))
#Profile route
@app.route('/profile')
@testConn
@authentication
def profile():
acc_id = getIdViaAuth()
data = db.selectAccountViaId(acc_id)
user_data = {
"fname":data.get("fname"),
"lname":data.get("lname"),
"email":data.get("email"),
"photo":data.get("photo"),
}
max_photo_filesize = basicControl.bytesToMb(app.config["MAX_PHOTO_FILESIZE"])
return render_template('profile.html',
viewdata = viewData( user_data = user_data,
max_photo_filesize=max_photo_filesize
)
)
#Video List route
@app.route('/videolist')
@testConn
@authentication
def videolist():
page = request.args.get("page")
search = request.args.get("search") if request.args.get("search") else ""
#Default
count = 0
limit = app.config['DEFAULT_MAX_LIMIT']
offset = 0
acc_id = getIdViaAuth()
acc_role = db.selectAccRole(acc_id).get("name")
videos = {}
latest_video = {}
has_uploadedby = False
if acc_role == app.config["ROLE_ADMIN"]:
has_uploadedby = True