-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
630 lines (534 loc) · 23.8 KB
/
app.py
File metadata and controls
630 lines (534 loc) · 23.8 KB
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
import logging
import os
import pymysql
import re
import meeting
from model import DBManager, Message
from flask import render_template, request, session, redirect, url_for, Flask, jsonify
from mysql import connector
from passlib.hash import sha256_crypt
from flask_socketio import SocketIO, join_room, leave_room
from datetime import datetime
import pickle
app = Flask(__name__)
# !--- For debugging switch to true ---!
app.debug = True
UPLOAD_FOLDER = '/vagrant/static/images/'
#UPLOAD_FOLDER = '/static/images/'
app.config["SECRET_KEY"] = "OCML3BRawWEUeaxcuKHLpw"
#toolbar = DebugToolbarExtension(app)
socketio = SocketIO(app, manage_session=False, cors_allowed_origins="*")
chatClients = dict()
def definedlog(fileHandler):
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
handler = logging.FileHandler(fileHandler)
handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s : %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
@app.route('/')
def index():
return render_template('/index.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
mycursor = DBManager().getCursor()
message = ""
if request.method == 'POST':
try:
userDetails = request.form
username = userDetails['username']
unQuery = "SELECT username FROM users WHERE username = '" + username + "'"
mycursor.execute(unQuery, username)
username_from_db = mycursor.fetchall()
if username_from_db:
raise Exception('User name already Exists!')
password = userDetails["password1"]
password_confirm = userDetails["password2"]
if password != password_confirm:
raise Exception('Passwords does not match!')
password = sha256_crypt.encrypt(userDetails["password1"])
firstName = userDetails['firstName']
lastName = userDetails['lastName']
phone = userDetails['phone']
email = userDetails['email']
result1 = email.find('@GMAIL.COM')
result2 = email.find('@gmail.com')
result3 = email.find('@gmail.COM')
result4 = email.find('@GMAIL.com')
result5 = email.find('@Gmail.com')
if result1 == -1 and result2 == -1 and result3 == -1 and result4 == -1 and result5 == -1:
error = 'you have to put gmail account in order to use our app'
raise Exception(error)
mycursor = DBManager().getCursor()
sql = "INSERT INTO users (username, password, firstName, lastName, phone, email) VALUES (%s, %s, %s, %s, %s, %s)"
val = (username, password, firstName, lastName, phone, email)
mycursor.execute(sql, val)
DBManager.connection.commit()
session['USERNAME'] = username
return redirect(url_for('homepage'))
except Exception as error:
message = str(error)
return render_template('/register.html', message=message)
@app.route('/login', methods=['GET', 'POST'])
def login():
message = ""
if get_user_logged_in():
return redirect('homepage')
if request.method == "POST":
req = request.form
username = req.get("username")
password = req.get("password")
try:
authenticate_user(username, password)
return redirect(url_for('homepage'))
except Exception as error:
message = str(error)
return render_template('/login.html', message=message)
def authenticate_user(username, password):
maulers = DBManager().getCursor()
Fender = "SELECT username, password FROM users WHERE username = %s"
maulers.execute(Fender, username)
result = maulers.fetchall()
print(result)
for user in result:
if sha256_crypt.verify(password, user[1]):
session["USERNAME"] = user[0]
return True
else:
raise Exception("Password doesn't match")
raise Exception("Username not found")
def get_user_logged_in():
if "USERNAME" in session:
return session["USERNAME"]
return False
@app.route("/homepage", methods=['POST', 'GET'])
def homepage():
un = get_user_logged_in()
ge=''
ar=''
if un:
req = request.form
filter = ""
if request.method == 'POST':
if req.get("filter") == 'submit':
ge = req.get("gender")
ar = req.get("area")
if ge != "all" and ar == "all":
filter = "gender='" + ge + "'"
elif ge == "all" and ar != "all":
filter = "area='" + ar + "'"
elif ge != "all" and ar != "all":
filter = "gender='" + ge + "' and area ='" + ar + "'"
queryhomepage = "SELECT * FROM dogs"
# add query for excluding from likes table
queryhomepage += " WHERE dog_id NOT IN (SELECT dog_id FROM likes WHERE username='" + un + "') " +\
"AND username <> '" + un + "'"
# add query for the filter in homepage
if filter != "":
queryhomepage += " AND " + filter
mycursor = DBManager().getCursor()
mycursor.execute(queryhomepage)
result = mycursor.fetchall()
return render_template('homepage.html', dogs=result,gender=ge,area=ar)
return redirect('login')
def convertToBinaryData(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
binaryData = file.read()
return binaryData
@app.route('/create_dog_profile/', methods=['POST', 'GET'])
def create_dog_profile():
username = get_user_logged_in()
if username:
if request.method == "POST":
try:
details = request.form
name = details['dog_name']
# check if chip already exists
chip = details['chip_number']
mycursor = DBManager().getCursor()
mycursor.execute("SELECT dog_id FROM dogs WHERE dog_id = '" + chip + "'")
chip_from_db = mycursor.fetchall()
if (chip_from_db):
raise Exception('Chip already Exists!')
birth_date = details['birth_date']
gender = details['gender']
area = details['area']
city = details['city']
type = details['type']
description = details['description']
img1 = request.files['files']
path1 = os.path.join('images/', img1.filename)
img1.save(os.path.join(UPLOAD_FOLDER, img1.filename))
photo1 = convertToBinaryData(
os.path.join(UPLOAD_FOLDER, img1.filename))
img2 = request.files['img2']
if img2.filename != '':
img2.save(os.path.join(UPLOAD_FOLDER, img2.filename))
path2 = os.path.join('images/', img2.filename)
photo2 = convertToBinaryData(
os.path.join(UPLOAD_FOLDER, img2.filename))
else:
photo2 = ''
path2 = ''
img3 = request.files['img3']
if img3.filename != '':
path3 = os.path.join('images/', img3.filename)
img3.save(os.path.join(UPLOAD_FOLDER, img3.filename))
photo3 = convertToBinaryData(
os.path.join(UPLOAD_FOLDER, img3.filename))
else:
photo3 = ''
path3 = ''
mycursor.execute(
"INSERT INTO dogs(dog_id,name,bday,gender,area,city, type,details,pic1,path1,pic2,path2,pic3,path3,username) VALUES (%s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
(chip, name, birth_date, gender, area, city, type, description, photo1, path1, photo2, path2, photo3, path3,
username))
DBManager().connection.commit()
message = "Dog added successfully"
except Exception as error:
message = str(error)
else:
message = " "
return render_template('create_dog_profile.html', message=message)
return redirect('/login')
@app.route("/dogProfile/<dog_id>")
def dogProfile(dog_id):
mycursor = DBManager().getCursor()
uname = get_user_logged_in()
if uname:
queryDogProfile = "select * from dogs where dog_id=" + dog_id
mycursor.execute(queryDogProfile)
result = mycursor.fetchall()
return render_template('dogProfile.html', dog=result)
return redirect('login')
@app.route("/favorites/add", methods=['POST'])
def yes_button():
username = get_user_logged_in()
if username and 'dog_id' in request.form:
details = request.form
dog_id = details['dog_id']
answer = details['answer']
if answer == 'yes' or answer == 'no':
mycursor = DBManager().getCursor()
mycursor.execute(
"INSERT INTO likes VALUES (%s, %s,%s)",
(username, dog_id, answer))
DBManager().connection.commit()
return 'success'
return 'fail'
@app.route("/favorites/", methods=['POST', 'GET'])
def favorites():
username = get_user_logged_in()
if username:
if request.method == 'POST':
details = request.form
clear_but = details['clear']
if clear_but == 'yes':
clearChoices(username)
return redirect('/homepage')
query_favorites = "select * from dogs left join likes on likes.dog_id = dogs.dog_id where likes.username='" + \
username + "' AND answer='yes' AND dogs.username <> '" + username + "'"
mycursor = DBManager().getCursor()
mycursor.execute(query_favorites)
dogs = mycursor.fetchall()
DBManager().connection.commit()
DBManager().closeConnection()
return render_template('favorites.html', dogs=dogs)
return redirect('/login')
@app.route('/new_meeting', methods=['GET', 'POST'])
def new_meeting():
'''
:return: new_meeting template
'''
return render_template('/new_meeting.html')
@app.route("/favorites/add_meeting", methods=['POST'])
def add_meeting():
'''
send a proposal for a meeting to dog owner
:return: homepage template
'''
mycursor = DBManager().getCursor()
details = request.form
username = get_user_logged_in()
mycursor.execute("select username from dogs where dog_id=" + details['dog'])
owner_username = mycursor.fetchone()
mycursor.execute("select name from dogs where dog_id=" + details['dog'])
dog_name = mycursor.fetchone()
DBManager().connection.commit()
sending_date = datetime.now()
#sending_date_formated = sending_date.strftime('%Y-%m-%d %H:%M:%S')
date_time = details['time'].split('T')
# the template massage: 'Can I meet {} in {} in {} at {}?\nYes/No'
msg = Message(username, owner_username[0], 'Can I meet ' + dog_name[0] + ' in ' + date_time[0] + ' in ' + date_time[1] + ' at ' + details['place'] + '?\nYes/No', sending_date, 'True')
send_message(msg, False)
return redirect('/homepage')
def clearChoices(username):
queryClear = "DELETE FROM likes WHERE username='" + username + "'"
mycursor = DBManager().getCursor()
mycursor.execute(queryClear)
DBManager().connection.commit()
@app.route('/help')
def help():
uname = get_user_logged_in()
if uname:
return render_template('/help.html')
return redirect('login')
@app.route('/updateUser', methods=['POST', 'GET'])
def updateUser():
message=None
mycursor = DBManager().getCursor()
uname = get_user_logged_in()
if uname:
mycursor.execute(
"SELECT * FROM users WHERE username = '" + uname + "'")
user = mycursor.fetchall()
if request.method == 'POST':
try:
formDetails = request.form
name = formDetails['name']
if name != "":
sql = "UPDATE users SET firstName = '" + \
name + "' WHERE username = '" + uname + "'"
mycursor.execute(sql)
DBManager().connection.commit()
lastname = formDetails['lastname']
if lastname != "":
sql = "UPDATE users SET lastName = '" + \
lastname + "' WHERE username = '" + uname + "'"
mycursor.execute(sql)
DBManager().connection.commit()
phone = formDetails["tel"]
if phone != "":
sql = "UPDATE users SET phone = '" + phone + \
"' WHERE username = '" + uname + "'"
mycursor.execute(sql)
DBManager().connection.commit()
mail = formDetails['mail']
if mail != "":
result1 = mail.find('@GMAIL.COM')
result2 = mail.find('@gmail.com')
result3 = mail.find('@gmail.COM')
result4 = mail.find('@GMAIL.com')
result5 = mail.find('@Gmail.com')
if result1 == -1 and result2 == -1 and result3 == -1 and result4 == -1 and result5 == -1 :
error = 'you have to put gmail account in order to use our app'
raise Exception(error)
else:
sql = "UPDATE users SET email = '" + mail + "' where username = '" + uname + "'"
mycursor.execute(sql)
DBManager().connection.commit()
message = "your details were updates successfully"
newpass = formDetails["newpass"]
renewpass = formDetails["confirm"]
if (newpass != "") & (renewpass != ""):
if newpass == renewpass:
newpass = sha256_crypt.encrypt(newpass)
sql = "UPDATE users SET password='" + newpass + "' where username='" + uname + "'"
mycursor.execute(sql)
DBManager().connection.commit()
message = "your details were updates successfully"
else:
message = "new password does NOT match to confirm password"
mycursor.execute(
"SELECT * FROM users WHERE username = '" + uname + "'")
user = mycursor.fetchall()
except Exception as error:
message = str(error)
else:
message = ""
return render_template("updateUser.html", dogs=showDogs(), user=user, m=message)
return redirect('login')
def showDogs():
mycursor = DBManager().getCursor()
un = session["USERNAME"]
queryShowDogs = "select dog_id,name from dogs where username='" + un + "'"
mycursor.execute(queryShowDogs)
result = mycursor.fetchall()
return result
@app.route("/updateUser/<dog_id>", methods=['POST', 'GET'])
def updateDog(dog_id):
if request.method == 'POST':
formDetails = request.form
if 'delete' in formDetails:
deleteDog(dog_id)
elif 'adopt' in formDetails:
adopted(dog_id)
return redirect('/updateUser')
def deleteDog(dog_id):
mycursor = DBManager().getCursor()
queryDeleteDog = "DELETE FROM dogs WHERE dog_id =" + dog_id
mycursor.execute(queryDeleteDog)
DBManager().connection.commit()
queryDeleteDog = "DELETE FROM likes WHERE dog_id =" + dog_id
mycursor.execute(queryDeleteDog)
DBManager().connection.commit()
return True
def adopted(dog_id):
mycursor = DBManager().getCursor()
mycursor.execute(
"INSERT INTO adopted SELECT d.* FROM dogs AS d WHERE dog_id = " + dog_id)
DBManager().connection.commit()
deleteDog(dog_id)
return True
#region chat_logic
def add_message_to_db(msg: Message) -> bool:
message_id = None
if msg.receiver and msg.content.strip() != '':
mycursor = DBManager.getCursor()
sql = "INSERT INTO messages (sender_username, receiver_username, content, sending_date, meeting_proposal) VALUES (%s, %s, %s, %s, %s)"
val = (msg.sender, msg.receiver, msg.content, msg.date.strftime('%Y-%m-%d %H:%M:%S'), msg.meeting_proposal)
mycursor.execute('select * from messages where sender_username="' + msg.receiver + '" and receiver_username="' + msg.sender + '" order by sending_date desc Limit 1')
last_massage= mycursor.fetchone()
print(last_massage)
# check if the last message was a meeting proposal and the owner replied yes
if last_massage is not None and msg.content.lower() == 'yes' and last_massage[5] == 'True':
mycursor.execute("select email from users where username='" + msg.sender + "'")
owner_email = mycursor.fetchone()
mycursor.execute("select email from users where username='" + msg.receiver + "'")
username_email = mycursor.fetchone()
# extract name place and time from the meeting proposal message
matches = re.findall(r'Can I meet (\S+) in (\S+) in (\S+) at (.*?)\?\nYes/No', last_massage[3])[0]
#meeting_output = os.popen('python meeting//create_meeting.py "' + matches[0] +'" "' + matches[3] + '" ' + matches[1] + 'T' + matches[2] + ' ' + owner_email[0] + ' ' + username_email[0]).read()
#print(f'end creating meeting: {meeting_output}')
meeting.create_meeting(dog_name=matches[0], place=matches[3], time=f'{matches[1]}T{matches[2]}', owner_email=owner_email[0], client_email=username_email[0])
try:
mycursor.execute(sql, val)
DBManager.connection.commit()
message_id = mycursor.lastrowid
print(f'inserted message with id {message_id}')
except Exception as error:
print(f'error in add_message_to_db: {str(error)}')
return message_id
def get_all_chats(sender_username):
view = []
try:
mycursor = DBManager.getCursor()
mycursor.execute("SELECT d.username FROM dogs d " +
"INNER JOIN likes l ON l.dog_id = d.dog_id " +
"WHERE l.username=%(sender)s " +
"AND d.dog_id NOT IN (SELECT dog_id FROM adopted) " +
"AND d.username <> %(sender)s " +
"AND l.answer='yes'" +
"UNION " +
"SELECT l.username FROM dogs d " +
"INNER JOIN likes l ON l.dog_id = d.dog_id " +
"WHERE d.username=%(sender)s " +
"AND l.username <> %(sender)s " +
"AND l.answer='yes'" +
"AND d.dog_id NOT IN (SELECT dog_id FROM adopted) " +
"ORDER BY 1 ASC", { 'sender': sender_username, })
view = mycursor.fetchall()
DBManager.closeConnection()
except Exception as error:
print(f'error in get_all_chats: {str(error)}')
return view
def get_all_messages(sender, receiver):
view = []
try:
mycursor = DBManager.getCursor()
mycursor.execute("SELECT * FROM messages WHERE (sender_username = %(sender)s AND receiver_username = %(receiver)s) " +
"OR (receiver_username = %(sender)s AND sender_username = %(receiver)s)" +
"ORDER BY sending_date ASC", { 'sender': sender,
'receiver': receiver})
view = mycursor.fetchall()
DBManager.closeConnection()
except Exception as error:
print(f'error in get_all_messages: {str(error)}')
return view
def join_chat(chatRoom):
uname = get_user_logged_in()
if uname not in chatClients or chatClients[uname] != chatRoom:
# leave last room before connecting to another
if uname in chatClients:
leave_room(chatClients[uname])
chatClients[uname] = chatRoom
join_room(chatRoom)
print(uname + ' has entered the room ' + chatRoom)
@app.route("/chat/<receiver_username>", methods=['GET', 'POST'])
@app.route("/chat/", defaults={'receiver_username':''})
def chat(receiver_username=None):
username = get_user_logged_in()
if username:
chatsList = get_all_chats(username)
return render_template('chat.html', chats=chatsList)
return redirect('/login')
@app.route("/chat_messages/<receiver_username>", methods=['GET', 'POST'])
def chat_messages(receiver_username):
messagesList = []
username = get_user_logged_in()
if username and receiver_username:
chatsList = get_all_chats(username)
# make sure chat exists before getting messages
if receiver_username and (f'{receiver_username}',) in chatsList:
messagesList = get_all_messages(username, receiver_username)
return render_template('chatMessages.html', messages=messagesList)
raise Exception(f'Failed when trying to fetch chat messages for {receiver_username}')
@socketio.on('connection')
def handle_connection(data):
uname = get_user_logged_in()
print(f'{uname} has connected')
@socketio.on('disconnect')
def handle_disconnect():
uname = get_user_logged_in()
print(f'{uname} has disconnected')
@socketio.on('join_chat')
def on_join(data):
if data and 'receiver' in data:
receiver_username = data['receiver']
chatRoom = f'{request.sid}#{receiver_username}'
join_chat(chatRoom)
@socketio.on('leave_chat')
def on_leave(data):
uname = get_user_logged_in()
if uname and uname in chatClients:
del chatClients[uname]
if uname and 'CHAT_ROOM' in session:
receiver_username = session['CHAT_ROOM']
chatRoom = f'{request.sid}#{receiver_username}'
leave_room(chatRoom)
print(uname + ' has left the room ' + chatRoom)
@socketio.on('send_message')
def on_send_message(json, methods=['GET', 'POST']):
print('received my event: ' + str(json))
sender_username = get_user_logged_in()
# check if there is a receiver for the message before sending
#if 'CHAT_ROOM' in session:
# receiver_username = session.get('CHAT_ROOM', None)
if sender_username in chatClients:
receiver_username = chatClients[sender_username].split("#")[1]
content = json['message']
sending_date = datetime.now()
print(f'message: {content} from { sender_username } to { receiver_username }')
# insert message to db
msg = Message(sender_username, receiver_username, content, sending_date, 'False')
send_message(msg, include_sender=True)
else:
print('chat room wasnt open with the receiver')
def send_message(msg: Message, include_sender:bool):
# insert message to db
msg.id = add_message_to_db(msg)
# send message to client and reciever if insertion succeeded
if msg.id:
print(f'Message {msg.id} was inserted')
# get template of message
msgArray = [[msg.id, msg.sender, msg.receiver, msg.content, msg.date]]
if include_sender:
# approve message was sent to the client
socketio.emit('message_received', render_template('chatMessages.html', messages=msgArray), room=chatClients[msg.sender])
# make sure receiver is in chat room with the sender
if msg.receiver in chatClients and chatClients[msg.receiver].split("#")[1] == msg.sender:
socketio.emit('message_received', render_template('chatMessages.html', messages=msgArray, logged_in_user=msg.receiver), room=chatClients[msg.receiver])
else:
print('insertion failed')
#endregion
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', debug=True)
pass