-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.py
2591 lines (2105 loc) · 113 KB
/
admin.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
import pickle
from socket import *
from threading import Thread
from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfilenames, askopenfilename, askopenfile
from tkinter.scrolledtext import ScrolledText
import geocoder
from tkcalendar import *
import tkinter.font as tkFont
import ssl
import warnings
from maps.map import App
from PIL import ImageTk
from PIL import Image
from datetime import datetime
import random as rand
from data_base.manage_data_base import *
import re
import os.path
from tkinter import ttk
import maps.map as map
from customtkinter import *
from client import Client
import json
from tkvideo import tkvideo
f = ('Open Sans', 16)
PATH = os.path.dirname(os.path.realpath(__file__))
class Admin:
"""
Admin class extends the regular user class and adds features of it's own such as
admin reports, a unique admin map and attractions loading
"""
def __init__(self):
# ignoring deprecation warning
warnings.filterwarnings("ignore", category=DeprecationWarning)
# starting socket, wrapping with ssl
self.client = ssl.wrap_socket(socket(AF_INET, SOCK_STREAM), server_side=False)
if len(gethostbyname_ex(gethostname())[-1]) > 1:
self.__HOST = gethostbyname_ex(gethostname())[-1][0]
else:
self.__HOST = gethostbyname_ex(gethostname())[-1][-1]
self.__HOST = "172.16.2.74"
self._BUFFER = 1024
self._ADDR = (self.__HOST, 50002)
# initiating important variables to avoid errors
self.event_handler = Event()
self.__logged_in = False
self.map = None
self.filename = None
self._save_image = b""
self.start_image = False
self.ratings = dict({})
self.map_data = [None for i in range(10)]
self.is_admin = False
self.already_offered, self.already_registered = 0, 0
self.user_data = [None for i in range(
10)] # [self.login_users, self.login_passwords, self.user_id, self.login_purchases, self.user_exists, self.user_data]
self.room_data = [None for i in range(5)] # [room name by offer_id, room average rating]
self.admin_data = [None for i in range(
8)] # [is_admin, self.records, self.offers, self.purchases, search_by_query (record), self.name, self.search_by_query (purchase)# ,
# self.ratings# , self.query_for_rating]
self.root = None
self.updated_offers = None
self.attractions = []
self.admin_map = None
self.disputed_id = []
# initiating the server time
self.server_time = self.server_time = datetime.now().strftime("%Y/%m/%d")
def make_directory_for_map(self, path):
"""
function makes the directory in the running directory for the map_images
:param path:
:return: None
"""
# if directory already exists, saving in there the images for the map
if os.path.isdir(path):
with open(path + "\\" + self.image_save, "wb") as f:
f.write(self._save_image)
else:
# making directory called "map_images"
# directory will save the images for the map
parent_dir = PATH
directory = "map_images"
path = os.path.join(parent_dir, directory)
if not os.path.exists(path):
os.mkdir(path)
with open(path + "\\" + self.image_save, "wb") as f:
f.write(self._save_image)
def recieve(self):
"""
Function receives input from server and handles it
"""
while 1:
try:
# expecting image
while self.start_image:
d = self.client.recv(self._BUFFER)
self._save_image += d
if len(d) < self._BUFFER:
self.start_image = False
# saving in directory for map_images
self.make_directory_for_map(PATH + r"\map_images")
self._save_image = b""
break
# receiving data from the server
data = self.client.recv(self._BUFFER)
try:
# name of the image
if data.decode().startswith("NAME"):
self.image_save = data.decode().split(" ")[1][data.decode().split(" ")[1].rfind("/") + 1:]
self.start_image = True
except UnicodeDecodeError:
pass
# pickling the data
pickle_data = pickle.loads(data)
# if the data received is type dictionary
if type(pickle_data) == dict:
self.offers = pickle.loads(data)
if self.map is not None:
# updating markers
self.updated_offers = pickle_data
self.map.update_markers(self.updated_offers)
# if the data received is type list
elif type(pickle_data) == list:
# handling data received from server
# if user tries to log in
if pickle_data[0] == "#LOGIN ANSWER#":
self.user_data[0] = pickle_data[1]
self.user_data[1] = pickle_data[2]
# if needed to update the current offers
elif pickle_data[0] == "#UPDATED OFFERS#":
self.updated_offers = pickle_data[1]
if self.map is not None:
# updating markers on the map
self.map.update_markers(self.updated_offers)
continue
# if record answer was sent
elif pickle_data[0] == "#RECORD ANSWER#":
self.user_data[2] = pickle_data[1]
# if logged purchases was sent
elif pickle_data[0] == "#LOGGED PURCHASES#":
self.user_data[3] = pickle_data[1]
# if room names were sent
elif pickle_data[0] == "#ROOM NAMES#":
self.map_data[0] = pickle_data[1]
continue
# if offers ordered by the price was sent
elif pickle_data[0] == "#OFFERS ORDERED BY PRICE#":
self.map_data[1] = pickle_data[1]
# if a location by room name was sent
elif pickle_data[0] == "#LOCATION BY ROOM NAMES#":
self.map_data[2] = pickle_data[1]
# if data on offer was sent
elif pickle_data[0] == "#INFORMATION ON OFFER#":
self.map_data[3] = pickle_data[1]
# if offer by purchase id was sent
elif pickle_data[0] == "#OFFER BY PURCHASE ID#":
self.map_data[4] = pickle_data[1]
# if purchase by offer id was sent
elif pickle_data[0] == "#PURCHASE BY OFFER ID#":
self.map_data[5] = pickle_data[1]
# if offers that are ordered by their rating were sent
elif pickle_data[0] == "#OFFERS ORDERED BY AVERAGE RATING#":
self.map_data[6] = pickle_data[1]
# if room name by offer id was sent
elif pickle_data[0] == "#ROOM NAME BY OFFER ID#":
self.room_data[0] = pickle_data[1]
# if rating by offer id was sent
elif pickle_data[0] == "#RATING BY OFFER ID#":
self.room_data[1] = pickle_data[1]
# if review by offer id was sent
elif pickle_data[0] == "#REVIEW BY OFFER ID#":
self.room_data[2] = pickle_data[1]
# if user is admin
elif pickle_data[0] == "#ADMIN ANSWER#":
self.admin_data[0] = pickle_data[1]
# if the 'records' table was sent
elif pickle_data[0] == "#ADMIN RECORDS#":
self.admin_data[1] = pickle_data[1]
# if the 'offers' table was sent
elif pickle_data[0] == "#ADMIN OFFERS#":
self.admin_data[2] = pickle_data[1]
# if 'purchases' table was sent
elif pickle_data[0] == "#ADMIN PURCHASES#":
self.admin_data[3] = pickle_data[1]
# if an admin query for a record was sent
elif pickle_data[0] == "#ADMIN QUERY FOR RECORD#":
self.admin_data[4] = pickle_data[1]
# if 'ratings' table was sent
elif pickle_data[0] == "#ADMIN RATINGS#":
self.admin_data[6] = pickle_data[1]
# if a new offer was sent, and needed to add a marker
elif pickle_data[0] == "#NEW MARKER#" and self.map is not None:
self.map.add_marker(pickle_data[1], pickle_data[2], pickle_data[3])
if self.admin_map is not None:
self.admin_map.add_marker(pickle_data[1], pickle_data[2], pickle_data[3])
continue
# if a name by email was sent
elif pickle_data[0] == "#NAME BY EMAIL#":
self.user_data[5] = pickle_data[1]
# if an admin query for purchase was sent
elif pickle_data[0] == "#ADMIN QUERY FOR PURCHASE#":
self.admin_data[5] = pickle_data[1]
# if an admin query for rating was sent
elif pickle_data[0] == "#ADMIN QUERY FOR RATING#":
self.admin_data[7] = pickle_data[1]
# if offer by email was sent
elif pickle_data[0] == "#OFFER BY EMAIL#":
self.user_data[6] = pickle_data[1]
# if time is up for a certain purchase
elif pickle_data[0] == "#TIME IS UP FOR PURCHASE#":
messagebox.showinfo("info", f"Your purchase duration was up for dates\n"
f"{pickle_data[1]}\nPlease rate")
# if a review was sent by offer id
elif pickle_data[0] == "#REVIEW BY OFFER ID#":
self.room_data[2] = pickle_data[1]
# if a new attraction was sent
elif pickle_data[0] == "#NEW ATTRACTION#":
# adding to regular map and to admin map
if self.map is not None:
self.map.add_attraction(*pickle_data[1])
if self.admin_map is not None:
self.admin_map.add_attraction(*pickle_data[1])
else:
self.attractions.append(pickle_data[1])
# if user has disputed offer
elif pickle_data[0] == "#DELETE MARKER#":
# getting the data on the marker
location = list(set(self.offers.items()) - set(pickle_data[1].items()))[0][1][7]
room_name = list(set(self.offers.items()) - set(pickle_data[1].items()))[0][1][6]
key = list(set(self.offers.items()) - set(pickle_data[1].items()))[0][0]
self.offers.pop(key)
if self.map is not None:
# deleting marker from the map
self.map.delete_marker(location, room_name, key)
self.disputed_id.append(key)
continue
# if admin has requested to make a certain table in the data base a .csv file
elif pickle_data[0] == "#NEW CSV FILE#":
with open(PATH + "\\" + pickle_data[1], "wb") as f:
f.write(pickle_data[2])
messagebox.showinfo("Success", f"Data Base {pickle_data[1]} was saved in a csv file",
icon="info")
continue
except pickle.UnpicklingError:
# handling data that doesn't need to be pickled
try:
data = data.decode()
except UnicodeDecodeError:
pass
if data == "":
pass
# if user already exists
if data == "#USER ALREADY EXISTS#":
self.user_data[4] = True
# if user doesn't exist
elif data == "#USER DOESN'T EXISTS#":
self.user_data[4] = False
# if user has already rated
elif data == "#AlREADY RATED#":
messagebox.showerror("Error", "You have already rated")
except (EOFError, OSError, ssl.SSLEOFError):
# if there is any connections problems with the server, making user exit
self.user_quit()
break
def change_name(self):
"""
function shows form for changing name for the user
:return: None
"""
# clearing screen
Client.clear_screen(self.root, self.menubar, self.on_closing)
# creating frame for form and images
bigger_frame = Frame(self.root, width=700, height=700, bg="white")
# setting images and widgets
CTkLabel(bigger_frame, text="Change Name", text_font=("Roboto Medium", -40), bg="white").pack(pady=30)
img = ImageTk.PhotoImage(Image.open("airbnb_images//airbnb_sign_up2.png").resize((350, 290)))
login_lable = Label(bigger_frame, image=img, borderwidth=0, bg='white')
login_lable.image = img
login_lable.pack(side="left", expand=1, fill=BOTH, padx=20)
# widgets of the form
change_frame = Frame(bigger_frame, bd=2, bg="#F5F5F5", relief=SOLID, padx=10, pady=10, height=300)
CTkLabel(change_frame, text="Enter New Name", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=0,
column=0,
sticky=W,
pady=10)
CTkLabel(change_frame, text="Enter Password", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=1,
column=0,
pady=10)
# creating change entries
self.name_tf = CTkEntry(change_frame, width=200, placeholder_text="Enter New Name")
self.pwd_tf = CTkEntry(change_frame, show='*', width=200, placeholder_text="Enter Password")
self.change_btn = CTkButton(change_frame, width=200, text='Submit', relief=SOLID, cursor='hand2',
fg_color="#E0E0E0", hover_color="#33A8FF", border_width=3,
text_font=("Roboto Medium", -18),
command=lambda: self.send_to_server_change("name"))
# widgets placement
self.name_tf.grid(row=0, column=1, pady=10, padx=20)
self.pwd_tf.grid(row=1, column=1, pady=10, padx=20)
self.change_btn.grid(row=4, pady=(20, 20), column=1)
change_frame.pack(side="left", pady=70)
bigger_frame.pack(padx=50, pady=50)
def send_to_server_change(self, credential):
"""
function sends to server what to credential to change and that data on the user
:param credential: the credential to change
:return: None
"""
if credential == "name":
# make sure entries are not empty
if self.name_tf.get() == "":
messagebox.showwarning("Warning", "Your new name can't be empty", icon="warning")
return
elif self.pwd_tf.get() == "":
messagebox.showwarning("Warning", "Your password can't be empty", icon="warning")
return
# sending to server to change credentials
self.client.send(pickle.dumps(["#CHANGE CREDENTIALS# name", self.name_tf.get(), self.pwd_tf.get()]))
messagebox.showinfo("Success", f"Name has changed to {self.name_tf.get()}")
self.user_data[5] = self.name_tf.get()
# clean entries
self.name_tf.delete(0, END)
self.pwd_tf.delete(0, END)
# process repeats for email, and password changing
elif credential == "email":
if self.email_tf.get() == "":
messagebox.showwarning("Warning", "Your new email can't be empty", icon="warning")
return
elif self.pwd_tf.get() == "":
messagebox.showwarning("Warning", "Your password can't be empty", icon="warning")
return
self.client.send(pickle.dumps(["#CHANGE CREDENTIALS# email", self.email_tf.get(), self.pwd_tf.get()]))
messagebox.showinfo("Success", f"Email has changed to {self.email_tf.get()}")
self.uemail = self.email_tf.get()
self.email_tf.delete(0, END)
self.pwd_tf.delete(0, END)
elif credential == "password":
if self.pwd_tf.get() == "":
messagebox.showwarning("Warning", "Your password cannot be empty", icon="warning")
return
elif self.new_pwd_tf.get() == "":
messagebox.showwarning("Warning", "Your new password can't be empty", icon="warning")
return
elif self.new_pwd_again_tf.get() == "":
messagebox.showwarning("Warning", "Your re-entering password cannot be empty", icon="warning")
return
if self.new_pwd_tf.get() != self.new_pwd_again_tf.get():
messagebox.showwarning("Warning", "New Password and Re-Enter New Password must match!", icon="warning")
return
self.client.send(pickle.dumps(["#CHANGE CREDENTIALS# password", self.new_pwd_tf.get(), self.pwd_tf.get()]))
messagebox.showinfo("Success", f"Password has changed to {self.new_pwd_tf.get()}")
self.pwd_tf.delete(0, END)
self.new_pwd_tf.delete(0, END)
self.new_pwd_again_tf.delete(0, END)
def change_password(self):
"""
function shows form for change password
:return: None
"""
# clearing screen
Client.clear_screen(self.root, self.menubar, self.on_closing)
bigger_frame = Frame(self.root, width=700, height=700, bg="white")
# setting images and widgets
CTkLabel(bigger_frame, text="Change Name", text_font=("Roboto Medium", -40), bg="white").pack(pady=30)
img = ImageTk.PhotoImage(Image.open("airbnb_images//airbnb_sign_up2.png").resize((350, 290)))
login_lable = Label(bigger_frame, image=img, borderwidth=0, bg='white')
login_lable.image = img
login_lable.pack(side="left", expand=1, fill=BOTH, padx=20)
# creating widgets for form
change_frame = Frame(bigger_frame, bd=2, bg="#F5F5F5", relief=SOLID, padx=10, pady=10, height=300)
CTkLabel(change_frame, text="Enter Password", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=0,
column=0,
sticky=W,
pady=10)
CTkLabel(change_frame, text="Enter New Password", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=1,
column=0,
pady=10,
sticky=W)
CTkLabel(change_frame, text="Re-Enter New Password", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=2,
column=0,
pady=10,
sticky=W)
# creating change entries
self.pwd_tf = CTkEntry(change_frame, width=200, placeholder_text="Enter Password")
self.new_pwd_tf = CTkEntry(change_frame, show='*', width=200, placeholder_text="Enter New Password")
self.new_pwd_again_tf = CTkEntry(change_frame, show='*', width=200, placeholder_text="Re-Enter Password")
self.change_btn = CTkButton(change_frame, width=200, text='Submit', relief=SOLID, cursor='hand2',
fg_color="#E0E0E0", hover_color="#33A8FF", border_width=3,
text_font=("Roboto Medium", -18),
command=lambda: self.send_to_server_change("password"))
# widgets placement
self.pwd_tf.grid(row=0, column=1, pady=10, padx=20)
self.new_pwd_tf.grid(row=1, column=1, pady=10, padx=20)
self.new_pwd_again_tf.grid(row=2, column=1, pady=10, padx=20)
self.change_btn.grid(row=4, pady=(20, 20), column=1)
change_frame.pack(side="left", pady=70)
bigger_frame.pack(padx=50, pady=50)
def change_email(self):
"""
function shows form for change password
:return: None
"""
# clearing screen
Client.clear_screen(self.root, self.menubar, self.on_closing)
# creating frame for the widgets
bigger_frame = Frame(self.root, width=700, height=700, bg="white")
# setting images and widgets
CTkLabel(bigger_frame, text="Change Email", text_font=("Roboto Medium", -40), bg="white").pack(pady=30)
img = ImageTk.PhotoImage(Image.open("airbnb_images//airbnb_sign_up2.png").resize((350, 290)))
login_lable = Label(bigger_frame, image=img, borderwidth=0, bg='white')
login_lable.image = img
login_lable.pack(side="left", expand=1, fill=BOTH, padx=20)
# creating widgets for the form
change_frame = Frame(bigger_frame, bd=2, bg="#F5F5F5", relief=SOLID, padx=10, pady=10, height=300)
CTkLabel(change_frame, text="Enter New Email", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=0,
column=0,
sticky=W,
pady=10)
CTkLabel(change_frame, text="Enter Password", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=1,
column=0,
pady=10)
# creating change entries
self.email_tf = CTkEntry(change_frame, width=200, placeholder_text="Enter New Email")
self.pwd_tf = CTkEntry(change_frame, show='*', width=200, placeholder_text="Enter Password")
self.change_btn = CTkButton(change_frame, width=200, text='Submit', relief=SOLID, cursor='hand2',
fg_color="#E0E0E0", hover_color="#33A8FF", border_width=3,
text_font=("Roboto Medium", -18),
command=lambda: self.send_to_server_change("email"))
# widgets placement
self.email_tf.grid(row=0, column=1, pady=10, padx=20)
self.pwd_tf.grid(row=1, column=1, pady=10, padx=20)
self.change_btn.grid(row=4, pady=(20, 20), column=1)
change_frame.pack(side="left", pady=70)
bigger_frame.pack(padx=50, pady=50)
def log_out(self):
"""
function logs out of the system
:return: None
"""
if self.__logged_in:
self.__logged_in = False
messagebox.showinfo("info", "You have logged out\n"
"Since this is admin we will close the window for you\n"
"If you wish to enter again, you must reopen the window\n"
"Thank you")
self.on_closing(True)
else:
# handling errors
messagebox.showerror("Error", "You are not logged in")
def change_date_for_admin(self):
"""
function shows form and changes the date of the system (for admin only)
:return: None
"""
# starting the root
date_root = Toplevel(self.root)
date_root.resizable(False, False)
var = DoubleVar()
# creating root, and calendar for changing the date
CTkLabel(date_root, text=f"Please the current date you want to change to", bg='#04AA6D',
text_font=("Roboto Medium", -20)).pack(pady=5)
# creating entry for change of date
self.date_change = DateEntry(date_root, font=f, locale='en_US', date_pattern='dd/mm/yyyy',
mindate=datetime.now())
self.date_change.pack(pady=10)
# submit button, sending to server the new date
CTkButton(date_root, fg_color="#E0E0E0", hover_color="#33A8FF",
border_width=3, text_font=("Roboto Medium", -18), relief=SOLID, cursor='hand2', text="Submit",
command=lambda: [self.client.send(str(self.date_change.get_date()).replace("-", "/").encode()),
messagebox.showinfo("Success", "Date Changed\n"),
date_root.destroy()]).pack(pady=10)
def convert_address_to_location(self):
"""
function converts address to location for the user to enter when
he/she offers a room
:return: None
"""
# creating root
self.location_root = Toplevel(self.root)
self.location_root.resizable(False, False)
frame = Frame(self.location_root)
# creating label
CTkLabel(self.location_root, text=f"Please enter an address\n\n", bg='#F5F5F5',
text_font=("Roboto Medium", -30)).pack(pady=10)
# creating the entry for
self.loc = CTkEntry(frame, width=200, placeholder_text="Enter Address")
self.loc.pack(side="left", padx=5)
# submit button
self.w = CTkButton(frame, fg_color="#E0E0E0", hover_color="#33A8FF",
border_width=3, text_font=("Roboto Medium", -18), relief=SOLID, cursor='hand2',
text="Submit",
command=lambda: self.calculate_address(self.loc.get()))
self.w.pack(side="left", padx=5)
# widget placements
frame.pack(pady=5)
self.lbl = CTkLabel(self.location_root, text="",
text_font=("Roboto Medium", -15))
self.lbl.pack(pady=3)
def calculate_address(self, address_string):
"""
function calculates geocode of an address
:param address_string: the address
:return: geocode of an address
"""
x, y = geocoder.osm(address_string).latlng
self.lbl.config(text="Your location is \n\n"
f"'{x, y}'", bg='#F5F5F5')
def on_closing(self, admin_log_out=None, close_immediately=None):
"""
function makes sure closing tkinter root goes without errors, closes root and client socket
admin_log_out: if admin is logging out
:return: None
"""
if close_immediately is not None:
self.root.destroy()
self.client.close()
return
if admin_log_out is not None:
try:
self.root.destroy()
self.client.close()
except:
pass
elif messagebox.askokcancel("Quit", "Are you sure you want to quit?"):
try:
self.root.destroy()
self.client.close()
except:
pass
messagebox.showinfo("Success", "Thank you for being with us", icon="info")
def show_home_screen(self):
"""
function shows the home screen for the client
:return:
"""
# clearing screen
Client.clear_screen(self.root, self.menubar, self.on_closing)
# showing entry for changing date to admin
CTkButton(self.root, width=150, text='Change Date', relief=SOLID, cursor='hand2',
fg_color="#E0E0E0", hover_color="#33A8FF", border_width=3,
text_font=("Roboto Medium", -20),
command=lambda: self.change_date_for_admin()).pack(pady=10, anchor="n", side=TOP)
# creating a label and an image to begin the trivia
self.begin = Label(self.root, text="Hello There!!!\n\nWelcome to my airBnB "
"", font=self.lbl_font,
bg='white')
self.begin.pack(expand="Yes", fill=BOTH, anchor=CENTER)
self.name = StringVar()
# showing the video on the home screen
self.video_label = CTkLabel(self.root)
self.video_label.pack(pady=20)
player = tkvideo("airbnb_images//airbnb_video.mp4", self.video_label,
loop=1, size=(700, 500))
try:
player.play()
except:
pass
# showing name if exists
if self.user_data[5] is not None:
lbl = CTkLabel(self.root, text=f"Hello {self.user_data[5]}", bg="white", text_font=("Roboto Medium", -30))
lbl.place(x=20, y=20)
def start_admin_root(self):
"""
function starts the admin root - showing login form
:return:
"""
# starting the root
# setting attributes
self.root = Tk()
self.root.resizable(False, False)
self.root.config(bg="white")
self.root.title("AirBnB")
self.root.minsize(1000, 800)
x = 1000
y = 800
self.root.geometry(
f"{str(x)}x{str(y)}+{int(self.root.winfo_screenwidth() / 2 - x / 2)}+{int(self.root.winfo_screenheight() / 2 - y / 2)}")
self.root.deiconify()
bigger_frame = Frame(self.root, width=700, height=700, bg="white")
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# setting picture of the logo
CTkLabel(bigger_frame, text="Admin Login", text_font=("Roboto Medium", -40), bg="white").pack(pady=30)
img = ImageTk.PhotoImage(Image.open("airbnb_images//airbnb_sign_up2.png").resize((350, 290)))
login_lable = Label(bigger_frame, image=img, borderwidth=0, bg='white')
login_lable.image = img
login_lable.pack(side="left", expand=1, fill=BOTH, padx=20)
# setting labels for form
login_frame = Frame(bigger_frame, bd=2, bg="#F5F5F5", relief=SOLID, padx=10, pady=10, height=300)
CTkLabel(login_frame, text="Enter Email", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=0, column=0,
sticky=W,
pady=10)
CTkLabel(login_frame, text="Enter Password", bg="#F5F5F5", text_font=("Roboto Medium", -18)).grid(row=1,
column=0,
pady=10)
# setting entries for form
self.email_tf = CTkEntry(login_frame, width=200, placeholder_text="Enter Email")
self.pwd_tf = CTkEntry(login_frame, show='*', width=200, placeholder_text="Enter Password")
self.login_btn = CTkButton(login_frame, width=200, text='Login', relief=SOLID, cursor='hand2',
fg_color="#E0E0E0", hover_color="#33A8FF", border_width=3,
text_font=("Roboto Medium", -18),
command=self.login_response)
# widgets placement
self.email_tf.grid(row=0, column=1, pady=10, padx=20)
self.pwd_tf.grid(row=1, column=1, pady=10, padx=20)
self.login_btn.grid(row=2, pady=(100, 20), column=1)
login_frame.pack(side="left", pady=70)
bigger_frame.pack(padx=50, pady=50)
# starting the receive thread in order to get messages from the server
self.receive_thread = Thread(target=self.recieve)
# self.receive_thread.daemon = True
self.receive_thread.start()
self.root.mainloop()
def connect(self):
"""
function connects to the server
:return: None
"""
while 1:
try:
self.client.connect(self._ADDR)
print("----Connected to server successfully----")
break
except (ConnectionRefusedError, TimeoutError):
continue
# starting admin root
self.start_admin_root()
def start_root(self):
"""
function starts regular root for the application
:return: None
"""
self.root.title("AirBnB")
self.root.minsize(1000, 800)
x = 1000
y = 800
self.root.geometry(
f"{str(x)}x{str(y)}+{int(self.root.winfo_screenwidth() / 2 - x / 2)}+{int(self.root.winfo_screenheight() / 2 - y / 2)}")
self.root.iconphoto(False, PhotoImage(file=PATH + r"\\airbnb_images\\airbnb_sign_up2.png"))
self.root.deiconify()
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# creating the menu
self.menubar = Menu(self.root)
# creating submenu for disputes
self.sub_menu = Menu(self.menubar, tearoff=0)
self.sub_menu.add_command(label='Dispute Purchases', command=self.show_cancel_purchases)
self.sub_menu.add_command(label='Dispute Offers', command=self.show_cancel_offers)
# creating the file menu
self.filemenu = Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label="Register", command=self.show_registration)
self.filemenu.add_command(label="Home Page", command=self.show_home_screen)
self.filemenu.add_command(label="Sign in", command=self.show_login)
self.filemenu.add_command(label="See offers", command=self.open_map)
self.filemenu.add_command(label="Offer Room", command=self.offer_room)
self.filemenu.add_command(label="Rate Purchases", command=self.show_purchases)
self.filemenu.add_command(label="Convert Address", command=self.convert_address_to_location)
# adding separators, adding 'exit', 'log out' commands
self.filemenu.add_separator()
self.filemenu.add_cascade(
label="Dispute",
menu=self.sub_menu
)
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command=self.on_closing)
self.filemenu.add_command(label="Log out", command=self.log_out)
self.menubar.add_cascade(label="User menu", menu=self.filemenu)
# creating 'change' menu
self.change_menu = Menu(self.menubar, tearoff=0)
self.change_menu.add_command(label="Change Email", command=self.change_email)
self.change_menu.add_command(label="Change Password", command=self.change_password)
self.change_menu.add_command(label="Change Name", command=self.change_name)
self.menubar.add_cascade(label="Change Credentials", menu=self.change_menu)
# creating the 'admin' menu
self.help_menu = Menu(self.menubar, tearoff=0)
self.help_menu.add_command(label="Show Records", command=self.show_records)
self.help_menu.add_command(label="Show Offers", command=self.show_offers)
self.help_menu.add_command(label="Show All Purchases", command=self.show_admin_purchases)
self.help_menu.add_command(label="Show Ratings", command=self.show_admin_ratings)
self.help_menu.add_command(label="Upload attractions", command=self.upload_attractions)
self.help_menu.add_command(label="Open Admin Map", command=self.open_admin_map)
self.help_menu.add_command(label="Export Data Base To Csv", command=self.data_base_to_csv)
self.menubar.add_cascade(label="Admin Menu", menu=self.help_menu)
self.root.config(menu=self.menubar)
# creating a label font
self.lbl_font = tkFont.Font(family="Sans-serif", size=20, weight=tkFont.BOLD)
# showing the home screen
self.show_home_screen()
self.root.resizable(False, False)
def search_records(self):
"""
function searches all the records given the query by the admin search on the 'record' table
:return: None
"""
# if admin hasn't entered any query, showing all records
if self.search_entry.get() == "":
for record in self.tree.get_children():
self.tree.delete(record)
self.row_counter = 0
for i in self.record_lst:
# inserting the data in Treeview widget
if self.row_counter % 2 == 0:
self.tree.insert('', 'end', values=(i[0], i[1], i[2], i[3], i[4], i[5]), tag=("evenrow",))
else:
self.tree.insert('', 'end', values=(i[0], i[1], i[2], i[3], i[4], i[5]), tag=("oddrow",))
self.row_counter += 1
else:
# getting the requested answer for the query
self.client.send(pickle.dumps(["#GET ADMIN QUERY FOR RECORD#", self.search_entry.get()]))
self.wait_for_server_to_respond(self.admin_data, 4)
# if query is not found
if not any(list(i) in self.record_lst for i in self.admin_data[4]):
messagebox.showerror("Error", "Record doesn't seem to appear in this table")
return
# showing the relevant results
self.row_counter = 0
for record in self.tree.get_children():
self.tree.delete(record)
for i in self.admin_data[4]:
if self.row_counter % 2 == 0:
# inserting the data in Treeview widget
self.tree.insert('', 'end', values=(i[0], i[1], i[2], i[3], i[4], i[5]), tag=("evenrow",))
else:
self.tree.insert('', 'end', values=(i[0], i[1], i[2], i[3], i[4], i[5]), tag=("oddrow",))
self.row_counter += 1
# showing how many records were found
self.w.config(text=f"The number of records found is {self.row_counter}")
self.admin_data[4] = None
def upload_attractions(self):
"""
function shows form to upload attractions
:return: None
"""
# starting root
self.updload_root = Toplevel(self.root)
# showing label and submit button
CTkLabel(self.updload_root, text=f"Upload your attractions file!!!!!\n\n"
f"(Remember to only upload a json file)", bg='#F5F5F5',
text_font=("Roboto Medium", -20)).pack(pady=20)
CTkButton(self.updload_root, fg_color="#E0E0E0", hover_color="#33A8FF",
border_width=3, relief=SOLID, cursor='hand2', text="Select",
command=self.add_attractions_file).pack(side='bottom', pady=10)
def data_base_to_csv(self):
"""
function exports any database table to a .csv file in the admin directory
:return:
"""
# creating root
csv_root = Toplevel(self.root)
csv_root.resizable(False, False)
CTkLabel(csv_root, text=f"Export To Csv Any Data Base", bg='#F5F5F5',
text_font=("Roboto Medium", -30)).pack(pady=20)
# showing radio buttons --> each radio button representing a table in database
frame = Frame(csv_root)
self.radio_var = IntVar(value=0)
self.radio_button1 = CTkRadioButton(master=frame, variable=self.radio_var, text="record",
text_font=("Roboto Medium", -16), value=0)
self.radio_button1.grid(row=0, column=0, padx=10, pady=5, sticky="w")
self.radio_button2 = CTkRadioButton(master=frame, variable=self.radio_var, text="offers",
text_font=("Roboto Medium", -16), value=1)
self.radio_button2.grid(row=1, column=0, padx=10, pady=5, sticky="w")
self.radio_button3 = CTkRadioButton(master=frame, variable=self.radio_var, text="purchases",
text_font=("Roboto Medium", -16), value=2)
self.radio_button3.grid(row=2, column=0, padx=10, pady=5, sticky="w")
self.radio_button4 = CTkRadioButton(master=frame, variable=self.radio_var, text="ratings",
text_font=("Roboto Medium", -16), value=3)
self.radio_button4.grid(row=3, column=0, padx=10, pady=5, sticky="w")
l = ["record", "offers", "purchases", "ratings"] # list of database tables
# submit button --> sending to server which database admin wants to save
CTkButton(frame, fg_color="#E0E0E0", hover_color="#33A8FF",
border_width=3, relief=SOLID, cursor='hand2', text="Select",
command=lambda: [self.client.send(pickle.dumps([f"#SAVE DATA BASE# {l[self.radio_var.get()]}"])),
csv_root.destroy()]).grid(row=4, column=0, pady=5)
frame.pack(pady=10)
def add_attractions_file(self):
"""
function adds the attraction file (.json) to the system
:return: None
"""
# opening task window for user
self.root.attributes('-topmost', False)
file_format = [("Json File", "*.json")]
file = askopenfile(mode='r', filetypes=file_format)
if not file:
# handling errors
self.filenames = None
messagebox.showerror("Error", "You must choose an image")
return
# getting the files real path
filepath = os.path.abspath(file.name)
with open(filepath, "r", encoding='utf-8') as f:
# loading the data from the .json file
data = json.loads(f.read())
# sending for each attraction --> the location, the name, and the image name of the attraction
for location, (name, path_to_picture) in data.items():
with open(path_to_picture, "rb") as f:
bytes = f.read()
image_name = path_to_picture[path_to_picture.rfind("\\") + 1:]
self.client.send(f"NAME {image_name}".encode())
self.client.send(bytes)
self.client.send(pickle.dumps(["#NEW ATTRACTION#", [location, name, image_name]]))