-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
568 lines (406 loc) · 14.4 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
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
import socket
import SocketServer
import threading
import thread
from threading import Lock
import json
import string
import signal, os
import sys
from datetime import datetime
from time import sleep
from Sharinf_DB_Con import DB_Accesser
SUCCESS = chr(1)
INSUCESS = chr(0)
PUBLIC = 0
PRIVATE = 1
FREE = 0
RESTRICTED = 1
CREATE_CONNECTION = 0
BEACON_DETECTED = 1
CREATE_SESSION = 2
SESSION_USERLIST = 3
SESSION_FILELIST = 4
JOIN_SESSION = 5
GETOUT_SESSION = 6
CHNGE_SESSION = 7
LOAD_FILE_SESSION = 8
REMOVE_FILE_SESSION = 14
SESSION_ENDED = 9
YOURNEWADMIN = 16
REQUESTJOINSESSION = 11
UPDATE_USERS = 12
UPDATE_FILES = 15
BEACON_UNDETECTED = 17
server = None
socketlist = {}
class usersThread (threading.Thread):
def __init__(self, sessionid):
threading.Thread.__init__(self)
self.sessionid = sessionid
def run(self):
print "starts user update for all users"
#sleep(1)
encoder = json.JSONEncoder()
bd = DB_Accesser()
users = bd.Get_AllUsersInSession({"sessionID": self.sessionid})
data = {"sessionID": self.sessionid, "userList": users}
datastr = encoder.encode(data)
cmdstr = unichr(UPDATE_USERS)
for usr in users:
skt = socketlist[usr["email"]][0]
mtx = socketlist[usr["email"]][2]
sendstr = "SHARINF" + cmdstr + datastr + "\endF"
mtx.acquire()
n_send = skt.sendall(sendstr)
#while(n_send is not None):
# n_send = skt.sendall(sendstr)
mtx.release()
print "users update done!"
return
class filesThread (threading.Thread):
def __init__(self, sessionid):
threading.Thread.__init__(self)
self.sessionid = sessionid
def run(self):
print "starts file update for all users"
#sleep(1)
encoder = json.JSONEncoder()
bd = DB_Accesser()
users = bd.Get_AllUsersInSession({"sessionID": self.sessionid})
files = bd.Get_AllFilesFromSession({"sessionID": self.sessionid})
data = {"sessionID": self.sessionid, "fileList": files}
datastr = encoder.encode(data)
cmdstr = unichr(UPDATE_FILES)
for usr in users:
print "update files for user " + usr["email"]
skt = socketlist[usr["email"]][0]
mtx = socketlist[usr["email"]][2]
sendstr = "SHARINF" + cmdstr + datastr + "\endF"
mtx.acquire()
n_send = skt.sendall(sendstr)
#while(n_send is not None):
# n_send = skt.sendall(sendstr)
mtx.release()
print "files update done!"
return
def handler(signum, frame):
server.shutdown()
server.server_close()
print "\nExiting Sharinf server...\n"
sys.exit(0)
class sharinfFrame():
def __init__(self, cmd, data):
decoder = json.JSONDecoder()
self.cmd = int(cmd)
if(data == [] or data == ''):
self.data = None
else:
try:
self.data = decoder.decode(data)
except:
raise
class MyTCPHandler(SocketServer.BaseRequestHandler):
def getUser(self):
db = DB_Accesser()
data = self.request.recv(5 * 1024)
if data is None:
return None
if(data[:7] != "SHARINF"):
print "No begin of frame"
return None
index = string.find(data,'\endF')
if(index == -1):
print "No end of frame"
return None
frame = sharinfFrame(data[7], data[8:index])
cmdstr = unichr(CREATE_CONNECTION)
if(frame == None or frame.cmd != CREATE_CONNECTION):
#tempstr = "First I need a create connection request with information about the user..."
self.request.send("SHARINF" + cmdstr + INSUCESS + "{\"error\":\"" + tempstr + "\"}" + "\endF")
#self.returnInsucess(CREATE_CONNECTION, "First I need a create connection request with information about the user...")
return None
db.Insert_User(frame.data)
self.request.send("SHARINF" + cmdstr + SUCCESS + "\endF")
#self.returnSuccess(CREATE_CONNECTION, None, us = frame.data["email"])
print "getUser: " + frame.data["email"]
return frame.data["email"]
def beaconDetectedHandle(self, data):
print "Beacon detected: " + self.user
db = DB_Accesser()
beaconlist = []
sessionlist = []
for beacon in data:
location = db.Get_Location(beacon)
while(location == None):
db.Insert_Location(beacon)
location = db.Get_Location(beacon)
print location
db.Insert_UserInLocation({"email": self.user, "localizationID": location["BeaconState"]["localizationID"]})
beaconlist.append(location)
tempsessid = db.Get_ActiveSessionFromLocal({"localizationID": location["BeaconState"]["localizationID"]})
if(tempsessid is not None):
sessionlist.append(db.Get_Session(tempsessid))
else:
sessionlist.append(None)
self.returnSuccess(BEACON_DETECTED, {"BeaconList": beaconlist, "SessionList": sessionlist})
return
def beaconUndetectedHandle(self, data):
print "Beacon undetected: " + self.user
db = DB_Accesser()
location = None
location = db.Get_Location(beacon)
if(location is not None):
db.Remove_UserFromLocation({"email": self.user, "localizationID": location["BeaconState"]["localizationID"]})
self.returnSuccess(BEACON_UNDETECTED)
return
def createSessionHandle(self, data):
print "create session: " + self.user
db = DB_Accesser()
location = db.Get_Location(data["BeaconState"])
if db.Get_ActiveSessionFromLocal({"localizationID": location["BeaconState"]["localizationID"]}) is not None:
self.returnInsucess(CREATE_SESSION, "Beacon already has session active...")
return
if(location == None):
self.returnInsucess("No beacon with that ID exists...")
if(location["BeaconState"]["state"] == "Occupied"):
self.returnInsucess("There is already a session in that beacon..")
session = {"s_begin" : datetime.now().date(), "activeFlag":True ,
"localizationID": location["BeaconState"]["localizationID"],
"s_type": data["SessionConfig"]["type"],
"permissions": data["SessionConfig"]["permissions"],"s_name": data["SessionConfig"]["s_name"]}
sessioninfo = db.Insert_Session(session)
if sessioninfo == None:
self.returnInsucess(CREATE_SESSION, "Beacon nonexisting...")
return
db.Insert_UserInSession({"email": self.user, "sessionID": sessioninfo["sessionID"]})
db.Set_SessionAdmin({"email": self.user, "sessionID": sessioninfo["sessionID"]})
self.sessionIDi = sessioninfo["sessionID"]
self.updateUsers(sessioninfo["sessionID"])
self.returnSuccess(CREATE_SESSION, sessioninfo)
self.sendSharinfFrame(YOURNEWADMIN, {"sessionID": sessioninfo["sessionID"]})
return
def joinSessionHandle(self, data):
print "join session: " + self.user + " in session " + chr(data["sessionID"])
db = DB_Accesser()
sessionid = data["sessionID"]
pubpriv = db.Get_Session({"sessionID" : sessionid})
pubpriv = pubpriv["SessionConfig"]["type"]
if(pubpriv == PRIVATE):
admin = db.Get_SessionAdmin({"sessionID": sessionid})
admin = admin["email"]
self.sendSharinfFrame(REQUESTJOINSESSION, {"sessionID": sessionid, "email": self.user}, usr = admin)
responseframe = self.getSharinfFrame(admin)
if responseframe.data == INSUCESS:
self.returnInsucess(JOIN_SESSION, "Administrar didnt accept")
return
result = db.Insert_UserInSession({"email": self.user, "sessionID": sessionid})
if result is True:
self.sessionIDi = sessionid
self.updateUsers(sessionid)
self.returnSuccess(JOIN_SESSION)
else:
self.returnInsucess(JOIN_SESSION, "It was not possible to join sesion probably beacause session does not exists or you are already there...")
return
def getOutSessionHandle(self, data):
print "leave session request: " + self.user + " in session " + chr(data["sessionID"])
db = DB_Accesser()
sessionid = data["sessionID"]
userisadmin = db.Get_UserInSession({"email": self.user , "sessionID": sessionid})
if(userisadmin is None):
self.returnInsucess(GETOUT_SESSION, "No user/session to get out...")
return
userisadmin = userisadmin["adminFlag"]
db.Remove_UserFromSession({"email": self.user, "sessionID": sessionid})
sessionusers = db.Get_AllUsersInSession({"sessionID" : sessionid})
print "sessionuser: " + str(sessionusers)
if sessionusers == []:
db.End_Session({"sessionID": sessionid})
# elif userisadmin:
# print "NEW ADMIN"
# tempusr = sessionusers[0]["email"]
# self.sendSharinfFrame(YOURNEWADMIN, {"sessionID": sessionid}, usr = tempusr)
# #responseframe = self.getSharinfFrame(tempusr)
# #if responseframe.data == SUCCESS:
# db.Set_SessionAdmin({"email": tempusr, "sessionID": sessionid})
print "leave session request DONE: " + self.user + " in session " + chr(data["sessionID"])
self.sessionIDi = None
self.returnSuccess(GETOUT_SESSION)
return sessionid
def loadFileHandle(self, data):
print "load file: " + self.user + " in session " + chr(data["sessionID"])
db = DB_Accesser()
sessionid = data["sessionID"]
permissions = db.Get_Session({"sessionID" : sessionid})
permissions = permissions["SessionConfig"]["permissions"]
admin = db.Get_SessionAdmin({"sessionID": sessionid})
#admin = admin["email"]
if permissions == RESTRICTED and self.user is not admin:
self.returnInsucess(LOAD_FILE_SESSION, "You dont have permissions to share")
return
db.Insert_File(data["File"])
result = db.Insert_FileInSession(data)
if result is True:
self.updateFiles(sessionid)
self.returnSuccess(LOAD_FILE_SESSION, None)
else:
self.returnInsucess(LOAD_FILE_SESSION)
return
def removeFileHandle(self, data):
db = DB_Accesser()
sessionid = data["sessionID"]
freerestr = db.Get_Session({"sessionID" : sessionid})
freerestr = freerestr["SessionConfig"]["permissions"]
owner = db.Get_File(data["File"])
owner = owner["owneremail"]
admin = db.Get_SessionAdmin({"sessionID": sessionid})
admin = admin["email"]
if (permissions == RESTRICTED) and (self.user is not admin) or (self.user is not owner):
self.returnInsucess(LOAD_FILE_SESSION, "You dont have permissions to share or you are not owner")
return
result = db.Remove_FileFromSession(data)
if result is True:
self.updateFiles(sessionid)
self.returnSuccess(LOAD_FILE_SESSION, None)
else:
self.returnInsucess(LOAD_FILE_SESSION)
return
def userListHandle(self,data):
db = DB_Accesser()
users = db.Get_AllUsersInSession(data)
datajson = {"userList": users}
if users is not None:
self.returnSuccess(SESSION_USERLIST, datajson)
else:
self.returnInsucess(SESSION_USERLIST)
def fileListHandle(self,data):
db = DB_Accesser()
files = db.Get_AllFilesFromSession(data)
datajson = {"fileList": files }
if files is not None:
self.returnSuccess(SESSION_FILELIST, datajson)
else:
self.returnInsucess(SESSION_FILELIST)
def getSharinfFrame(self, usr = None):
db = DB_Accesser()
if usr == None:
usr = self.user
skt = socketlist[usr][0]
mtx = socketlist[usr][1]
try:
mtx.acquire()
self.data = skt.recv(5 * 1024)
mtx.release()
except:
print "CONNECTION ABRUPLY TERMINATED BY " + self.user
return None
if self.data is None:
return None
print "Data received: " + self.data
if(self.data[:7] != "SHARINF"):
print "No begin of frame"
return None
index = string.find(self.data,'\endF')
if(index == -1):
print "No end of frame"
return None
try:
returnfram = sharinfFrame(self.data[7], self.data[8:index])
return returnfram
except:
print "RECEIVED BAD FRAME FROM: " + self.user
return None
def sendSharinfFrame(self, cmd, data, usr = None, status = None):
db = DB_Accesser()
if usr == None:
usr = self.user
cmdstr = unichr(cmd)
if data is not None:
datastr = self.encoder.encode(data)
skt = socketlist[usr][0]
mtx = socketlist[usr][2]
try:
mtx.acquire()
if(status is None):
if(data is None):
skt.send("SHARINF" + cmdstr + "\endf")
else:
skt.send("SHARINF" + cmdstr + datastr + "\endf")
else:
if(data is None):
skt.send("SHARINF" + cmdstr + status + "\endf")
else:
skt.send("SHARINF" + cmdstr + status + datastr + "\endf")
mtx.release()
except:
return
def returnSuccess(self, cmd, data = None):
print "Returning success"
self.sendSharinfFrame(cmd, data, status = SUCCESS)
return
def returnInsucess(self, cmd, description = "ERROR"):
print "Returning INSUCESS"
error = { "error" : description }
self.sendSharinfFrame(cmd, error, status = INSUCESS)
return
def updateUsers(self, sessionid):
thread1 = usersThread(sessionid)
thread1.start()
#thread.start_new_thread(sendFilesUpdateForSession, (sessionid,))
return
def updateFiles(self, sessionid):
thread1 = filesThread(sessionid)
thread1.start()
#thread.start_new_thread(sendFilesUpdateForSession, (sessionid,))
return
def handle(self):
self.encoder = json.JSONEncoder()
self.user = self.getUser()
self.sessionIDi = None
if(self.user == None):
return
socketlist[self.user] = (self.request, Lock(), Lock()) #(socket for user, Lock for receiving, Lock for sending)
while(True):
frame = self.getSharinfFrame()
if frame is None:
print "end connection with " + self.user
if(self.sessionIDi is not None):
self.getOutSessionHandle({"sessionID": self.sessionIDi})
socketlist.pop(self.user)
return
if(frame.cmd is BEACON_DETECTED):
self.beaconDetectedHandle(frame.data)
elif(frame.cmd is CREATE_SESSION):
self.createSessionHandle(frame.data)
elif(frame.cmd is GETOUT_SESSION):
sessionid = self.getOutSessionHandle(frame.data)
self.updateUsers(sessionid)
elif(frame.cmd is JOIN_SESSION):
self.joinSessionHandle(frame.data)
elif(frame.cmd is LOAD_FILE_SESSION):
self.loadFileHandle(frame.data)
elif(frame.cmd is REMOVE_FILE_SESSION):
self.removeFileHandle(frame.data)
elif(frame.cmd is SESSION_USERLIST):
self.userListHandle(frame.data)
elif(frame.cmd is SESSION_FILELIST):
self.fileListHandle(frame.data)
elif(frame.cmd is BEACON_UNDETECTED):
self.beaconUndetectedHandle(frame.data)
else:
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass
if __name__ == "__main__":
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)
SocketServer.TCPServer.allow_reuse_address = True
HOST, PORT = socket.gethostbyname(socket.gethostname()), 8888
server = ThreadedTCPServer((HOST, PORT), MyTCPHandler)
print server.server_address
server_thread = threading.Thread(target=server.serve_forever)
#server_thread.daemon = True
server_thread.start()
while(True):
pass
server.shutdown()
server.server_close()