-
Notifications
You must be signed in to change notification settings - Fork 2
/
_wscapture.py
75 lines (63 loc) · 1.71 KB
/
_wscapture.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
import dataset
import websocket
import time
import json
import sys
import threading
# This script is not ran directly, but spawned by voobly_playback.py
match_id = int(sys.argv[1])
db = dataset.connect('sqlite:///voobly.db')
connected = False
last_seen = time.time()
def flattenit(pyobj, keystring=''):
if type(pyobj) is dict:
keystring = keystring + "_" if keystring else keystring
for k in pyobj:
yield from flattenit(pyobj[k], keystring + k)
elif type(pyobj) is list:
keystring = keystring + "_" if keystring else keystring
for i in range(len(pyobj)):
yield from flattenit(pyobj[i], keystring + str(i))
else:
yield keystring, pyobj
def on_error(ws, error):
print(error)
def on_close(ws):
print("*** Closed")
def on_open(ws):
global connected, last_seen
print("*** Connected")
last_seen = time.time()
t = threading.Thread(target=check_timeout, args=(ws,))
t.start()
connected = True
def on_message(ws, message):
global last_seen
data = json.loads(message)
flattened = {k:v for k,v in flattenit(data)}
flattened['match_id'] = match_id
db['replay'].upsert(flattened, ['match_id', 'current_time', 'type'])
last_seen = time.time()
try:
from exceptions import WinError
except ImportError:
class WinError(OSError): pass
def check_timeout(ws):
while ws.keep_running:
print('last_seen:', last_seen)
tim = time.time()
if tim > last_seen + 5:
print('closing!')
ws.close()
time.sleep(3)
if __name__ == "__main__":
tries = 1
while not connected and tries < 20:
print('Trying to connect...', tries)
tries += 1
ws = websocket.WebSocketApp("ws://localhost:9002/",
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()