forked from seatable/seatable-api-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket_io.py
More file actions
84 lines (63 loc) · 2.68 KB
/
socket_io.py
File metadata and controls
84 lines (63 loc) · 2.68 KB
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
import time
from datetime import datetime
# https://python-socketio.readthedocs.io
import socketio
from .constants import JOIN_ROOM, UPDATE_DTABLE, NEW_NOTIFICATION
class SIO(socketio.Client):
def _handle_disconnect(self, namespace):
"""io server disconnect"""
self.logger.info('Engine.IO connection disconnected')
if not self.connected:
return
self.disconnect()
namespace = namespace or '/'
self._trigger_event('io-disconnect', namespace=namespace)
class SocketIO(object):
def __init__(self, base):
self.base = base
self.sio = SIO(request_timeout=base.timeout)
def __str__(self):
return '<SeaTable SocketIO [ %s ]>' % self.base.dtable_name
def _connect(self):
self.sio.on('connect', self._on_connect)
self.sio.on('disconnect', self._on_disconnect)
self.sio.on('io-disconnect', self._on_io_disconnect)
self.sio.on('connect_error', self._on_connect_error)
self.sio.on(UPDATE_DTABLE, self.on_update_dtable)
self.sio.on(NEW_NOTIFICATION, self.on_new_notification)
self.sio.connect(self._dtable_ws_url())
def _dtable_ws_url(self):
return self.base.dtable_server_url + '?dtable_uuid=' + self.base.dtable_uuid
def _refresh_jwt_token(self):
self.base.auth()
print(datetime.now(), '[ SeaTable SocketIO JWT token refreshed ]')
def _on_connect(self):
if datetime.now() >= self.base.jwt_exp:
self._refresh_jwt_token()
self.sio.emit(JOIN_ROOM, (self.base.dtable_uuid, self.base.jwt_token))
print(datetime.now(), '[ SeaTable SocketIO connection established ]')
def _on_disconnect(self):
print(datetime.now(), '[ SeaTable SocketIO connection dropped ]')
def _on_io_disconnect(self):
print(datetime.now(), '[ SeaTable SocketIO connection disconnected ]')
time.sleep(3)
self._refresh_jwt_token()
self.sio.connect(self._dtable_ws_url())
def _on_connect_error(self, error_msg):
print(datetime.now(), '[ SeaTable SocketIO connection error ]', error_msg)
def on_update_dtable(self, data, index, *args):
""" Default is print received data
You can overwrite this event
"""
print(datetime.now(), '[ SeaTable SocketIO on UPDATE_DTABLE ]')
print(data)
def on_new_notification(self, data, index, *args):
""" Default is print received data
You can overwrite this event
"""
print(datetime.now(), '[ SeaTable SocketIO on NEW_NOTIFICATION ]')
print(data)
def on(self, event, handler):
self.sio.on(event, handler)
def wait(self):
self.sio.wait()