-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat_server.py
370 lines (349 loc) · 17.7 KB
/
chat_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
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
"""
Created on Tue Jul 22 00:47:05 2014
@author: alina, zzhang
"""
import time
import socket
import select
import sys
import string
import indexer
import json
import pickle as pkl
from chat_utils import *
import chat_group as grp
import sqlutils
import chessboard
class Server:
def __init__(self):
sqlutils.sql_init()
self.new_clients = [] # list of new sockets of which the user id is not known
self.logged_name2sock = {} # dictionary mapping username to socket
self.logged_sock2name = {} # dict mapping socket to user name
self.all_sockets = []
self.group = grp.Group()
# start server
self.boards = {}
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind(SERVER)
self.server.listen(5)
self.all_sockets.append(self.server)
# initialize past chat indices
self.indices = {}
# sonnet
# self.sonnet_f = open('AllSonnets.txt.idx', 'rb')
# self.sonnet = pkl.load(self.sonnet_f)
# self.sonnet_f.close()
self.sonnet = indexer.PIndex("AllSonnets.txt")
def new_client(self, sock):
# add to all sockets and to new clients
print('new client...')
sock.setblocking(0)
self.new_clients.append(sock)
self.all_sockets.append(sock)
def login(self, sock):
# read the msg that should have login code plus username
try:
msg = json.loads(myrecv(sock))
print("login:", msg)
if len(msg) > 0:
if msg["action"] == "login":
name = msg["name"]
passwd = msg["passwd"]
if self.group.is_member(name) != True:
key = sqlutils.get_password(name)
if name in sqlutils.get_users():
if key == passwd:
# move socket from new clients list to logged clients
self.new_clients.remove(sock)
# add into the name to sock mapping
self.logged_name2sock[name] = sock
self.logged_sock2name[sock] = name
# load chat history of that user
if name not in self.indices.keys():
try:
self.indices[name] = pkl.load(
open(name+'.idx', 'rb'))
except IOError: # chat index does not exist, then create one
self.indices[name] = indexer.Index(name)
print(name + ' logged in')
self.group.join(name)
mysend(sock, json.dumps(
{"action": "login", "status": "ok"}))
else: # wrong password
mysend(sock, json.dumps(
{"action": "login", "status": "wrong password","message":"Wrong password!" }))
print(name + ' wrong password')
else: # no such user
print('no users')
mysend(sock, json.dumps(
{"action": "login", "status": "no such user","message":"No such user!"}))
else: # a client under this name has already logged in
mysend(sock, json.dumps(
{"action": "login", "status": "duplicate","message": "Duplicate login!"}))
print(name + ' duplicate login attempt')
elif msg["action"] == "signin":
name = msg['name']
passwd = msg['passwd']
if sqlutils.create_user(name, passwd):
mysend(sock, json.dumps(
{"action": "signin", "status": "ok"}))
print(name + ' signed in')
else:
mysend(sock, json.dumps(
{"action": "signin", "status": "duplicate", "message" : "Duplicate signin!"}))
print(name + ' duplicate signin attempt')
else:
print('wrong code received')
else: # client died unexpectedly
self.logout(sock)
except:
self.all_sockets.remove(sock)
def logout(self, sock):
# remove sock from all lists
name = self.logged_sock2name[sock]
pkl.dump(self.indices[name], open(name + '.idx', 'wb'))
del self.indices[name]
del self.logged_name2sock[name]
del self.logged_sock2name[sock]
if name in self.boards.keys():
del self.boards[name]
self.all_sockets.remove(sock)
self.group.leave(name)
sock.close()
# ==============================================================================
# main command switchboard
# ==============================================================================
def handle_msg(self, from_sock):
# read msg code
msg = myrecv(from_sock)
if len(msg) > 0:
# ==============================================================================
# handle connect request
# ==============================================================================
msg = json.loads(msg)
if msg["action"] == "connect":
to_name = msg["target"]
from_name = self.logged_sock2name[from_sock]
if to_name == from_name:
msg = json.dumps({"action": "connect", "status": "self"})
# connect to the peer
elif self.group.is_member(to_name):
to_sock = self.logged_name2sock[to_name]
self.group.connect(from_name, to_name)
the_guys = self.group.list_me(from_name)
msg = json.dumps(
{"action": "connect", "status": "success"})
for g in the_guys[1:]:
to_sock = self.logged_name2sock[g]
mysend(to_sock, json.dumps(
{"action": "connect", "status": "request", "from": from_name}))
else:
msg = json.dumps(
{"action": "connect", "status": "no-user"})
mysend(from_sock, msg)
# ==============================================================================
# handle messeage exchange: one peer for now. will need multicast later
# ==============================================================================
elif msg["action"] == "exchange":
from_name = self.logged_sock2name[from_sock]
the_guys = self.group.list_me(from_name)
#said = msg["from"]+msg["message"]
said2 = text_proc(msg["message"], from_name)
self.indices[from_name].add_msg_and_index(said2)
for g in the_guys[1:]:
to_sock = self.logged_name2sock[g]
self.indices[g].add_msg_and_index(said2)
mysend(to_sock, json.dumps(
{"action": "exchange", "from": msg["from"], "message": msg["message"]}))
# ==============================================================================
# listing available peers
# ==============================================================================
elif msg["action"] == "list":
from_name = self.logged_sock2name[from_sock]
msg = self.group.list_all()
mysend(from_sock, json.dumps(
{"action": "list", "results": msg}))
# ==============================================================================
# retrieve a sonnet
# ==============================================================================
elif msg["action"] == "poem":
poem_indx = int(msg["target"])
from_name = self.logged_sock2name[from_sock]
print(from_name + ' asks for ', poem_indx)
poem = self.sonnet.get_poem(poem_indx)
poem = '\n'.join(poem).strip()
print('here:\n', poem)
mysend(from_sock, json.dumps(
{"action": "poem", "results": poem}))
# ==============================================================================
# time
# ==============================================================================
elif msg["action"] == "time":
ctime = time.strftime('%d.%m.%y,%H:%M', time.localtime())
mysend(from_sock, json.dumps(
{"action": "time", "results": ctime}))
# ==============================================================================
# deal with game
# ==============================================================================
elif msg["action"] == "game_start":
from_name = self.logged_sock2name[from_sock]
to_name = msg["target"]
print('game start from ' + from_name + ' to ' + to_name)
if to_name not in self.group.list_all():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "no-user"}))
elif to_name in self.boards.keys():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "busy"}))
else:
to_sock = self.logged_name2sock[to_name]
mysend(to_sock, json.dumps(
{"action": "game_invite", "from": from_name}))
elif msg["action"] == "game_accept":
from_name = self.logged_sock2name[from_sock]
to_name = msg["target"]
print('game accept from ' + from_name + ' to ' + to_name)
if to_name not in self.group.list_all():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "no-user"}))
elif to_name in self.boards.keys():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "busy"}))
else:
self.boards[to_name] = self.boards[from_name] = chessboard.Board()
self.boards[to_name].last = from_name
to_sock = self.logged_name2sock[to_name]
mysend(to_sock, json.dumps(
{"action": "game_start", "from": from_name}))
mysend(from_sock, json.dumps(
{"action": "game_start", "from": to_name}))
elif msg["action"] == "game_reject":
from_name = self.logged_sock2name[from_sock]
to_name = msg["target"]
print('game reject from ' + from_name + ' to ' + to_name)
if to_name not in self.group.list_all():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "no-user"}))
else:
to_sock = self.logged_name2sock[to_name]
mysend(to_sock, json.dumps(
{"action": "game_reject", "from": from_name}))
elif msg["action"] == "game_move":
from_name = self.logged_sock2name[from_sock]
to_name = msg["target"]
print('game move from ' + from_name + ' to ' + to_name)
if to_name not in self.group.list_all():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "no-user"}))
mysend(from_sock, json.dumps(
{"action": "game_end", "status": "?"}))
if from_name in self.boards.keys():
del self.boards[from_name]
elif to_name not in self.boards.keys():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "unknown error"}))
if from_name in self.boards.keys():
del self.boards[from_name]
else:
try:
to_sock = self.logged_name2sock[to_name]
if from_name == self.boards[from_name].last:
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "not your turn"}))
else:
self.boards[from_name].place(int(msg["x"]),int(msg["y"]),from_name)
self.boards[from_name].last = from_name
mysend(to_sock, json.dumps(
{"action": "game_move", "from": from_name, "x": msg["x"], "y": msg["y"]}))
mysend(from_sock, json.dumps(
{"action": "game_move", "from": from_name, "x": msg["x"], "y": msg["y"]}))
w = self.boards[from_name].check()
if w != -1:
mysend(to_sock, json.dumps(
{"action": "game_win", "from": w}))
mysend(from_sock, json.dumps(
{"action": "game_win", "from": w}))
del self.boards[from_name],self.boards[to_name]
except:
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "illegal move"}))
elif msg["action"] == "game_quit":
from_name = self.logged_sock2name[from_sock]
to_name = msg["target"]
print('game move from ' + from_name + ' to ' + to_name)
if to_name not in self.group.list_all():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "no-user"}))
mysend(from_sock, json.dumps(
{"action": "game_end", "status": "?"}))
if from_name in self.boards.keys():
del self.boards[from_name]
elif to_name not in self.boards.keys():
mysend(from_sock, json.dumps(
{"action": "game_error", "status": "unknown error"}))
if from_name in self.boards.keys():
del self.boards[from_name]
else:
to_sock = self.logged_name2sock[to_name]
mysend(from_sock, json.dumps(
{"action": "game_quit", "from": from_name}))
mysend(to_sock, json.dumps(
{"action": "game_quit", "from": from_name}))
del self.boards[from_name],self.boards[to_name]
# ==============================================================================
# search
# ==============================================================================
elif msg["action"] == "search":
term = msg["target"]
from_name = self.logged_sock2name[from_sock]
print('search for ' + from_name + ' for ' + term)
# search_rslt = (self.indices[from_name].search(term))
search_rslt = '\n'.join(
[x[-1] for x in self.indices[from_name].search(term)])
print('server side search: ' + search_rslt)
mysend(from_sock, json.dumps(
{"action": "search", "results": search_rslt}))
# ==============================================================================
# the "from" guy has had enough (talking to "to")!
# ==============================================================================
elif msg["action"] == "disconnect":
from_name = self.logged_sock2name[from_sock]
the_guys = self.group.list_me(from_name)
self.group.disconnect(from_name)
the_guys.remove(from_name)
if len(the_guys) == 1: # only one left
g = the_guys.pop()
to_sock = self.logged_name2sock[g]
mysend(to_sock, json.dumps({"action": "disconnect"}))
# ==============================================================================
# the "from" guy really, really has had enough
# ==============================================================================
else:
# client died unexpectedly
self.logout(from_sock)
# ==============================================================================
# main loop, loops *forever*
# ==============================================================================
def run(self):
print('starting server...')
while(1):
read, write, error = select.select(self.all_sockets, [], [])
print('checking logged clients..')
for logc in list(self.logged_name2sock.values()):
if logc in read:
self.handle_msg(logc)
print('checking new clients..')
for newc in self.new_clients[:]:
if newc in read:
self.login(newc)
print('checking for new connections..')
if self.server in read:
# new client request
sock, address = self.server.accept()
self.new_client(sock)
def main():
server = Server()
server.run()
if __name__ == "__main__":
main()