-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
203 lines (177 loc) · 7.84 KB
/
Copy pathmain.py
File metadata and controls
203 lines (177 loc) · 7.84 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
#!/usr/bin/env python
import asyncio
import websockets
import json
from controller import Controller
import uuid
sessions = {} # dictionary {sessionId: user ID}
active_users = {} # {user_id: socket}
controller = Controller()
counter = 0 # counts the number of websockets created - for control purposes
current_user = None
async def handler(websocket):
global counter
counter += 1
session_id = str(uuid.uuid4())
sessions[session_id] = -1
while True:
try:
message = await websocket.recv()
except websockets.ConnectionClosed:
print(f"Client (({websocket})) disconnected.")
break
message_dict = json.loads(message)
if message_dict["action"] == "signup":
user = controller.signup(message_dict["username"], message_dict["password"])
if controller.response_ok:
sessions[session_id] = user["id"]
response = {
"action": "routing",
"url": "http://localhost:8000/chatboard.html?sec="+session_id,
}
else:
response = {
"action": "error",
}
response["msg"] = controller.code
await websocket.send(json.dumps(response))
if controller.response_ok:
response = {
"action": "new-login",
"user": user
}
for id, clientsocket in active_users.items():
if clientsocket != websocket:
await clientsocket.send(json.dumps(response))
if message_dict["action"] == "login":
user = controller.login(message_dict["username"], message_dict["password"])
if controller.response_ok:
sessions[session_id] = user["id"]
response = {
"action": "routing",
"url": "http://localhost:8000/chatboard.html?sec="+session_id
}
else:
response = {
"action": "error"
}
response["msg"] = controller.code
await websocket.send(json.dumps(response))
if controller.response_ok:
response = {
"action": "new-login",
"user": user
}
for id, clientsocket in active_users.items():
# inform all users that new user logged in
if clientsocket != websocket:
await clientsocket.send(json.dumps(response))
if message_dict["action"] == "on-load":
if message_dict["session"] in sessions.keys():
valid_session_id = message_dict["session"] # we will use the "old" session created before sign in
usr_id = sessions[valid_session_id]
sessions.pop(session_id) # remove new session_id
sessions[valid_session_id] = usr_id
users = controller.load_users()
current_user = controller.load_user(usr_id)
active_users[current_user["id"]] = websocket
response = {
"action": "on-load",
"users": users,
"user": current_user
}
else:
response = {"action": "error", "msg": "Session not valid"}
await websocket.send(json.dumps(response))
if message_dict["action"] == "logout":
# change status of the user in DB
deactivated = controller.logout(message_dict["userid"])
if deactivated:
# destroy session
del sessions[message_dict["session"]]
del active_users[message_dict["userid"]]
# inform others
response = {
"action": "logout",
"userid": message_dict["userid"]
}
for socket in active_users.values():
await socket.send(json.dumps(response))
if message_dict["action"] == "load-friend":
if message_dict["session"] in sessions:
response = {}
# fill the response with friend's data
if load_user(message_dict["userid"], response):
# add conversation messages with the friend
sgn = load_conversation(message_dict["userid"], message_dict["current_id"], response)
else:
response = {"action": "error", "msg": "Session not valid"}
await websocket.send(json.dumps(response))
if message_dict["action"] == "message-sent":
# current websocket is sending message to a friend
if message_dict["session"] in sessions:
sgn = controller.received_message(message_dict["from"],
message_dict["to"],
message_dict["message"])
if message_dict["to"] in active_users:
# if recipient in active_users
socket = active_users[message_dict["to"]]
if sgn:
# and if message saved in DB, forward message to the recipient and inform sender of success
forward_response = {
"action": "message-received",
"from_id": message_dict["from"],
"message": message_dict["message"],
}
response = {
"action": "receipt-confirmation",
"success": "success",
"message": message_dict["message"]
}
await socket.send(json.dumps(forward_response))
else:
# inform sender of failure to send (save msg in DB)
response = {
"action": "receipt-confirmation",
"success": "fail",
"message": message_dict["message"]
}
else:
if sgn:
# recipient not online, but message successfuly saved
response = {
"action": "receipt-confirmation",
"success": "will be delivered later",
"message": message_dict["message"]
}
else:
response = {"action": "error", "msg": "Session not valid"}
await websocket.send(json.dumps(response))
if message_dict["action"] == "message":
for id, socket in active_users.items():
if id != user_id:
await socket.send(json.dumps(message_dict))
async def main():
async with websockets.serve(handler, "", 8022):
await asyncio.Future() # run forever
def load_user(user_id: int, response: dict) -> bool:
user = controller.load_user(user_id)
# messages = controller.load_messages(message_dict["userid"])
if controller.response_ok:
response["action"] = "load-friend"
response["user"] = user
return True
else:
response = {"action": "error", "msg": controller.code}
return False
def load_conversation(user_id: int, current_id: int, response: dict) -> bool:
# load the conversation between current user and requested id
msg_dict = controller.load_conversation(current_id, user_id)
if controller.response_ok:
response["conversation"] = msg_dict
return True
else:
response = {"action": "error", "msg": controller.code}
return False
if __name__ == "__main__":
asyncio.run(main())