-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclientmanager.py
82 lines (67 loc) · 2.65 KB
/
clientmanager.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
from dataclasses import dataclass
from threading import Thread
import time
import base64
import json
from log import log
@dataclass
class Client():
uid: str
data: dict
ip: str
lastConnected: int
evalMessages: list[int]
# Manages state for various clients, so that I can send them updates
class ClientManager():
def __init__(self, dropTime):
self.clients = []
self.dropTime = dropTime
Thread(target=self.continuousRemoveOldClients).start()
self.lastChangeTime = time.time()
def getClients(self):
return self.clients
def decode_data(self, uid):
return json.loads(base64.b64decode(uid).decode("utf-8"))
def registerClientConnect(self, uid, ip, data):
self.lastChangeTime = time.time()
for client in self.clients:
if client.uid == uid:
client.ip = ip
client.lastConnected = time.time()
return
log("New client connected with uid " + str(uid) + " and ip " + str(ip) + " and data " + str(data))
self.clients.append(Client(uid, data, ip, time.time(), ["console.log('Connected to server! Test evaluation.');"]))
def getClientEvaluations(self, uid):
for client in self.clients:
if client.uid == uid:
return client.evalMessages
return []
def clearClientEvaluations(self, uid):
self.lastChangeTime = time.time()
for client in self.clients:
if client.uid == uid:
client.evalMessages = []
def addClientEvaluation(self, uid, code):
self.lastChangeTime = time.time()
log("Told to add client evaluation for uid " + uid + " with code " + code)
for client in self.clients:
if client.uid == uid or uid == "*":
client.evalMessages.append(code)
log("Found! Added evaluation.")
if uid != "*":
return
if uid != "*":
log("Not found!")
def removeOldClients(self):
deleteList = [] # to make it all one operation. I could use a list comprehension, but then I wouldn't get to log it.
for client in self.clients:
if time.time() - client.lastConnected > self.dropTime:
log("Planning to remove client with uid " + client.uid + " due to inactivity")
deleteList.append(client)
self.clients = [client for client in self.clients if not client in deleteList]
if len(deleteList) > 0:
self.lastChangeTime = time.time()
def continuousRemoveOldClients(self):
while True:
self.removeOldClients()
time.sleep(5)