-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
626 lines (545 loc) · 21.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
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
from Tool import app, db , socketio
from Tool.forms import RegistrationForm, LoginForm , MakeTeamForm , TeamLoginForm , MakeUpcoming , UpdateUserForm ,UpdateTeamForm , Make_Rental , UpdateRent , KnowledgeForm , UpdateKnowledgeForm
from Tool.models import User,Team,Events , Rent , Knowledge
from flask import render_template,request, url_for, redirect, flash ,abort, jsonify, make_response
from flask_login import current_user, login_required, login_user , logout_user
from picture_handler import add_profile_pic , add_team_pic , add_rent_pic , add_knowledge_pic
import secrets
from sqlalchemy import desc, asc
import os
import json
from dotenv import load_dotenv
from flask import Flask, render_template, request, abort
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import VideoGrant
from datetime import datetime
load_dotenv()
twilio_account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
twilio_api_key_sid = os.environ.get('TWILIO_API_KEY_SID')
twilio_api_key_secret = os.environ.get('TWILIO_API_KEY_SECRET')
def userby_username(username):
user = User.query.filter_by(username=username).first()
print('user' + str(user.id) + user.email)
return user
def teamsby_username(user):
a = 1
teams = user.teams
if len(teams) == 0:
team_names = "You are not a member of any team. Please join a team."
else:
team_names = 'Your Teams are: ' + '\n'
for team in teams:
team = str(team)[-2]
team = int(team)
team = Team.query.filter_by(id=team).first()
team_name = team.name
team_names += str(a) + '.' + team_name + '\n'
a += 1
print(team_names)
return team_names
############ * CHATBOT * #################
@app.route('/webhook', methods=['POST'])
def webhook():
print("webhook started")
req = request.get_json(silent=True, force=True)
res = processRequest(req)
res = json.dumps(res, indent=4)
print(res)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
def processRequest(req):
result = req.get("queryResult")
intent = result.get("intent").get('displayName')
parameters = result.get("parameters")
if intent == 'Organiziva_ViewTeams':
try:
username = parameters.get('username')
user = userby_username(username)
webhookresponse = teamsby_username(user)
#print(webhookresponse)
except AttributeError:
webhookresponse = "User "+ username + " does not exist! Please enter a vaid username."
return {
"fulfillmentMessages": [
{
"text": {
"text": [
webhookresponse
]
}
}
]
}
############ * CHATBOT * #################
#########################################
@app.route('/' , methods = ['GET' , 'POST'])
def index():
return render_template("index.htm")
@app.route('/chatbot')
def chatbot():
return render_template('chatbot.htm')
@app.route('/register' , methods = ['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(name = form.name.data,
username = form.username.data,
email = form.email.data ,
password = form.password.data)
db.session.add(user)
db.session.commit()
if form.picture.data is not None:
id = user.id
pic = add_profile_pic(form.picture.data,id)
user.profile_image = pic
db.session.commit()
return redirect(url_for('login'))
return render_template('register.htm', form = form)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for("index"))
@app.route('/login' , methods = ['GET', 'POST'])
def login():
form = LoginForm()
error = ''
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.check_password(form.password.data) :
login_user(user)
flash('Log in Success!')
next = request.args.get('next')
if next == None or not next[0] =='/':
next = url_for('index')
return redirect(next)
elif user is not None and user.check_password(form.password.data) == False:
error = 'Wrong Password'
elif user is None:
error = 'No such login Pls create one'
return render_template('login.htm', form=form, error = error)
@app.route('/maketeam' , methods = ['GET' , 'POST'])
@login_required
def make_team():
form = MakeTeamForm()
if form.validate_on_submit():
error = 'no'
random = secrets.token_hex(8)
randomid = random + form.team_name.data
team = Team(name = form.team_name.data,
password = form.team_password.data,
randomid = randomid,
ownerid = current_user.id)
db.session.add(team)
current_user.teams.append(team)
db.session.commit()
return redirect(url_for('team', team_id = team.randomid))
return redirect(url_for('join_team'))
else:
error = 'ono'
return render_template('maketeam.htm', form = form, error = error)
@app.route('/jointeam' , methods = ['GET' , 'POST'])
@login_required
def join_team():
form = TeamLoginForm()
if form.validate_on_submit():
team = Team.query.filter_by(randomid = form.randomid.data).first()
if team is not None and team.check_password(form.team_password.data) :
current_user.teams.append(team)
db.session.commit()
return redirect(url_for('team', team_id = team.randomid))
elif team is not None and team.check_password(form.team_password.data) == False:
error = 'Wrong Password'
elif team is None:
error = 'Wrong id .'
return render_template('teamlogin.htm', form = form)
########## * ERROR HANDLERS * #############
@app.route('/<team_id>/<type>/makeupcoming', methods = ['GET' , 'POST'])
@login_required
def make_upcoming(team_id,type):
error = ''
zoo = ''
print(type)
team = Team.query.filter_by(randomid = team_id).first()
form = MakeUpcoming()
if form.validate_on_submit():
if team is not None and team.ownerid == current_user.id:
event = Events(teamid = team_id,
title = form.title.data,
event = form.description.data,
type = type)
db.session.add(event)
db.session.commit()
if form.start_date.data is not None and type == 'upcoming' or type == 'completed':
event.start_date = form.start_date.data
db.session.commit()
if type == 'ongoing' :
event.start_date = datetime.now()
db.session.commit()
if type == 'completed':
zoo = 'Looks like You forgot to make this event while it was upcoming or ongoing. Never mind you can store it in our database so that we remember your achievement'
event.end_date = datetime.now()
db.session.commit()
user = []
users = form.users.data
if ',' in users:
user = users.split(',')
elif users == 'all':
for worker in team.workers:
user.append(worker.username)
else:
user.append(users)
for u in user:
worker = User.query.filter_by(username = u).first()
if worker is None or worker not in team.workers:
continue
else:
worker.events.append(event)
db.session.commit()
return redirect(url_for('team' , team_id = team_id))
elif team is not None and team.ownerid != current_user.id :
abort(403)
elif team is None:
abort(404)
return render_template('upcoming.htm' , form = form , type = type , zoo = zoo)
@app.route('/<team_id>/team', methods = ['GET' , 'POST'])
@login_required
def team(team_id):
team = Team.query.filter_by(randomid = team_id).first()
if current_user in team.workers:
team_upcoming = Events.query.filter_by(type = 'upcoming', teamid = team_id).order_by(Events.start_date.asc())
for upcoming in team_upcoming:
if upcoming.start_date is None:
continue
now = datetime.now()
if upcoming.start_date.strftime('%d-%m-%Y') <= now.strftime('%d-%m-%Y'):
return redirect(url_for('change_event' , team_id = team_id , event_id = upcoming.id , type = 'o'))
team_ongoing = Events.query.filter_by(type = 'ongoing', teamid = team_id).order_by(Events.start_date.asc())
team_completed = Events.query.filter_by(type = 'completed', teamid = team_id).order_by(Events.date.asc())
team_owner = team.ownerid
else:
abort(403)
return render_template('team.htm',team = team ,team_owner = team_owner, team_upcoming = team_upcoming,
team_ongoing = team_ongoing , team_completed = team_completed , team_id = team_id )
@app.route('/<team_id>/<event_id>/event', methods = ['GET' , 'POST'])
@login_required
def event(team_id,event_id):
mylist = []
team = Team.query.filter_by(randomid = team_id).first()
if current_user in team.workers:
events = Events.query.filter_by(id = event_id).first()
else:
abort(403)
return render_template('event.htm', events = events , mylist = mylist)
@app.route('/<team_id>/<event_id>/<type>/changeevent', methods = ['GET' , 'POST'])
@login_required
def change_event(team_id,event_id,type):
team = Team.query.filter_by(randomid = team_id).first()
event = Events.query.filter_by(id = event_id).first()
if current_user in team.workers:
if type == 'u':
event.type = 'upcoming'
event.start_date = None
elif type == 'o':
event.type = 'ongoing'
event.start_date = datetime.now()
elif type == 'c':
event.type = 'completed'
event.end_date = datetime.now()
db.session.commit()
else:
abort(403)
return redirect(url_for('team', team_id = team_id))
@app.route('/account',methods = ['GET','POST'])
@login_required
def account():
pic = current_user.profile_image
form = UpdateUserForm()
if form.validate_on_submit():
current_user.email = form.email.data
current_user.username = form.username.data
if form.picture.data is not None:
id = current_user.id
pic = add_profile_pic(form.picture.data,id)
current_user.profile_image = pic
flash('User Account Created')
db.session.commit()
return redirect(url_for('account'))
elif request.method == 'GET':
form.username.data = current_user.username
form.email.data = current_user.email
profile_image = url_for('static', filename= current_user.profile_image)
return render_template('account.htm', profile_image=profile_image, form=form, pic = pic)
@app.route('/<team_id>/teamaccount',methods = ['GET','POST'])
@login_required
def team_account(team_id):
team = Team.query.filter_by(randomid = team_id).first()
if team is not None and current_user.id == team.ownerid:
pic = team.team_image
form = UpdateTeamForm()
if form.validate_on_submit():
team.randomid = form.randomid.data
team.name = form.name.data
if form.picture.data is not None:
id = team.id
pic = add_team_pic(form.picture.data,id)
team.team_image = pic
db.session.commit()
flash('Team Account Created')
db.session.commit()
return redirect(url_for('team_account' , team_id = team_id))
elif request.method == 'GET':
form.randomid.data = team.randomid
form.name.data = team.name
team_image = url_for('static', filename= team.team_image)
else:
abort(403)
return render_template('account_team.htm', team_image=team_image, form=form, pic = pic , team = team)
@app.route('/allteams' , methods = ['GET' , 'POST'])
@login_required
def all_teams():
teams = []
for team in current_user.teams:
teams.append(team)
return render_template('all_teams.htm' , teams = teams )
@app.route('/makerental' , methods = ['GET' , 'POST'])
@login_required
def make_rental():
form = Make_Rental()
if form.validate_on_submit():
id = current_user.id
pic = add_rent_pic(form.picture.data,id)
rent = Rent(thing = form.thing.data,
description = form.description.data,
image = pic,
userid = id,
price = form.price.data)
db.session.add(rent)
db.session.commit()
return redirect(url_for('all_rental'))
return render_template('makerent.htm' , form = form)
@app.route('/allrental' , methods = ['GET' , 'POST'])
@login_required
def all_rental():
rent = Rent.query.filter_by(rented = 'No').order_by(Rent.price.asc())
return render_template('allrent.htm' , rent = rent )
@app.route('/<rent_id>/single' , methods = ['GET' , 'POST'])
@login_required
def single_rent(rent_id):
rent = Rent.query.filter_by(id = rent_id).first()
image = url_for('static' , filename = rent.image)
return render_template('single_rent.htm' , rent = rent , image = image)
@app.route('/<rent_id>/update' , methods = ['GET' , 'POST'])
@login_required
def update(rent_id):
rent = Rent.query.filter_by(id = rent_id).first()
form = UpdateRent()
if rent is None:
abort(404)
elif current_user.id != rent.user.id:
abort(403)
else:
pic = rent.image
if form.validate_on_submit():
rent.thing = form.thing.data
rent.description = form.description.data
rent.price = form.price.data
rent.rented = form.rent.data
if form.picture.data is not None:
id = rent.id
pic = add_rent_pic(form.picture.data,id)
rent.image = pic
db.session.commit()
flash('Rent Account Updated')
db.session.commit()
return redirect(url_for('all_rental'))
elif request.method == 'GET':
form.thing.data = rent.thing
form.description.data = rent.description
form.price.data = rent.price
form.rent.data = rent.rented
image = url_for('static', filename= rent.image)
return render_template('update.htm' , image = image, rent = rent , form = form , rent_id = rent_id)
@app.route('/<rent_id>/delete',methods = ['GET','POST'])
@login_required
def delete(rent_id):
rent = Rent.query.get_or_404(rent_id)
if rent.user != current_user:
abort(403)
db.session.delete(rent)
db.session.commit()
flash('Rent deleted')
return redirect(url_for('all_rental'))
@app.route('/yourrental' , methods = ['GET' , 'POST'])
@login_required
def your_rental():
rent = Rent.query.filter_by(userid = current_user.id).order_by(Rent.price.asc())
return render_template('allrent.htm' , rent = rent)
@app.route('/<team_id>/users' , methods = ['GET' , 'POST'])
@login_required
def user_team(team_id):
team = Team.query.filter_by(randomid = team_id).first()
if current_user not in team.workers:
abort(403)
return render_template('user_team.htm' , team = team)
@app.route('/<team_id>/knowledge' , methods = ['GET' , 'POST'])
@login_required
def all_knowledge(team_id):
team = Team.query.filter_by(randomid = team_id).first()
image = []
if team is None:
abort(404)
if current_user not in team.workers:
abort(403)
else:
knowledge = Knowledge.query.filter_by(teamid = team_id).order_by(Knowledge.date.desc())
return render_template('knowledge.htm' ,team_id = team_id, knowledge = knowledge)
@app.route('/<team_id>/makeknowledge' , methods = ['GET' , 'POST'])
@login_required
def make_knowledge(team_id):
team = Team.query.filter_by(randomid = team_id).first()
if team is not None and current_user not in team.workers:
abort(403)
elif team is None:
abort(404)
else:
form = KnowledgeForm()
if form.validate_on_submit():
knowledge = Knowledge(title = form.title.data,
content=form.content.data,
teamid=team_id,
userid=current_user.id)
db.session.add(knowledge)
db.session.commit()
if form.picture.data is not None:
id = team.id
pic = add_knowledge_pic(form.picture.data,id)
knowledge.image = pic
db.session.commit()
return redirect(url_for('all_knowledge' , team_id = team_id))
return render_template('make_knowledge.htm' , form = form)
@app.route('/<team_id>/<knowledge_id>/single_knowledge' , methods = ['GET' , 'POST'])
@login_required
def single_knowledge(knowledge_id , team_id):
team = Team.query.filter_by(randomid = team_id).first()
if team is None:
abort(404)
elif current_user not in team.workers:
abort(403)
else:
knowledge = Knowledge.query.get_or_404(knowledge_id)
return render_template('single_knowledge.htm' , knowledge = knowledge , team_id = team_id ,team = team)
@app.route('/<team_id>/<knowledge_id>/update' , methods = ['GET' , 'POST'])
@login_required
def update_knowledge(knowledge_id , team_id):
knowledge = Knowledge.query.filter_by(id = knowledge_id).first()
team = Team.query.filter_by(randomid = team_id).first()
image = ''
form = UpdateKnowledgeForm()
if knowledge is None or team is None:
abort(404)
elif current_user.id != knowledge.user.id and current_user.id != team.ownerid:
abort(403)
else:
pic = knowledge.image
if form.validate_on_submit():
knowledge.title = form.title.data
knowledge.content = form.content.data
if form.picture.data is not None:
id = knowledge.id
pic = add_knowledge_pic(form.picture.data,id)
knowledge.image = pic
db.session.commit()
flash('Rent Account Updated')
db.session.commit()
return redirect(url_for('all_knowledge'))
elif request.method == 'GET':
form.title.data = knowledge.title
form.content.data = knowledge.content
if knowledge.image:
image = url_for('static', filename= knowledge.image)
return render_template('update_knowledge.htm' ,team_id = team_id, image = image, knowledge = knowledge , form = form , knowledge_id =knowledge_id)
@app.route('/<team_id>/<knowledge_id>/delete_k',methods = ['GET','POST'])
@login_required
def delete_knowledge(team_id, knowledge_id ) :
knowledge = Knowledge.query.get(knowledge_id)
team = Team.query.filter_by(randomid = team_id).first()
if knowledge is None or team is None:
abort(404)
elif current_user.id != knowledge.user.id and current_user.id != team.ownerid:
abort(403)
else:
db.session.delete(knowledge)
db.session.commit()
flash('Knowledge deleted')
return redirect(url_for('all_knowledge' , team_id = team_id))
@app.route('/<event_id>/<team_id>/delete_event')
@login_required
def delete_event(event_id,team_id):
event = Events.query.filter_by(id = event_id).first()
team = Team.query.filter_by(randomid = team_id).first()
if event is None:
abort(404)
elif current_user.id != team.ownerid:
abort(403)
else:
db.session.delete(event)
db.session.commit()
return redirect(url_for('team' , team_id = team_id))
@app.route('/whiteboard/<team_id>')
def whiteboard(team_id):
team = Team.query.filter_by(randomid = team_id).first()
if team is None:
abort(404)
elif current_user not in team.workers:
abort(403)
return render_template('whiteboard.html' , team = team )
@app.route('/<team_id>/vc', methods=['GET','POST'])
@login_required
def vc(team_id):
team = Team.query.filter_by(randomid = team_id).first()
if team is None:
abort(404)
elif current_user not in team.workers:
abort(403)
return render_template('vc.html' , team_id = team_id , team = team)
@app.route('/vc_login', methods=['POST'])
@login_required
def vc_login():
username = request.get_json(force=True).get('username')
if not username:
abort(401)
token = AccessToken(twilio_account_sid, twilio_api_key_sid,
twilio_api_key_secret, identity=username)
token.add_grant(VideoGrant(room='My Room'))
return {'token': token.to_jwt().decode()}
@app.route('/<teamid>/chat' , methods = ['GET' , 'POST'])
@login_required
def sessions(teamid):
team = Team.query.filter_by(randomid = teamid).first()
if team is None or current_user not in team.workers:
abort(403)
return render_template('chat.html')
def messageReceived(methods=['GET', 'POST']):
print('message was received!!!')
@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
print('received my event: ' + str(json))
socketio.emit('my response', json, callback=messageReceived)
###########################################
@app.errorhandler(404)
def page_not_found(e):
return render_template('Error/404.html'), 404
@app.errorhandler(403)
def action_forbidden(e):
return render_template('Error/403.html'), 403
@app.errorhandler(410)
def page_deleted(e):
return render_template('Error/410.html'), 410
@app.errorhandler(500)
def internal_server_error(e):
return render_template('Error/500.html'), 500
##############################################
if __name__ == '__main__':
socketio.run(app,debug=True)