-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
281 lines (211 loc) · 8.58 KB
/
server.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
import socket
from threading import Thread
import json
import time
from datetime import datetime
class Auth:
def __init__(self, path):
self.path = path
# ensure file exists
try:
with open(self.path, "r") as file:
pass
except FileNotFoundError:
with open(self.path, "x") as file:
pass
with open(self.path, "a") as file:
file.write("{}")
def login(self, username, password):
with open(self.path, "r") as file:
contents = json.load(file)
if username in contents:
if str(hash(password)) == contents[username]:
return True
return False
def signup(self, username, password):
with open(self.path, "r") as file:
contents = json.load(file)
if username in contents:
return False
contents[username] = str(hash(password))
with open(self.path, "w") as file:
json.dump(contents, file, indent=4)
return True
class Server:
def __init__(self):
self.ip = "127.0.0.1"
self.port = 33000
self.addr = (self.ip, self.port)
self.clients = {}
self.rooms = {}
self.auth = Auth("pswd.json")
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.ip, self.port))
def accept_incoming_connections(self):
while True:
client, client_address = self.server.accept()
print(f"{client_address} has connected.")
self.clients[client] = {
'address':client_address,
'client':client,
'username':None,
'room':None
}
Thread(target=self.handle_client, args=(client,)).start()
def create_room(self, name, pswd, sock):
if self.clients[sock]['username'] == None:
return
if name in self.rooms:
sock.send(f"room:room taken:create".encode("utf-8"))
return
self.rooms[name] = pswd
self.clients[sock]['room'] = name
sock.send(f"room:success:create".encode("utf-8"))
time.sleep(0.5)
sock.send(f"users:{self.clients[sock]['username']}".encode("utf-8"))
time.sleep(0.5)
tm = datetime.now().strftime("%H:%M")
sock.send(f"msg:{tm}:SERVER:{self.clients[sock]['username']} connected".encode("utf-8"))
def users_in_room(self, name):
count = 0
for sock in self.clients:
if self.clients[sock]['room'] == name:
count += 1
return count
def get_users_in_room(self, name):
users = []
for sock in self.clients:
if self.clients[sock]['room'] == name:
users.append(self.clients[sock]['username'])
for i in users:
print(f"User: {i}")
return users
def room_exists(self, name):
return name in self.rooms
def add_user_to_room(self, sock, room, pswd):
if self.clients[sock]['username'] == None or self.clients[sock]['room'] != None:
return "no username"
if room not in self.rooms:
return "non-existent room"
if self.rooms[room] != pswd:
return "incorrect password"
self.clients[sock]['room'] = room
return "correct"
def del_room(self, name):
if self.users_in_room(name) == 0:
del self.rooms[name]
def send(self, msg, sock):
sock.send(msg)
def send_all(self, msg):
for sock in self.clients:
sock.send(msg)
def broadcast_msg(self, msg, room):
for sock in self.clients:
if self.clients[sock]['username'] != None and self.clients[sock]['room'] == room:
sock.send(msg)
def send_users_room(self, room):
users = self.get_users_in_room(room)
msg = f"users"
for u in users:
msg += f":{u}"
msg = msg.encode("utf-8")
self.broadcast_msg(msg, room)
def handle_client(self, client):
while True:
try:
msg = client.recv(1024).decode('utf-8')
except OSError:
break
if msg.startswith("login:"):
if self.clients[client]['username'] != None:
del self.clients[client]
break
uname = msg.split(":")[1]
pswd = msg.split(":")[2]
result = self.auth.login(uname, pswd)
message = "login:" + str(result)
message = message.encode("utf-8")
self.send(message, client)
if result:
self.clients[client]['username'] = uname
elif msg.startswith("signup:"):
if self.clients[client]['username'] != None:
del self.clients[client]
return
uname = msg.split(":")[1]
pswd = msg.split(":")[2]
result = self.auth.signup(uname, pswd)
message = "signup:" + str(result)
message = message.encode("utf-8")
self.send(message, client)
if result:
self.clients[client]['username'] = uname
elif msg.startswith("msg:"):
if self.clients[client]['username'] == None:
del self.clients[client]
return
if self.clients[client]['room'] == None:
del self.clients[client]
return
text = msg.split(":")[3]
# time of message sent
hr = msg.split(":")[1]
mn = msg.split(":")[2]
fmt = f"msg:{hr}:{mn}:{self.clients[client]['username']}:{text}"
fmt = fmt.encode("utf-8")
self.broadcast_msg(fmt, self.clients[client]['room'])
elif msg.startswith("end"):
room = None
if self.clients[client]['username'] != None and self.clients[client]['room'] != None:
tm = datetime.now().strftime("%H:%M")
fmt = f"msg:{tm}:SERVER:{self.clients[client]['username']} left"
fmt = fmt.encode("utf-8")
room = self.clients[client]['room']
self.broadcast_msg(fmt, self.clients[client]['room'])
del self.clients[client]
# will delete room if no users left
if room != None:
self.del_room(room)
if self.room_exists(room):
self.send_users_room(room)
elif msg.startswith("logout"):
room = None
if self.clients[client]['username'] != None and self.clients[client]['room'] != None:
tm = datetime.now().strftime("%H:%M")
fmt = f"msg:{tm}:SERVER:{self.clients[client]['username']} left"
fmt = fmt.encode("utf-8")
room = self.clients[client]['room']
self.broadcast_msg(fmt, self.clients[client]['room'])
self.clients[client]['username'] = None
self.clients[client]['room'] = None
# will delete room if no users left
if room != None:
self.del_room(room)
if self.room_exists(room):
self.send_users_room(room)
elif msg.startswith("room:"):
action = msg.split(":")[1]
name = msg.split(":")[2]
pswd = msg.split(":")[3]
if action == "create":
self.create_room(name, pswd, client)
elif action == "join":
ret = self.add_user_to_room(client, name, pswd)
if ret != "correct":
client.send(f"room:{ret}:join".encode("utf-8"))
else:
client.send(f"room:success:join".encode("utf-8"))
self.send_users_room(name)
time.sleep(0.5)
tm = datetime.now().strftime("%H:%M")
self.broadcast_msg(f"msg:{tm}:SERVER:{self.clients[client]['username']} connected".encode("utf-8"), name)
def close(self):
self.server.close()
def start(self, listen=5):
self.server.listen(listen)
accept = Thread(target=self.accept_incoming_connections)
accept.start()
accept.join()
if __name__ == "__main__":
server = Server()
server.start()