-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatRoomHelpers.py
348 lines (286 loc) · 10.6 KB
/
ChatRoomHelpers.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
import os
from socket import socket
import json
import sys
from tkinter import BOTH, PhotoImage, X, LEFT
from tkinter.constants import END
from tkinter.ttk import Frame, Label, Entry, Button
class ClientList:
"""
Class to represent the client list that the server maintains
"""
client_list = []
def __init__(self):
self.client_list = []
def addToList(self, conn: socket, name: str, chat_room: str):
"""
Adds a connection to the list with the inputted data
Parameters:
self (ClientList): This instance
conn (socket): Connection to client
name (str): Name of client
chat_room (str): Chat room that they are in
Returns:
(boolean): True if item was successfully added
"""
temp_dict = {'Connection': conn, 'Name': name, 'Room': chat_room}
for entry in self.client_list:
if (entry['Connection'] == conn and entry['Name'] == name
and entry['Room'] == chat_room):
return False
self.client_list.append(temp_dict)
def removeFromList(self, conn: socket):
"""
Removes an item from the list give the connection
Parmeters:
self (ClientList): This instance
conn (socket): Connection to client
Returns:
(boolean): True if item was removed successfully
"""
for entry in self.client_list:
if entry['Connection'] == conn:
self.client_list.remove(entry)
return True
return False
def getList(self):
"""
Returns a copy of the list of clients
"""
return self.client_list.copy()
def connectionsInRoom(self, chat_room: str):
"""
Finds all clients in a give chat room.
Parameters:
self (ClientList): This instance
chat_room (str): Chat room to search for
Returns:
(list): A list of connections in that room
"""
connections = []
for entry in self.client_list:
if entry['Room'] == chat_room:
connections.append(entry['Connection'])
return connections
def connections(self):
"""
Returns a list of all connections.
Parameters:
self (ClientList): This instance
Returns:
(list): List of all connections
"""
connections = []
for entry in self.client_list:
connections.append(entry['Connection'])
return connections
def getConnRoom(self, conn: socket):
"""
Gets the current room that this connection is in.
Parameters:
self (ClientList): This instance
conn (socket): Connections to search for
Returns:
(str): The current chat room of this connection
"""
for entry in self.client_list:
if entry['Connection'] == conn:
return entry['Room']
return None
def getName(self, conn: socket):
"""
Given a socket, return the name of that user.
Parameters:
self (ClientList): This instance
conn (socket): Connections to search for
Returns:
(str): The name of the user of that connection
"""
for entry in self.client_list:
if entry['Connection'] == conn:
return entry['Name']
return None
def updateChatRoom(self, conn: socket, chat_room: str):
"""
Given a connection, it will change its chat room
Parameters:
self (ClientList): This instance
conn (socket): The connection to update
chat_room (str): The chat room to change to
Returns:
(boolean): True if client has left the room
"""
for entry in self.client_list:
if entry['Connection'] == conn:
entry['Room'] = chat_room
return True
return False
class MessageProtocol:
"""
Class providing helper functions for the message protocol. Contains the
header_len variable which is the max length of the header file (8 bytes).
The protocol uses fixed length headers. A header of lenght 8 bytes is first
sent. It contains the message length and senders name to the client. The
message is then sent.
"""
header_len = 8 # Max length of header in bytes
def create_header(msg: str, name: str):
"""
Creates the header for the inputted message.
Parameters:
msg (str): The message to be sent
name (str): The name of the client sending the message
Returns:
(str): A json object representing the header for the message
Errors:
ValueError: If header lenght is too long
"""
header_dict = {'content-length': len(msg.encode()),
'name': name}
header = json.dumps(header_dict)
if (len(header) >= 2**MessageProtocol.header_len):
raise ValueError('Header too large')
return header
def parse_header(header: str):
"""
Parses the header and returns a dictionary representing it.
Parameters:
header (str): The header to parse
Returns:
(dict): A dictionary representing the header
"""
return (json.loads(header))
def send_msg_protocol(conn: socket, msg: str, name: str):
"""
Function to send the message, including headers. It will first send the
header for the message. Then sends the actual message.
Parameters:
conn (socket): Connection to send message down
msg (str): Message to send
name (str): Name of sending process
"""
header = MessageProtocol.create_header(msg, name).encode()
header += b' ' * ((2**MessageProtocol.header_len) - len(header))
conn.sendall(header) # Send header
conn.sendall(msg.encode()) # Send message
def recv_msg_protocol(conn: socket):
"""
Handles the recieving of messages using the protocol where the
header is sent first, then the message. Returns nothing if header
is invalid
Parameters:
conn (socket): Socket to recieve message from
Returns:
(str): The message sent from socket
"""
try:
msg_header = json.loads(conn
.recv(2**MessageProtocol.header_len)
.decode())
msg = conn.recv(msg_header['content-length']).decode()
return msg
except json.decoder.JSONDecodeError:
# Malformed header, do nothing
return None
class ClientSetUp(Frame):
"""
Dialog box that presents 3 inputs to the user:
Username
Server IP
Port
Extends the Frame class in tkinter.
"""
def __init__(self):
super().__init__()
self.name = ''
self.ip = ''
self.port = ''
self.initUI()
def initUI(self):
"""
Initialises the dialog box. The box will contain fields for the
username, server ip and server port. A button is used to submit
the data.
"""
self.master.title("Connection Details")
self.pack(fill=BOTH, expand=True)
# Prepare the username field
frame1 = Frame(self)
frame1.pack(fill=X)
lbl1 = Label(frame1, text="Username", width=14)
lbl1.pack(side=LEFT, padx=5, pady=10)
self.entry1 = Entry(frame1, textvariable=self.name)
self.entry1.pack(fill=X, padx=5, expand=True)
# Prepare the server address field
frame2 = Frame(self)
frame2.pack(fill=X)
lbl2 = Label(frame2, text="Server Address", width=14)
lbl2.pack(side=LEFT, padx=5, pady=10)
self.entry2 = Entry(frame2, textvariable=self.ip)
self.entry2.pack(fill=X, padx=5, expand=True)
# Prepare the server port field
frame3 = Frame(self)
frame3.pack(fill=X)
lbl3 = Label(frame3, text="Server Port", width=14)
lbl3.pack(side=LEFT, padx=5, pady=10)
self.entry3 = Entry(frame3, textvariable=self.port)
self.entry3.pack(fill=X, padx=5, expand=True)
frame4 = Frame(self)
frame4.pack(fill=X)
# Command tells the form what to do when the button is clicked
btn = Button(frame4, text="Submit", command=self.onSubmit)
btn.pack(padx=5, pady=10)
# Give entry1 focus
self.entry1.focus()
# Set up what happens when Return is pressed
# All entries will move onto the next except port which will submit
# Note: These didn't work if they weren't lambdas (don't know why)
self.entry1.bind('<Return>', lambda event: self.entry2.focus())
self.entry2.bind('<Return>', lambda event: self.entry3.focus())
self.entry3.bind('<Return>', lambda event: self.onSubmit())
photo = PhotoImage(file=resource_path('icon.png'))
self.master.iconphoto(False, photo)
def onSubmit(self):
"""
When clicked, the user input is stored in the instance variables
and the boxes are cleared. The widget is then destroyed.
"""
self.name = self.entry1.get()
self.ip = self.entry2.get()
self.port = self.entry3.get()
self.entry1.delete(0, END)
self.entry2.delete(0, END)
self.entry3.delete(0, END)
self.quit()
def retry(self, name='', ip='', port=''):
"""
Used if the user enters incorrect data. It will repopulate
the fields where the data was correct. The mainloop is started
once the fields are populated.
Parameters:
name (str): Name of client
ip (str): IP of server
port (str): Port of server
"""
self.entry1.insert(0, name)
self.entry2.insert(0, ip)
self.entry3.insert(0, port)
self.mainloop()
self.quit()
def on_close(self):
self.destroy()
sys.exit()
def resource_path(relative_path: str):
"""
Utility to get the absolute path of the file. Assumes file is in
current directory. Needed for when scirpts are converted into executables.
Parameters:
relative_path (str): Name of file to find
Returns:
(str): Absolute path of file in current directory
"""
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)