-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsharing.py
509 lines (398 loc) · 12.7 KB
/
sharing.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
import time
import logging
import datetime
import traceback
import threading
postgresInstalled = False
mysqlInstalled = False
try:
import psycopg2
postgresInstalled = True
logging.info('Postgres support enabled')
except:
logging.info(f'Postgres support disabled: {traceback.format_exc()}')
try:
import mysql.connector
mysqlInstalled = True
logging.info('Mysql support enabled')
except:
logging.info(f'Mysql support disabled: {traceback.format_exc()}')
server = None
port = None
db = None
username = None
password = None
dbType = None
writeLock = threading.Lock()
def setDbInfo(newServer, newPort, newDb, newUsername, newPassword, newDbType):
global server, port, db, username, password, dbType
if ((newDbType == 'mysql' and not mysqlInstalled)
or (newDbType == 'postgres' and not postgresInstalled)
or newDbType not in ('mysql', 'postgres')):
return
server = newServer
port = newPort
db = newDb
username = newUsername
password = newPassword
dbType = newDbType
def dbConfigured():
return bool(server)
def getDbConnection():
if dbType == 'mysql':
return mysql.connector.connect(database=db,
host=server,
user=username,
password=password,
port=port)
elif dbType == 'postgres':
return psycopg2.connect(database=db,
host=server,
user=username,
password=password,
port=port)
def getCursor(conn):
if dbType == 'mysql':
return conn.cursor(buffered=True)
else:
return conn.cursor()
def writeState(player, playerId, event, state):
if not dbConfigured():
return
timestamp = round(time.time(), 3)
playerNoQuery = """
select sharing.player_no
from sharing
where sharing.player_name = %(player)s
order by sharing.timestamp desc
limit 1
"""
# deleteQuery = """
# delete from sharing
# where sharing.player_name = %(player)s
# """
insertQuery = """
insert into sharing (player_name, player_id, event_name, state, timestamp, player_no)
values (%(player)s, %(id)s, %(event)s, %(state)s, %(timestamp)s, %(playerNo)s);
"""
updateQuery = """
update events
set last_activity = current_timestamp()
where events.name = %(event)s;
""" if dbType == 'mysql' else """
update events
set last_activity = current_timestamp
where events.name = %(event)s;
"""
with writeLock:
conn = getDbConnection()
cursor = getCursor(conn)
playerNo = None
cursor.execute(playerNoQuery, { 'player': player })
result = cursor.fetchone()
if result:
playerNo = result[0]
cursor.close()
cursor = conn.cursor()
# cursor.execute(deleteQuery, { 'player': player })
cursor.execute(insertQuery, {
'player': player,
'id': playerId,
'event': event,
'state': state,
'timestamp': timestamp,
'playerNo': playerNo,
})
cursor.close()
cursor = conn.cursor()
cursor.execute(updateQuery, {
'event': event,
})
cursor.close()
conn.commit()
conn.close()
return timestamp
def writeLocationHistory(playerName, sessionId, history):
if not dbConfigured():
return
query = """
insert into location_sharing (player_name, session_id, room, x, y, timestamp)
values (%(player)s, %(session)s, %(room)s, %(x)s, %(y)s, %(timestamp)s)
"""
with writeLock:
conn = getDbConnection()
cursor = getCursor(conn)
for point in history:
cursor.execute(query, {
'player': playerName,
'session': sessionId,
'room': point['room'],
'x': point['x'],
'y': point['y'],
'timestamp': point['timestamp'],
})
cursor.close()
conn.commit()
conn.close()
def getNewestSession(playerName):
query = """
select location_sharing.session_id
from location_sharing
where location_sharing.player_name = %(player)s
order by location_sharing.timestamp desc
limit 1
"""
conn = getDbConnection()
cursor = getCursor(conn)
cursor.execute(query, {
'player': playerName,
})
result = cursor.fetchone()
return result[0] if result else None
def getLocationHistory(playerName, timestamp, delaySeconds=0):
if not dbConfigured():
return
sessionId = getNewestSession(playerName)
if not sessionId:
return
query = """
select location_sharing.room
,location_sharing.x
,location_sharing.y
,location_sharing.timestamp
from location_sharing
where location_sharing.timestamp > %(timestamp)s
and location_sharing.player_name = %(player)s
and location_sharing.session_id = %(session)s
and (%(delaySeconds)s = 0 or location_sharing.creation_time <= date_add(current_timestamp(), interval (-1 * %(delaySeconds)s) second))
order by location_sharing.timestamp
""" if dbType == 'mysql' else """
select location_sharing.room
,location_sharing.x
,location_sharing.y
,location_sharing.timestamp
from location_sharing
where location_sharing.timestamp > %(timestamp)s
and location_sharing.player_name = %(player)s
and location_sharing.session_id = %(session)s
and (%(delaySeconds)s = 0 or location_sharing.creation_time <= (current_timestamp - interval '1 second' * %(delaySeconds)s))
order by location_sharing.timestamp
"""
conn = getDbConnection()
cursor = getCursor(conn)
cursor.execute(query, {
'player': playerName,
'session': sessionId,
'timestamp': timestamp,
'delaySeconds': delaySeconds,
})
result = cursor.fetchall()
points = []
for row in result:
points.append({
'room': row[0],
'x': row[1],
'y': row[2],
'timestamp': float(row[3]),
})
cursor.close()
conn.close()
return { 'timestamp': points[-1]['timestamp'], 'points': points, 'sessionId': sessionId } if points else None
def getState(player, timestamp, delaySeconds=0):
if not dbConfigured():
return None
query = """
select sharing.state
,sharing.timestamp
from sharing
where sharing.player_name = %(player)s
and sharing.timestamp > %(timestamp)s
and (%(delaySeconds)s = 0 or sharing.creation_time <= date_add(current_timestamp(), interval (-1 * %(delaySeconds)s) second))
order by sharing.timestamp desc
limit 1
""" if dbType == 'mysql' else """
select sharing.state
,sharing.timestamp
from sharing
where sharing.player_name = %(player)s
and sharing.timestamp > %(timestamp)s
and (%(delaySeconds)s = 0 or sharing.creation_time <= (current_timestamp - interval '1 second' * %(delaySeconds)s))
order by sharing.timestamp desc
limit 1
"""
conn = getDbConnection()
cursor = getCursor(conn)
cursor.execute(query, {
'player': player,
'timestamp': timestamp or 0,
'delaySeconds': delaySeconds,
})
result = cursor.fetchone()
cursor.close()
conn.close()
return { 'state': result[0], 'timestamp': str(result[1]) } if result else None
def getPlayerId(player):
if not dbConfigured():
return None
query = """
select sharing.player_id
from sharing
where sharing.player_name = %(player)s
order by sharing.timestamp desc
limit 1
"""
conn = getDbConnection()
cursor = getCursor(conn)
cursor.execute(query, {
'player': player,
})
result = cursor.fetchone()
cursor.close()
conn.close()
return result[0] if result else None
def getEventPlayers(event):
if not dbConfigured():
return None
threshold = datetime.datetime.now() - datetime.timedelta(hours=2)
threshold = time.mktime(threshold.timetuple())
query = """
select sharing.player_name
,max(sharing.player_no)
from sharing
where sharing.event_name = %(event)s
and sharing.timestamp > %(threshold)s
group by sharing.player_name
order by max(sharing.player_no)
"""
purgeQuery = """
update sharing
set player_no = null
where timestamp <= %(threshold)s
"""
updateQuery = """
update sharing
set player_no = %(playerNo)s
where player_name = %(playerName)s
"""
with writeLock:
conn = getDbConnection()
cursor = conn.cursor()
cursor.execute(query, {
'event': event,
'threshold': threshold,
})
result = cursor.fetchall()
cursor.close()
cursor = conn.cursor()
cursor.execute(purgeQuery, {
'threshold': threshold
})
conn.commit()
players = [{ 'player': x[0], 'number': x[1] } for x in result]
maxNumber = max([x['number'] for x in players if x['number'] != None] or [0])
unNumberedPlayers = sorted([x for x in players if x['number'] == None], key=lambda x: x['player'].lower())
for player in unNumberedPlayers:
player['number'] = maxNumber + 1
cursor.close()
cursor = conn.cursor()
cursor.execute(updateQuery, {
'playerName': player['player'],
'playerNo': player['number'],
})
maxNumber += 1
conn.commit()
cursor.close()
conn.close()
return [x['player'] for x in sorted(players, key=lambda x: x['number'])]
def eventExists(eventName):
if not dbConfigured():
return
eventQuery = """
select 1
from events
where events.name = %(eventName)s
union
select 1
from sharing
where sharing.event_name = %(eventName)s
"""
conn = getDbConnection()
cursor = getCursor(conn)
cursor.execute(eventQuery, { 'eventName': eventName })
result = cursor.fetchone()
cursor.close()
conn.close()
return bool(result)
def eventInfo(eventName):
if not dbConfigured():
return
eventQuery = """
select events.name
,not events.view_code is null as private_view
,not events.join_code is null as private_join
from events
where events.name = %(eventName)s
union
select sharing.event_name
,false as private_view
,false as private_join
from sharing
where sharing.event_name = %(eventName)s
order by private_view desc, private_join desc
"""
conn = getDbConnection()
cursor = getCursor(conn)
cursor.execute(eventQuery, { 'eventName': eventName })
result = cursor.fetchone()
cursor.close()
conn.close()
return {
'eventName': result[0],
'privateView': result[1],
'privateJoin': result[2],
} if result else None
def authenticateEvent(eventName, code):
if not dbConfigured():
return
eventQuery = """
select events.join_code
,events.view_code
from events
where events.name = %(eventName)s
"""
conn = getDbConnection()
cursor = getCursor(conn)
cursor.execute(eventQuery, { 'eventName': eventName })
result = cursor.fetchone()
cursor.close()
conn.close()
if result:
return (code == result[0] or result[0] == None,
code == result[1] or result[1] == None)
return None
def createEvent(eventName, joinCode, viewCode):
if not dbConfigured():
return
query = """
insert into events (name, join_code, view_code)
values (%(eventName)s, %(joinCode)s, %(viewCode)s)
"""
success = True
if eventExists(eventName):
success = False
if success:
if joinCode == '':
joinCode = None
if viewCode == '':
viewCode = None
conn = getDbConnection()
cursor = conn.cursor()
cursor.execute(query, {
'eventName': eventName,
'joinCode': joinCode,
'viewCode': viewCode,
})
conn.commit()
cursor.close()
conn.close()
return success