-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
1667 lines (1359 loc) · 71 KB
/
client.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
# importing the required modules
import pickle
from socket import *
from threading import Thread
from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfilenames
from tkinter.scrolledtext import ScrolledText
import geocoder
import imageio
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
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 datetime import datetime
from contextlib import suppress
from tkvideo import tkvideo
import matplotlib.pyplot as plt
from skimage import data, io
# defining font and computer's path to the project
f = ('Open Sans', 16)
PATH = os.path.dirname(os.path.realpath(__file__))
class Client:
"""
Client class connects to server server, and manages also tkinter
involved with communicating with the server
"""
def __init__(self):
# ignoring deprecation warning
warnings.filterwarnings("ignore", category=DeprecationWarning)
# setting up client socket, wrapping with ssl
self.client = ssl.wrap_socket(socket(AF_INET, SOCK_STREAM), server_side=False)
self._BUFFER = 1024
if len(gethostbyname_ex(gethostname())[-1]) > 1:
self.__HOST = gethostbyname_ex(gethostname())[-1][0]
else:
self.__HOST = gethostbyname_ex(gethostname())[-1][-1]
self._ADDR = (self.__HOST, 50002)
# initiating important variables to avoid errors
self.event_handler = Event()
self.__logged_in = False
self.map = None
self.filenames = None
self._save_image = b""
self.start_image = False
self.ratings = dict({})
self.map_data = [None for i in range(10)]
self.admin_data = [None] # is admin
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.offers]
self.room_data = [None for i in range(5)] # [room name by offer_id, room average rating, room rating]
self.name = None
self.updated_offers = None
self.user_id = None
self.root = None
self.attractions = []
self.video_label = None
self.server_time = datetime.now().strftime("%Y/%m/%d")
self.paths = None
self.disputed_id = []
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:
# excepting image bytes from server
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
try:
pickle_data = pickle.loads(data)
except (EOFError, ValueError, OverflowError, MemoryError):
raise
# 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 on the map
self.updated_offers = pickle_data
self.map.update_markers(self.updated_offers)
continue
# 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 the room names were sent
elif pickle_data[0] == "#ROOM NAMES#":
self.map_data[0] = pickle_data[1]
continue
# if user is admin
elif pickle_data[0] == "#ADMIN ANSWER#":
self.admin_data[0] = pickle_data[1]
# if offers ordered by the price were sent
elif pickle_data[0] == "#OFFERS ORDERED BY PRICE#":
self.map_data[1] = pickle_data[1]
# if location the room names was sent
elif pickle_data[0] == "#LOCATION BY ROOM NAMES#":
self.map_data[2] = pickle_data[1]
# if data on the offer was sent
elif pickle_data[0] == "#INFORMATION ON OFFER#":
self.map_data[3] = pickle_data[1]
# if an offer by purchase id was sent
elif pickle_data[0] == "#OFFER BY PURCHASE ID#":
self.map_data[4] = pickle_data[1]
# if a 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 a room name by offer id was sent
elif pickle_data[0] == "#ROOM NAME BY OFFER ID#":
self.room_data[0] = pickle_data[1]
# if a new marker was sent
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])
continue
# if name by email in 'record' table was sent
elif pickle_data[0] == "#NAME BY EMAIL#":
self.user_data[5] = pickle_data[1]
# if time is up to date on 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 an offer by user email was sent
elif pickle_data[0] == "#OFFER BY EMAIL#":
self.user_data[6] = pickle_data[1]
# if a rating was sent by offer id
elif pickle_data[0] == "#RATING BY OFFER ID#":
self.room_data[1] = pickle_data[1]
# 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, updating the map
elif pickle_data[0] == "#NEW ATTRACTION#":
if self.map is not None:
self.map.add_attraction(*pickle_data[1])
else:
self.attractions.append(pickle_data[1])
# if another user disputed an 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
except pickle.UnpicklingError:
# handling data that is doesn't need to be pickled
try:
data = data.decode()
except UnicodeDecodeError:
pass
if data == "":
self.user_quit()
# if admin changed the date
try:
if data.find("/") != -1 and len(data) < 14:
self.server_time = data
# updating the server time
if self.map is not None:
self.map.update_server_time(self.server_time)
except TypeError:
pass
# if user already exists
if data == "#USER ALREADY EXISTS#":
self.user_data[4] = True
# if user doesn't exists
elif data == "#USER DOESN'T EXISTS#":
self.user_data[4] = False
# if client have already rated
elif data == "#AlREADY RATED#":
messagebox.showerror("Error", "You have already rated")
# if a client was made admin
elif data == "#BECOME ADMIN#":
messagebox.showinfo("WOW!!!!", "Seems like you were promoted to be admin\n"
"You can now proceed to go to admin file", icon="info")
except (EOFError, OSError, ssl.SSLEOFError):
# if there is any connections problems with the server, making user exit
self.user_quit()
break
def log_out(self):
"""
function logs out of system
:return: None
"""
if self.__logged_in:
self.__logged_in = False
messagebox.showinfo("info", "You have logged out")
else:
messagebox.showerror("Error", "You are not logged in")
self.user_data[5] = None
self.show_home_screen()
return
def show_home_screen(self):
"""
function shows the home screen for the client
:return:
"""
Client.clear_screen(self.root, self.menubar, self.on_closing)
# 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 video
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 connect(self):
"""
function shows loading screen
:return: None
"""
# creating the root, with geometry and airbnb icon
self.root = Tk()
self.root.iconphoto(False, PhotoImage(file=PATH + r"\\airbnb_images\\airbnb_sign_up2.png"))
self.root.title("AirBnb")
self.root.minsize(1000, 800)
self.root.config(bg='white')
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()
# setting picture
self.img = ImageTk.PhotoImage(Image.open(PATH + r"\\airbnb_images\\airbnb_sign_up2.png"))
self.begin_lable = Label(self.root, image=self.img, borderwidth=0)
self.begin_lable.image = self.img
self.begin_lable.pack(pady=30)
# setting loading screen, trying to connect to server
CTkLabel(self.root, text="Connecting to the server now...", text_color="black",
text_font=("Open Suns", -30)).pack(pady=30)
try:
self.root.after(100, self.connect_to_server)
self.root.mainloop()
except TclError:
pass
def connect_to_server(self):
"""
function connects to server socket
:return: None
"""
while 1:
try:
self.client.connect(self._ADDR)
print("----Connected to server successfully----")
break
except (ConnectionRefusedError, TimeoutError):
continue
# starting the root
self.start_root()
def start_root(self):
"""
function starts the tkinter root for the user
:return: None
"""
# clearing screen, defining root
Client.clear_screen(self.root, None, None)
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# creating menu
self.menubar = Menu(self.root)
# creating the 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 user 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)
# creating submenu for disputes
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.menubar.add_cascade(label="User menu", menu=self.filemenu)
self.root.config(menu=self.menubar)
self.lbl_font = tkFont.Font(family="Sans-serif", size=20, weight=tkFont.BOLD)
# creating the receive thread
self.receive_thread = Thread(target=self.recieve)
self.receive_thread.start()
# showing the home screen
self.show_home_screen()
self.root.resizable(False, False)
self.root.mainloop()
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 the 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 Password", 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 email
: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 user_quit(self):
"""
function closes client socket
:return:None
"""
try:
self.client.close()
print("----CLIENT SHUT DOWN----")
except:
pass
def convert_address_to_location(self):
"""
function converts address to location (x,y) for the user to enter when
:return: None
"""
# opening the root
self.location_root = Toplevel(self.root)
self.location_root.resizable(False, False)
frame = Frame(self.location_root)
# widgets and setting placements
CTkLabel(self.location_root, text=f"Please enter an address\n\n", bg='#F5F5F5',
text_font=("Roboto Medium", -30)).pack(pady=10)
# setting widgets
self.loc = CTkEntry(frame, width=200, placeholder_text="Enter Address")
self.loc.pack(side="left", padx=5)
# calculate 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)
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):
"""
function makes sure closing window goes without errors
:return: None
"""
if 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_cancel_purchases(self):
"""
function creates a table tree for purchases client has made
:return: None
"""
Client.clear_screen(self.root, self.menubar, self.on_closing)
# getting purchases
if self.__logged_in:
self.client.send(pickle.dumps(["#GET PURCHASES#", self.uemail]))
self.wait_for_server_to_respond(self.user_data, 3)
purchases = self.user_data[3]
else:
purchases = map.get_recent_orders()
CTkLabel(self.root, text=f"Your purchases\n\n"
f"(Double click to cancel)", bg='#F5F5F5',
text_font=("Roboto Medium", -30)).pack(pady=20)
# showing note to user
f = CTkFrame(self.root, corner_radius=0, border_width=3, bg="white")
CTkLabel(f, text=f"Note\n\nThe purchases that are shown here are only the ones that\n"
f"their starting date is at least 2 days from today .\n"
f"Please take that into consideration 🙏🙏🙏🙏",
text_font=("Roboto Medium", -15)).pack(pady=3)
f.pack(pady=3)
s = ttk.Style()
s.theme_use('clam')
# creating tree for purchases
self.tree = ttk.Treeview(self.root, column=("c1", "c2", "c3", "c4", "c5"), show='headings', height=5)
# setting tree columns
self.tree.column("# 1", anchor=CENTER)
self.tree.heading("# 1", text="Purchase id")
self.tree.column("# 2", anchor=CENTER)
self.tree.heading("# 2", text="Offer id")
self.tree.column("# 3", anchor=CENTER)
self.tree.heading("# 3", text="Check In")
self.tree.column("# 4", anchor=CENTER)
self.tree.heading("# 4", text="Check Out")
self.tree.column("# 5", anchor=CENTER)
self.tree.heading("# 5", text="Email")
# inserting rows
for i in purchases:
d = datetime.strptime(i[2].split("-")[0][:-1], '%Y/%m/%d')
if int(str(d - datetime.today())[0]) >= 2:
# inserting the data in Treeview widget
self.tree.insert('', 'end', values=(i[0], i[1],
i[2].split("-")[0], i[2].split("-")[1], i[3]))
# binding each element to cancel_purchases function
self.tree.bind("<Double-1>", lambda *args: self.cancel_purchases())
self.tree.pack(pady=50, fill=X)
def show_cancel_offers(self):
"""
function creates a tree for offers client has made so that he/she can dispute any one of them
:return: None
"""
# clearing the screen
Client.clear_screen(self.root, self.menubar)
# if user isn't logged in yet
if not self.__logged_in:
messagebox.showerror("Error", "You are not logged in yet")
self.show_home_screen()
return
# showing label
CTkLabel(self.root, text=f"Your offers\n\n"
f"(Double click to dispute)", bg='#F5F5F5',
text_font=("Roboto Medium", -30)).pack(pady=20)
# getting offers
self.client.send(pickle.dumps(["#GET OFFER BY EMAIL#", self.uemail]))
self.wait_for_server_to_respond(self.user_data, 6)
# creating tree for offers
self.row_counter = 0
self.tree = ttk.Treeview(self.root, column=("#1", "#2", "#3", "#4", "#5", "#6", "#7", "#8"),
show='headings')
# setting tree columns
self.tree.column("# 1", anchor=CENTER, width=15)
self.tree.heading("# 1", text="Offer Id")
self.tree.column("# 2", anchor=CENTER, width=15)
self.tree.heading("# 2", text="User Id")
self.tree.column("# 3", anchor=CENTER, width=15)
self.tree.heading("# 3", text="Room Id")
self.tree.column("# 4", anchor=CENTER, width=15)
self.tree.heading("# 4", text="Price Per Night")
self.tree.column("# 5", anchor=CENTER, width=100)
self.tree.heading("# 5", text="Duration")
self.tree.column("# 6", anchor=CENTER, width=50)
self.tree.heading("# 6", text="Conditions")
self.tree.column("# 7", anchor=CENTER, width=15)
self.tree.heading("# 7", text="Room Name")
self.tree.column("# 8", anchor=CENTER, width=20)
self.tree.heading("# 8", text="Geo (coordinates)")
# inserting rows
for i in self.user_data[6]:
# 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[5], i[6], i[7], i[8]),
tag=("evenrow",))
else:
self.tree.insert('', 'end', values=(i[0], i[1], i[2], i[3], i[5], i[6], i[7], i[8]),
tag=("oddrow",))
self.row_counter += 1
# setting each row in different colors
self.tree.tag_configure('oddrow', background='white')
self.tree.tag_configure('evenrow', background='#f2f2f2')
# binding tree to cancel_offer function
self.tree.pack(pady=20, expand=1, fill=BOTH)
self.tree.bind("<Double-1>", lambda *args: self.cancel_offer())
def cancel_offer(self):
"""
function cancels offers client has made
:return: None
"""
# getting the offer
try:
item = self.tree.selection()[0]
data = self.tree.item(item, "values")
except IndexError:
messagebox.showerror("error", "You haven't offered anything yet")
return
q = messagebox.askquestion("Confirmation", "Are you sure you want this offers to be canceled?",
icon='warning')
# disputing offer
if q == "yes":
self.client.send(pickle.dumps(["#DELETE FROM DATA BASE# offers", data[0]]))
messagebox.showinfo("Success", "You have disputed offer!!!")
self.tree.delete(item)
def cancel_purchases(self):
"""
function cancels purchases client has made
:return: None
"""
# getting the purchase
try:
item = self.tree.selection()[0]
data = self.tree.item(item, "values")
except IndexError:
messagebox.showerror("error", "You haven't purchased anything yet")
return
# getting room name by the offer id
self.client.send(pickle.dumps(["#GET ROOM NAME BY OFFER ID#", data[1]]))
self.wait_for_server_to_respond(self.room_data, 0)
q = messagebox.askquestion("Confirmation", "Are you sure you want this purchase to be canceled?",
icon='warning')
# deleting purchase
if q == "yes":
self.client.send(pickle.dumps(["#DELETE FROM DATA BASE# purchases", data[0]]))
messagebox.showinfo("Success", "You have disputed purchase!!!")
self.tree.delete(item)
def show_purchases(self):
"""
function shows user his/her purchases for him/her to rate them
:return:
"""
Client.clear_screen(self.root, self.menubar)
CTkLabel(self.root, text=f"Your purchases", bg='#F5F5F5',
text_font=("Roboto Medium", -30)).pack(pady=20)
# getting purchases
if self.__logged_in:
self.client.send(pickle.dumps(["#GET PURCHASES#", self.uemail]))
self.wait_for_server_to_respond(self.user_data, 3)
purchases = self.user_data[3]
# deleting disputed purchases
for i in purchases:
if int(i[1]) in self.disputed_id:
purchases.remove(i)
else:
purchases = map.get_recent_orders()
s = ttk.Style()
s.theme_use('clam')
# creating tree for showing purchases
self.tree = ttk.Treeview(self.root, column=("c1", "c2", "c3", "c4", "c5"), show='headings', height=5)
# setting tree columns
self.tree.column("# 1", anchor=CENTER)
self.tree.heading("# 1", text="Purchase id")
self.tree.column("# 2", anchor=CENTER)
self.tree.heading("# 2", text="Offer id")
self.tree.column("# 3", anchor=CENTER)
self.tree.heading("# 3", text="Check In")
self.tree.column("# 4", anchor=CENTER)
self.tree.heading("# 4", text="Check Out")
self.tree.column("# 5", anchor=CENTER)
self.tree.heading("# 5", text="Email")
# inserting rows
for i in purchases:
# inserting the data in Treeview widget
self.tree.insert('', 'end', values=(i[0], i[1],
i[2].split("-")[0], i[2].split("-")[1], i[3]))
# binding tree to show_rating function
self.tree.bind("<Double-1>", lambda *args: self.show_rating())
self.tree.pack(pady=20, fill=X)
def show_rating(self):
"""
function shows rating screen for user in order to rate a room he has been in
:return: None
"""
# getting data on purchase
try:
item = self.tree.selection()[0]
data = self.tree.item(item, "values")
except IndexError:
messagebox.showerror("error", "You haven't purchased anything yet")
return
if item in self.ratings.keys():
messagebox.showerror("error", "You have already rated this purchase")
return
# opening rating root
rating_root = Toplevel(self.root)
rating_root.resizable(False, False)
self.client.send(pickle.dumps(["#GET ROOM NAME BY OFFER ID#", data[1]]))
self.wait_for_server_to_respond(self.room_data, 0)
var = DoubleVar()