skapi 2.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- skapi/__init__.py +15 -0
- skapi/_cognito.py +386 -0
- skapi/_database.py +1454 -0
- skapi/_encryption.py +1359 -0
- skapi/_forward.py +484 -0
- skapi/_http.py +373 -0
- skapi/_md5.py +94 -0
- skapi/_project.py +83 -0
- skapi/_realtime.py +549 -0
- skapi/_social.py +323 -0
- skapi/_srp.py +126 -0
- skapi/_user.py +880 -0
- skapi/_ws.py +176 -0
- skapi/client.py +270 -0
- skapi/errors.py +26 -0
- skapi-2.4.0.dist-info/METADATA +46 -0
- skapi-2.4.0.dist-info/RECORD +20 -0
- skapi-2.4.0.dist-info/WHEEL +5 -0
- skapi-2.4.0.dist-info/licenses/LICENSE +201 -0
- skapi-2.4.0.dist-info/top_level.txt +1 -0
skapi/_realtime.py
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Realtime messaging over a WebSocket, ported from skapi-js (src/methods/realtime.ts) without
|
|
3
|
+
WebRTC: one connection per Skapi object, one group at a time, private messages to users,
|
|
4
|
+
presence notices, keep-alive, planned renewal before the server's 2 hour cut, and reconnects.
|
|
5
|
+
|
|
6
|
+
The callback runs on a background thread with dicts shaped as in skapi-js:
|
|
7
|
+
{"type", "message", "sender", "sender_cid", "sender_rid", "code"} for messages and notices, and
|
|
8
|
+
{"type", "message"} for connection events (success, close, error, reconnect).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import random
|
|
15
|
+
import re
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
import warnings
|
|
19
|
+
from typing import Any, Callable, Dict, Optional
|
|
20
|
+
|
|
21
|
+
from ._database import user_id as _user_id
|
|
22
|
+
from ._ws import WebSocket, WebSocketClosed
|
|
23
|
+
from .errors import SkapiError
|
|
24
|
+
|
|
25
|
+
PING_INTERVAL = 60.0
|
|
26
|
+
PONG_TIMEOUT = 10.0
|
|
27
|
+
PONGLESS_PINGS_DEAD = 3
|
|
28
|
+
CONNECTION_LIFETIME = 7200.0
|
|
29
|
+
RENEW_BEFORE = 300.0
|
|
30
|
+
RENEW_JITTER = 120.0
|
|
31
|
+
JOIN_WAIT = 3.0
|
|
32
|
+
SEND_WINDOW = 0.1
|
|
33
|
+
SEQ_WAIT = 1.5
|
|
34
|
+
MAX_FRAME_BYTES = 32768
|
|
35
|
+
BATCH_CHARS = MAX_FRAME_BYTES - 2048
|
|
36
|
+
MAX_NOTIFICATION_BYTES = 3072
|
|
37
|
+
_UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE)
|
|
38
|
+
_PRESENCE = {"j": [("has joined the message group.", "USER_JOINED")],
|
|
39
|
+
"l": [("has left the message group.", "USER_LEFT")],
|
|
40
|
+
"d": [("has been disconnected.", "USER_DISCONNECTED"), ("has left the message group.", "USER_LEFT")]}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _p(message: str, code: str = "INVALID_PARAMETER") -> SkapiError:
|
|
44
|
+
return SkapiError(message, code)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class _Realtime:
|
|
48
|
+
"""The live state of one Skapi object's realtime connection."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, skapi, callback: Callable[[Dict[str, Any]], None]):
|
|
51
|
+
self.skapi = skapi
|
|
52
|
+
self.callback = callback
|
|
53
|
+
self.ws: Optional[WebSocket] = None
|
|
54
|
+
self.lock = threading.RLock()
|
|
55
|
+
self.closing = False
|
|
56
|
+
self.room: Optional[str] = None
|
|
57
|
+
self.reconnect_attempts = 0
|
|
58
|
+
self.seq = 0
|
|
59
|
+
self.order: Dict[str, Dict[str, Any]] = {}
|
|
60
|
+
self.join_wait: Optional[Dict[str, Any]] = None
|
|
61
|
+
self.pong_seen = False
|
|
62
|
+
self.pongless_pings = 0
|
|
63
|
+
self.pong_deadline: Optional[float] = None
|
|
64
|
+
self.ping_sent_at = 0.0
|
|
65
|
+
self.renew_at = 0.0
|
|
66
|
+
self.generation = 0
|
|
67
|
+
self.last_send: Dict[str, float] = {}
|
|
68
|
+
self.window: Optional[Dict[str, Any]] = None
|
|
69
|
+
self.send_lock = threading.Lock()
|
|
70
|
+
|
|
71
|
+
# ---- events to the user's callback -----------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
def emit(self, msg: Dict[str, Any]) -> None:
|
|
74
|
+
try:
|
|
75
|
+
self.callback(msg)
|
|
76
|
+
except Exception as err:
|
|
77
|
+
warnings.warn(f"realtime callback raised {err!r}", RuntimeWarning, stacklevel=2)
|
|
78
|
+
|
|
79
|
+
# ---- connection -------------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
def open(self, renew: bool = False) -> None:
|
|
82
|
+
"""Opens a socket (fresh token first) and starts its reader and keep-alive threads."""
|
|
83
|
+
token = self.skapi._access_token()
|
|
84
|
+
_, record = self.skapi._requester.endpoints()
|
|
85
|
+
try:
|
|
86
|
+
ws = WebSocket(record["websocket_private"] + "?token=" + token)
|
|
87
|
+
except (WebSocketClosed, OSError) as err:
|
|
88
|
+
raise SkapiError("WebSocket closed before it opened.", "INVALID_REQUEST", err) from None
|
|
89
|
+
with self.lock:
|
|
90
|
+
old = self.ws
|
|
91
|
+
self.ws = ws
|
|
92
|
+
self.generation += 1
|
|
93
|
+
generation = self.generation
|
|
94
|
+
self.pong_seen = False
|
|
95
|
+
self.pongless_pings = 0
|
|
96
|
+
self.pong_deadline = None
|
|
97
|
+
self.reconnect_attempts = 0
|
|
98
|
+
self.renew_at = time.time() + CONNECTION_LIFETIME - RENEW_BEFORE - random.random() * RENEW_JITTER
|
|
99
|
+
if not renew:
|
|
100
|
+
self.emit({"type": "success", "message": "Connected to WebSocket server."})
|
|
101
|
+
self.forget_order()
|
|
102
|
+
if self.room:
|
|
103
|
+
self.send_raw({"action": "joinRoom", "rid": self.room, "token": self.skapi._session.access_token.jwt_token, "ver": 2})
|
|
104
|
+
threading.Thread(target=self.read_loop, args=(ws, generation), daemon=True, name="skapi-realtime-read").start()
|
|
105
|
+
threading.Thread(target=self.ping_loop, args=(ws, generation), daemon=True, name="skapi-realtime-ping").start()
|
|
106
|
+
if renew and old is not None:
|
|
107
|
+
try:
|
|
108
|
+
old.close()
|
|
109
|
+
except OSError:
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
def send_raw(self, frame: Dict[str, Any]) -> None:
|
|
113
|
+
ws = self.ws
|
|
114
|
+
if ws is None or ws.closed:
|
|
115
|
+
raise _p("Realtime connection is not open. Try reconnecting with connect_realtime().", "INVALID_REQUEST")
|
|
116
|
+
ws.send(json.dumps(frame, separators=(",", ":"), ensure_ascii=False))
|
|
117
|
+
|
|
118
|
+
def current(self, generation: int) -> bool:
|
|
119
|
+
return generation == self.generation and not self.closing
|
|
120
|
+
|
|
121
|
+
def ping_loop(self, ws: WebSocket, generation: int) -> None:
|
|
122
|
+
next_ping = time.time()
|
|
123
|
+
while self.current(generation) and not ws.closed:
|
|
124
|
+
now = time.time()
|
|
125
|
+
if self.pong_deadline is not None and now >= self.pong_deadline:
|
|
126
|
+
if now - self.ping_sent_at > 30:
|
|
127
|
+
self.pong_deadline = None # this thread ran late: ping again instead
|
|
128
|
+
next_ping = now
|
|
129
|
+
else:
|
|
130
|
+
self.drop(ws, generation)
|
|
131
|
+
return
|
|
132
|
+
if now >= self.renew_at:
|
|
133
|
+
self.renew_at = float("inf")
|
|
134
|
+
threading.Thread(target=self.renew, args=(generation,), daemon=True).start()
|
|
135
|
+
if now >= next_ping:
|
|
136
|
+
if self.pong_seen:
|
|
137
|
+
self.pongless_pings += 1
|
|
138
|
+
if self.pongless_pings >= PONGLESS_PINGS_DEAD:
|
|
139
|
+
self.drop(ws, generation)
|
|
140
|
+
return
|
|
141
|
+
if self.pong_deadline is None:
|
|
142
|
+
self.ping_sent_at = now
|
|
143
|
+
self.pong_deadline = now + PONG_TIMEOUT
|
|
144
|
+
try:
|
|
145
|
+
ws.send('{"action":"keepAlive"}')
|
|
146
|
+
except (OSError, WebSocketClosed):
|
|
147
|
+
return
|
|
148
|
+
next_ping = now + PING_INTERVAL
|
|
149
|
+
time.sleep(0.5)
|
|
150
|
+
|
|
151
|
+
def renew(self, generation: int) -> None:
|
|
152
|
+
if not self.current(generation):
|
|
153
|
+
return
|
|
154
|
+
try:
|
|
155
|
+
self.open(renew=True)
|
|
156
|
+
except SkapiError:
|
|
157
|
+
pass # the old socket stays
|
|
158
|
+
|
|
159
|
+
def drop(self, ws: WebSocket, generation: int) -> None:
|
|
160
|
+
if not self.current(generation):
|
|
161
|
+
return
|
|
162
|
+
try:
|
|
163
|
+
ws.close()
|
|
164
|
+
except OSError:
|
|
165
|
+
pass
|
|
166
|
+
self.emit({"type": "error", "message": "Skapi: WebSocket unexpected close."})
|
|
167
|
+
self.schedule_reconnect(generation)
|
|
168
|
+
|
|
169
|
+
def schedule_reconnect(self, generation: int) -> None:
|
|
170
|
+
def run():
|
|
171
|
+
while self.current(generation):
|
|
172
|
+
if not self.skapi._signed_in():
|
|
173
|
+
self.emit({"type": "error", "message": "Skapi: Realtime connection closed. User login is required."})
|
|
174
|
+
return
|
|
175
|
+
self.reconnect_attempts += 1
|
|
176
|
+
attempts = self.reconnect_attempts
|
|
177
|
+
base = min(30.0, 3.0 * 2 ** (attempts - 1))
|
|
178
|
+
self.emit({"type": "reconnect", "message": f"Reconnecting to WebSocket server...{attempts}"})
|
|
179
|
+
time.sleep(base * (1 + random.random() * 0.5))
|
|
180
|
+
if not self.current(generation):
|
|
181
|
+
return
|
|
182
|
+
try:
|
|
183
|
+
if self.skapi._user and self.skapi._user.get("anonymous"):
|
|
184
|
+
if self.skapi.verify_anonymous_session() is None:
|
|
185
|
+
continue
|
|
186
|
+
self.open()
|
|
187
|
+
return
|
|
188
|
+
except SkapiError:
|
|
189
|
+
continue
|
|
190
|
+
threading.Thread(target=run, daemon=True, name="skapi-realtime-reconnect").start()
|
|
191
|
+
|
|
192
|
+
def read_loop(self, ws: WebSocket, generation: int) -> None:
|
|
193
|
+
while True:
|
|
194
|
+
try:
|
|
195
|
+
text = ws.recv()
|
|
196
|
+
except (WebSocketClosed, OSError):
|
|
197
|
+
if self.current(generation):
|
|
198
|
+
self.emit({"type": "error", "message": "Skapi: WebSocket unexpected close."})
|
|
199
|
+
self.schedule_reconnect(generation)
|
|
200
|
+
elif self.closing and generation == self.generation:
|
|
201
|
+
self.emit({"type": "close", "message": "WebSocket connection closed."})
|
|
202
|
+
return
|
|
203
|
+
self.pong_deadline = None
|
|
204
|
+
try:
|
|
205
|
+
data = json.loads(text)
|
|
206
|
+
except ValueError:
|
|
207
|
+
continue
|
|
208
|
+
if isinstance(data, dict):
|
|
209
|
+
self.read_frame(data)
|
|
210
|
+
|
|
211
|
+
# ---- incoming frames -------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
def read_frame(self, data: Dict[str, Any]) -> None:
|
|
214
|
+
if "#pong" in data:
|
|
215
|
+
self.pong_seen = True
|
|
216
|
+
self.pongless_pings = 0
|
|
217
|
+
return
|
|
218
|
+
if isinstance(data.get("#presence"), list):
|
|
219
|
+
rid = data.get("#srid")
|
|
220
|
+
for event in data["#presence"]:
|
|
221
|
+
if not isinstance(event, list) or not event or event[0] not in _PRESENCE:
|
|
222
|
+
continue
|
|
223
|
+
uid = event[1] if len(event) > 1 else None
|
|
224
|
+
cid = event[2] if len(event) > 2 else None
|
|
225
|
+
for text, code in _PRESENCE[event[0]]:
|
|
226
|
+
self.notice({"type": "notice", "message": f'User "{uid}" {text}', "sender": uid or None,
|
|
227
|
+
"sender_cid": f"cid:{cid}" if cid else None, "sender_rid": rid or None, "code": code})
|
|
228
|
+
return
|
|
229
|
+
if isinstance(data.get("#batch"), list):
|
|
230
|
+
for entry in data["#batch"]:
|
|
231
|
+
if isinstance(entry, dict):
|
|
232
|
+
self.read_frame(entry)
|
|
233
|
+
return
|
|
234
|
+
kind = None
|
|
235
|
+
for key, name in (("#message", "message"), ("#private", "private"), ("#notice", "notice"), ("#rtc", "rtc"), ("#error", "error"), ("#ice", "ice")):
|
|
236
|
+
if key in data:
|
|
237
|
+
kind = name
|
|
238
|
+
payload = data[key]
|
|
239
|
+
break
|
|
240
|
+
if kind in (None, "rtc", "ice"):
|
|
241
|
+
return
|
|
242
|
+
msg = {"type": kind, "message": payload, "sender": data.get("#user_id") or None,
|
|
243
|
+
"sender_cid": f"cid:{data['#scid']}" if data.get("#scid") else None,
|
|
244
|
+
"sender_rid": data.get("#srid") or None, "code": data.get("#code") or None}
|
|
245
|
+
if kind == "notice":
|
|
246
|
+
self.notice(msg)
|
|
247
|
+
elif kind == "message" and isinstance(data.get("#seq"), (int, float)) and not isinstance(data.get("#seq"), bool) and msg["sender_cid"]:
|
|
248
|
+
self.in_order(msg, int(data["#seq"]))
|
|
249
|
+
else:
|
|
250
|
+
self.deliver(msg)
|
|
251
|
+
|
|
252
|
+
def deliver(self, msg: Dict[str, Any]) -> None:
|
|
253
|
+
body = msg.get("message")
|
|
254
|
+
if isinstance(body, dict) and isinstance(body.get("__skapi_batch"), list):
|
|
255
|
+
for item in body["__skapi_batch"]:
|
|
256
|
+
self.emit(dict(msg, message=item))
|
|
257
|
+
else:
|
|
258
|
+
self.emit(msg)
|
|
259
|
+
|
|
260
|
+
def notice(self, msg: Dict[str, Any]) -> None:
|
|
261
|
+
if msg.get("code") in ("USER_LEFT", "USER_DISCONNECTED") and msg.get("sender_cid"):
|
|
262
|
+
self.forget_order(msg["sender_cid"])
|
|
263
|
+
wait = self.join_wait
|
|
264
|
+
if (wait and msg.get("code") == "USER_JOINED" and msg.get("sender_rid") == wait["group"]
|
|
265
|
+
and msg.get("sender") == (self.skapi._user or {}).get("user_id")):
|
|
266
|
+
wait["event"].set()
|
|
267
|
+
self.emit(msg)
|
|
268
|
+
|
|
269
|
+
# in-order delivery of a sender's numbered group messages (the fan-out can reorder them)
|
|
270
|
+
def in_order(self, msg: Dict[str, Any], seq: int) -> None:
|
|
271
|
+
with self.lock:
|
|
272
|
+
cid = msg["sender_cid"]
|
|
273
|
+
state = self.order.setdefault(cid, {"next": seq, "waiting": {}, "timer": None})
|
|
274
|
+
if seq < state["next"]:
|
|
275
|
+
ready = [msg]
|
|
276
|
+
else:
|
|
277
|
+
state["waiting"][seq] = msg
|
|
278
|
+
ready = self._drain(state)
|
|
279
|
+
if state["waiting"] and state["timer"] is None:
|
|
280
|
+
state["timer"] = threading.Timer(SEQ_WAIT, self._skip_gap, args=(cid,))
|
|
281
|
+
state["timer"].daemon = True
|
|
282
|
+
state["timer"].start()
|
|
283
|
+
for m in ready:
|
|
284
|
+
self.deliver(m)
|
|
285
|
+
|
|
286
|
+
def _drain(self, state) -> list:
|
|
287
|
+
out = []
|
|
288
|
+
while state["next"] in state["waiting"]:
|
|
289
|
+
out.append(state["waiting"].pop(state["next"]))
|
|
290
|
+
state["next"] += 1
|
|
291
|
+
return out
|
|
292
|
+
|
|
293
|
+
def _skip_gap(self, cid: str) -> None:
|
|
294
|
+
with self.lock:
|
|
295
|
+
state = self.order.get(cid)
|
|
296
|
+
if not state:
|
|
297
|
+
return
|
|
298
|
+
state["timer"] = None
|
|
299
|
+
if state["waiting"]:
|
|
300
|
+
state["next"] = min(state["waiting"])
|
|
301
|
+
ready = self._drain(state)
|
|
302
|
+
if state["waiting"]:
|
|
303
|
+
state["timer"] = threading.Timer(SEQ_WAIT, self._skip_gap, args=(cid,))
|
|
304
|
+
state["timer"].daemon = True
|
|
305
|
+
state["timer"].start()
|
|
306
|
+
for m in ready:
|
|
307
|
+
self.deliver(m)
|
|
308
|
+
|
|
309
|
+
def forget_order(self, cid: Optional[str] = None) -> None:
|
|
310
|
+
with self.lock:
|
|
311
|
+
cids = [cid] if cid else list(self.order)
|
|
312
|
+
ready = []
|
|
313
|
+
for c in cids:
|
|
314
|
+
state = self.order.pop(c, None)
|
|
315
|
+
if state:
|
|
316
|
+
if state["timer"]:
|
|
317
|
+
state["timer"].cancel()
|
|
318
|
+
ready += [state["waiting"][k] for k in sorted(state["waiting"])]
|
|
319
|
+
for m in ready:
|
|
320
|
+
self.deliver(m)
|
|
321
|
+
|
|
322
|
+
# ---- outgoing group posts: posts within 100 ms travel as one frame, so they arrive in order
|
|
323
|
+
|
|
324
|
+
def queue_group_post(self, group: str, content: Any, frame_base: Dict[str, Any]) -> None:
|
|
325
|
+
with self.send_lock:
|
|
326
|
+
if self.window and self.window["group"] != group:
|
|
327
|
+
self._flush_locked()
|
|
328
|
+
if self.window:
|
|
329
|
+
self.window["items"].append(content)
|
|
330
|
+
return
|
|
331
|
+
now = time.time()
|
|
332
|
+
since = now - self.last_send.get(group, 0)
|
|
333
|
+
self.last_send[group] = now
|
|
334
|
+
if since >= SEND_WINDOW:
|
|
335
|
+
self._send_group(frame_base, content)
|
|
336
|
+
return
|
|
337
|
+
timer = threading.Timer(SEND_WINDOW, self.flush)
|
|
338
|
+
timer.daemon = True
|
|
339
|
+
self.window = {"group": group, "items": [content], "base": frame_base, "timer": timer}
|
|
340
|
+
timer.start()
|
|
341
|
+
|
|
342
|
+
def flush(self) -> None:
|
|
343
|
+
with self.send_lock:
|
|
344
|
+
self._flush_locked()
|
|
345
|
+
|
|
346
|
+
def _flush_locked(self) -> None:
|
|
347
|
+
w, self.window = self.window, None
|
|
348
|
+
if not w:
|
|
349
|
+
return
|
|
350
|
+
w["timer"].cancel()
|
|
351
|
+
self.last_send[w["group"]] = time.time()
|
|
352
|
+
items = w["items"]
|
|
353
|
+
while items:
|
|
354
|
+
n = len(items)
|
|
355
|
+
while n > 1 and len(json.dumps({"__skapi_batch": items[:n]}, separators=(",", ":"), ensure_ascii=False).encode("utf-16-le")) // 2 > BATCH_CHARS:
|
|
356
|
+
n = -(-n // 2)
|
|
357
|
+
self._send_group(w["base"], items[0] if n == 1 else {"__skapi_batch": items[:n]})
|
|
358
|
+
items = items[n:]
|
|
359
|
+
|
|
360
|
+
def _send_group(self, base: Dict[str, Any], content: Any) -> None:
|
|
361
|
+
with self.lock:
|
|
362
|
+
seq = self.seq
|
|
363
|
+
self.seq += 1
|
|
364
|
+
frame = dict(base, content=content)
|
|
365
|
+
frame["seq"] = seq
|
|
366
|
+
try:
|
|
367
|
+
self.send_raw(frame)
|
|
368
|
+
except (SkapiError, OSError, WebSocketClosed):
|
|
369
|
+
pass # not open at send time: dropped, as in skapi-js
|
|
370
|
+
|
|
371
|
+
def close(self) -> None:
|
|
372
|
+
self.closing = True
|
|
373
|
+
if self.window:
|
|
374
|
+
self.window["timer"].cancel()
|
|
375
|
+
self.window = None
|
|
376
|
+
ws = self.ws
|
|
377
|
+
if self.join_wait:
|
|
378
|
+
self.join_wait["event"].set()
|
|
379
|
+
self.room = None
|
|
380
|
+
if ws is not None:
|
|
381
|
+
ws.close()
|
|
382
|
+
self.forget_order()
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class RealtimeMixin:
|
|
386
|
+
"""Mixed into Skapi."""
|
|
387
|
+
|
|
388
|
+
_rt: Optional[_Realtime] = None
|
|
389
|
+
|
|
390
|
+
def connect_realtime(self, callback: Callable[[Dict[str, Any]], None]) -> None:
|
|
391
|
+
"""
|
|
392
|
+
Opens the realtime connection. callback(event) runs on a background thread for every
|
|
393
|
+
message, notice and connection event. Returns once connected; reconnects on its own.
|
|
394
|
+
"""
|
|
395
|
+
if not callable(callback):
|
|
396
|
+
raise SkapiError("Callback must be a function.", "INVALID_REQUEST")
|
|
397
|
+
self._ensure_connection()
|
|
398
|
+
if not self._signed_in():
|
|
399
|
+
raise SkapiError("No access.", "INVALID_REQUEST")
|
|
400
|
+
if self._rt is not None and not self._rt.closing:
|
|
401
|
+
self._rt.callback = callback
|
|
402
|
+
return
|
|
403
|
+
rt = _Realtime(self, callback)
|
|
404
|
+
self._rt = rt
|
|
405
|
+
try:
|
|
406
|
+
rt.open()
|
|
407
|
+
except SkapiError:
|
|
408
|
+
self._rt = None
|
|
409
|
+
rt.emit({"type": "error", "message": "Skapi: WebSocket connection failed."})
|
|
410
|
+
raise
|
|
411
|
+
|
|
412
|
+
def close_realtime(self) -> None:
|
|
413
|
+
"""Closes the realtime connection; the group hears that you disconnected and left."""
|
|
414
|
+
rt, self._rt = self._rt, None
|
|
415
|
+
if rt is not None:
|
|
416
|
+
rt.close()
|
|
417
|
+
|
|
418
|
+
def _live(self) -> _Realtime:
|
|
419
|
+
if self._rt is None or self._rt.closing:
|
|
420
|
+
raise SkapiError("No realtime connection. Execute connect_realtime() before this method.", "INVALID_REQUEST")
|
|
421
|
+
return self._rt
|
|
422
|
+
|
|
423
|
+
def join_realtime(self, group: Any) -> Dict[str, str]:
|
|
424
|
+
"""Joins a message group (one at a time), or leaves the current one with None."""
|
|
425
|
+
rt = self._live()
|
|
426
|
+
if isinstance(group, dict):
|
|
427
|
+
group = group.get("group")
|
|
428
|
+
group = group or None
|
|
429
|
+
if not group and not rt.room:
|
|
430
|
+
return {"type": "success", "message": "Left realtime message group."}
|
|
431
|
+
if group is not None and not isinstance(group, str):
|
|
432
|
+
raise _p('"group" must be a string | None.')
|
|
433
|
+
token = self._access_token()
|
|
434
|
+
if rt.join_wait:
|
|
435
|
+
rt.join_wait["event"].set()
|
|
436
|
+
if rt.ws is not None and not rt.ws.closed:
|
|
437
|
+
rt.send_raw({"action": "joinRoom", "rid": group, "token": token, "ver": 2})
|
|
438
|
+
if group:
|
|
439
|
+
rt.join_wait = {"group": group, "event": threading.Event(), "until": time.time() + JOIN_WAIT}
|
|
440
|
+
rt.room = group
|
|
441
|
+
return {"type": "success", "message": f'Joined realtime message group: "{group}".' if group else "Left realtime message group."}
|
|
442
|
+
|
|
443
|
+
def post_realtime(self, message: Any, recipient: str, notification: Optional[Dict[str, Any]] = None) -> Dict[str, str]:
|
|
444
|
+
"""Sends to a user (by user ID) or to the group you joined. notification: {title, body, config?: {always}}."""
|
|
445
|
+
rt = self._live()
|
|
446
|
+
if not recipient:
|
|
447
|
+
raise SkapiError("No recipient.", "INVALID_REQUEST")
|
|
448
|
+
self._fresh_id_token()
|
|
449
|
+
notification_str, config = "", {}
|
|
450
|
+
if notification is not None:
|
|
451
|
+
if not isinstance(notification, dict):
|
|
452
|
+
raise _p('"notification" should be an object with "title" and "body".')
|
|
453
|
+
for key in ("title", "body"):
|
|
454
|
+
if key not in notification:
|
|
455
|
+
raise _p(f'Key "{key}" is required.')
|
|
456
|
+
if not isinstance(notification[key], str):
|
|
457
|
+
raise _p(f'"{key}" should be type: <string>.')
|
|
458
|
+
config = notification.get("config") or {}
|
|
459
|
+
if not isinstance(config, dict) or ("always" in config and not isinstance(config["always"], bool)):
|
|
460
|
+
raise _p('"config.always" should be type: <boolean>.')
|
|
461
|
+
notification_str = json.dumps({"title": notification["title"], "body": notification["body"]}, separators=(",", ":"), ensure_ascii=False)
|
|
462
|
+
if len(notification_str.encode("utf-8")) > MAX_NOTIFICATION_BYTES:
|
|
463
|
+
raise _p("Notification size exceeds 3kb.")
|
|
464
|
+
if rt.ws is None or rt.ws.closed:
|
|
465
|
+
raise SkapiError("Realtime connection is not open. Try reconnecting with connect_realtime().", "INVALID_REQUEST")
|
|
466
|
+
token = f"IdT:{self.service}:{self.owner}:{self._session.id_token.jwt_token}"
|
|
467
|
+
|
|
468
|
+
def checked(frame):
|
|
469
|
+
size = len(json.dumps(frame, separators=(",", ":"), ensure_ascii=False).encode("utf-8"))
|
|
470
|
+
if size > MAX_FRAME_BYTES:
|
|
471
|
+
raise _p(f"Message is {size} bytes; a realtime message can be at most {MAX_FRAME_BYTES} bytes including its headers.")
|
|
472
|
+
return frame
|
|
473
|
+
|
|
474
|
+
if isinstance(recipient, str) and _UUID.match(recipient):
|
|
475
|
+
rt.send_raw(checked({"action": "sendMessage", "uid": recipient, "content": message, "notification": notification_str,
|
|
476
|
+
"notificationConfig": config, "token": token}))
|
|
477
|
+
return {"type": "success", "message": "Message sent."}
|
|
478
|
+
|
|
479
|
+
if recipient != rt.room:
|
|
480
|
+
raise SkapiError(f'User has not joined to the recipient group. Run join_realtime("{recipient}")', "INVALID_REQUEST")
|
|
481
|
+
checked({"action": "broadcast", "rid": recipient, "content": message, "notification": notification_str,
|
|
482
|
+
"notificationConfig": config, "token": token, "#seq": 0})
|
|
483
|
+
wait = rt.join_wait
|
|
484
|
+
if wait and wait["group"] == recipient:
|
|
485
|
+
# until the server announces your own join, the group would not get the message yet
|
|
486
|
+
wait["event"].wait(max(0.0, wait["until"] - time.time()))
|
|
487
|
+
if rt.join_wait is wait:
|
|
488
|
+
rt.join_wait = None
|
|
489
|
+
base = {"action": "broadcast", "rid": recipient, "notification": notification_str, "notificationConfig": config, "token": token}
|
|
490
|
+
if notification is not None:
|
|
491
|
+
rt._send_group(base, message) # a post with a notification is never grouped
|
|
492
|
+
else:
|
|
493
|
+
rt.queue_group_post(recipient, message, base)
|
|
494
|
+
return {"type": "success", "message": "Message sent."}
|
|
495
|
+
|
|
496
|
+
def get_realtime_users(self, params: Optional[Dict[str, Any]] = None, fetch_options: Optional[dict] = None) -> dict:
|
|
497
|
+
"""Who is connected in a group (default: the group you joined): [{user_id, cid}]."""
|
|
498
|
+
params = dict(params or {})
|
|
499
|
+
body: Dict[str, Any] = {}
|
|
500
|
+
if "group" in params:
|
|
501
|
+
if not isinstance(params["group"], str):
|
|
502
|
+
raise _p(f'{json.dumps(params["group"], default=repr)} is invalid in "group". allowed type or value is: Type<string>.')
|
|
503
|
+
body["group"] = params["group"]
|
|
504
|
+
else:
|
|
505
|
+
room = self._rt.room if self._rt else None
|
|
506
|
+
if not room:
|
|
507
|
+
raise _p('No group has been joined. Otherwise "group" is required.')
|
|
508
|
+
body["group"] = room
|
|
509
|
+
if "user_id" in params:
|
|
510
|
+
body["user_id"] = _user_id(params["user_id"], 'User ID in "user_id"')
|
|
511
|
+
res = self._call("get-ws-group", body, auth=True, fetch_options=fetch_options)
|
|
512
|
+
if isinstance(res, dict) and isinstance(res.get("list"), list):
|
|
513
|
+
res["list"] = [{"user_id": str(i.get("uid", "")).split("#")[1] if "#" in str(i.get("uid", "")) else i.get("uid"),
|
|
514
|
+
"cid": f"cid:{i.get('cid')}"} for i in res["list"]]
|
|
515
|
+
return res
|
|
516
|
+
|
|
517
|
+
def get_realtime_groups(self, params: Optional[Dict[str, Any]] = None, fetch_options: Optional[dict] = None) -> dict:
|
|
518
|
+
"""Groups that have members now: [{group, number_of_users}]."""
|
|
519
|
+
self._ensure_connection()
|
|
520
|
+
if not params:
|
|
521
|
+
params = {"searchFor": "group", "value": " ", "condition": ">"}
|
|
522
|
+
params = dict(params)
|
|
523
|
+
search_for = params.get("searchFor", "group")
|
|
524
|
+
if search_for not in ("group", "number_of_users"):
|
|
525
|
+
raise _p(f'{json.dumps(search_for, default=repr)} is invalid in "searchFor". allowed types or values are: "group", "number_of_users".')
|
|
526
|
+
value = params.get("value", 0 if search_for == "number_of_users" else " ")
|
|
527
|
+
conditions = [">", ">=", "=", "<", "<=", "!=", "gt", "gte", "eq", "lt", "lte", "ne"]
|
|
528
|
+
condition = params.get("condition")
|
|
529
|
+
if condition is not None and condition not in conditions:
|
|
530
|
+
raise _p(f'{json.dumps(condition, default=repr)} is invalid in "condition". allowed types or values are: ' + ", ".join(json.dumps(c) for c in conditions) + ".")
|
|
531
|
+
if condition is None:
|
|
532
|
+
condition = ">" if value == " " or not value else "="
|
|
533
|
+
body: Dict[str, Any] = {"searchFor": search_for, "value": value}
|
|
534
|
+
if "range" in params and params["range"] is not None:
|
|
535
|
+
body["range"] = params["range"]
|
|
536
|
+
condition = None
|
|
537
|
+
if search_for == "number_of_users" and (isinstance(value, bool) or not isinstance(value, (int, float))):
|
|
538
|
+
raise _p('"value" must be a number.')
|
|
539
|
+
if search_for == "group" and not isinstance(value, str):
|
|
540
|
+
raise _p('"value" must be a string.')
|
|
541
|
+
if "range" in body and type(body["range"]) is not type(value):
|
|
542
|
+
raise _p(f'"range" must be a {"number" if isinstance(value, (int, float)) else "string"}.')
|
|
543
|
+
if condition:
|
|
544
|
+
body["condition"] = condition
|
|
545
|
+
res = self._call("get-ws-group", body, auth=True, fetch_options=fetch_options)
|
|
546
|
+
if isinstance(res, dict) and isinstance(res.get("list"), list):
|
|
547
|
+
res["list"] = [{"group": str(i.get("rid", "")).split("#")[1] if "#" in str(i.get("rid", "")) else i.get("rid"),
|
|
548
|
+
"number_of_users": i.get("cnt")} for i in res["list"]]
|
|
549
|
+
return res
|