streamcom-scoreboard-client 2.0.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.
- streamcom_scoreboard/__init__.py +57 -0
- streamcom_scoreboard/_core.py +456 -0
- streamcom_scoreboard/_delay.py +67 -0
- streamcom_scoreboard/_time.py +18 -0
- streamcom_scoreboard/_version.py +1 -0
- streamcom_scoreboard/aio.py +173 -0
- streamcom_scoreboard/backoff.py +32 -0
- streamcom_scoreboard/board.py +635 -0
- streamcom_scoreboard/client.py +482 -0
- streamcom_scoreboard/clock.py +151 -0
- streamcom_scoreboard/errors.py +130 -0
- streamcom_scoreboard/py.typed +0 -0
- streamcom_scoreboard/stream.py +694 -0
- streamcom_scoreboard/stream_errors.py +109 -0
- streamcom_scoreboard/types.py +290 -0
- streamcom_scoreboard_client-2.0.0.dist-info/METADATA +237 -0
- streamcom_scoreboard_client-2.0.0.dist-info/RECORD +19 -0
- streamcom_scoreboard_client-2.0.0.dist-info/WHEEL +4 -0
- streamcom_scoreboard_client-2.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Live data from Streamcom: matches, competitions, clubs and courts on public API v2, with
|
|
2
|
+
clocks resolved for you, and the live stream that follows them."""
|
|
3
|
+
|
|
4
|
+
from ._core import Follow
|
|
5
|
+
from ._time import format_time, parse_time
|
|
6
|
+
from ._version import __version__
|
|
7
|
+
from .aio import AsyncStreamcomClient
|
|
8
|
+
from .backoff import Backoff
|
|
9
|
+
from .board import ABSENT, CourtChange, CourtFields, Declarable, Exclusion, Period, TeamFields
|
|
10
|
+
from .client import (
|
|
11
|
+
DEFAULT_API_URL,
|
|
12
|
+
ClubsApi,
|
|
13
|
+
CompetitionsApi,
|
|
14
|
+
CourtsApi,
|
|
15
|
+
MatchesApi,
|
|
16
|
+
MatchSync,
|
|
17
|
+
StreamcomClient,
|
|
18
|
+
)
|
|
19
|
+
from .clock import Clock, ClockReading, format_clock_text
|
|
20
|
+
from .errors import ApiError, ApiErrorCode
|
|
21
|
+
from .stream import MAX_DELAY, SILENCE, EventType, LiveStream, StreamEvent
|
|
22
|
+
from .stream_errors import StreamError, StreamErrorCode
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"ABSENT",
|
|
26
|
+
"DEFAULT_API_URL",
|
|
27
|
+
"MAX_DELAY",
|
|
28
|
+
"SILENCE",
|
|
29
|
+
"ApiError",
|
|
30
|
+
"ApiErrorCode",
|
|
31
|
+
"AsyncStreamcomClient",
|
|
32
|
+
"Backoff",
|
|
33
|
+
"Clock",
|
|
34
|
+
"ClockReading",
|
|
35
|
+
"ClubsApi",
|
|
36
|
+
"CompetitionsApi",
|
|
37
|
+
"CourtChange",
|
|
38
|
+
"CourtFields",
|
|
39
|
+
"CourtsApi",
|
|
40
|
+
"Declarable",
|
|
41
|
+
"EventType",
|
|
42
|
+
"Exclusion",
|
|
43
|
+
"Follow",
|
|
44
|
+
"LiveStream",
|
|
45
|
+
"MatchSync",
|
|
46
|
+
"MatchesApi",
|
|
47
|
+
"Period",
|
|
48
|
+
"StreamError",
|
|
49
|
+
"StreamErrorCode",
|
|
50
|
+
"StreamEvent",
|
|
51
|
+
"StreamcomClient",
|
|
52
|
+
"TeamFields",
|
|
53
|
+
"__version__",
|
|
54
|
+
"format_clock_text",
|
|
55
|
+
"format_time",
|
|
56
|
+
"parse_time",
|
|
57
|
+
]
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
"""Following public API v2's stream without the socket: frames in, events out.
|
|
2
|
+
|
|
3
|
+
The npm package's ``followStream`` and the Java SDK's ``StreamCore``, rule for rule, held to
|
|
4
|
+
``sdks/cases/stream.json``:
|
|
5
|
+
|
|
6
|
+
1. The board is v1's, so the board rules are v1's: one :class:`CourtState` per court, and a
|
|
7
|
+
sequence gap is answered with ``resync``.
|
|
8
|
+
2. A reconnect is a new subscription: the server holds nothing for a closed connection, so every
|
|
9
|
+
(re)connect sends what is followed again.
|
|
10
|
+
3. ``live`` and ``ended`` are transitions this stream saw, never the state it joined in.
|
|
11
|
+
|
|
12
|
+
The state is guarded by a lock: frames arrive on the stream's thread, reads come from anywhere.
|
|
13
|
+
Events are handed out once the lock is let go, so a handler may block, subscribe or read without
|
|
14
|
+
holding up the stream.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import threading
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from datetime import datetime
|
|
23
|
+
from typing import Any, Callable, Iterable, Optional, Protocol
|
|
24
|
+
|
|
25
|
+
from .board import CourtChange, CourtFields, CourtState
|
|
26
|
+
from .clock import epoch_ms
|
|
27
|
+
from .stream_errors import GoneKind, StreamError, refusal_error, unreadable_error
|
|
28
|
+
from .types import Match, StreamLimits
|
|
29
|
+
|
|
30
|
+
PER_MESSAGE = 500
|
|
31
|
+
"""At most this many ids per list in one ``subscribe`` (the API's limit)."""
|
|
32
|
+
|
|
33
|
+
_TYPES = frozenset(
|
|
34
|
+
{"welcome", "court-snapshot", "court-update", "court-clock", "court-status", "match", "gone",
|
|
35
|
+
"ping"}
|
|
36
|
+
)
|
|
37
|
+
_LISTS: dict[GoneKind, str] = {"court": "courts", "match": "matches", "competition": "competitions"}
|
|
38
|
+
_KINDS: tuple[GoneKind, ...] = ("court", "match", "competition")
|
|
39
|
+
_FOLLOWED = frozenset({"starting", "live"})
|
|
40
|
+
_LIMIT_KEYS = (
|
|
41
|
+
"streams_per_key",
|
|
42
|
+
"dials_per_minute",
|
|
43
|
+
"max_queued",
|
|
44
|
+
"subscribe_max",
|
|
45
|
+
"messages_burst",
|
|
46
|
+
"max_message_bytes",
|
|
47
|
+
"ping_interval_ms",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Follow:
|
|
53
|
+
"""What a stream follows, by id: courts, matches and competitions.
|
|
54
|
+
|
|
55
|
+
- a **match**: the match at once and on every change; from ``starting`` until it ends, its
|
|
56
|
+
court's board;
|
|
57
|
+
- a **competition**: the same for every match in it, the whole season first, then changes;
|
|
58
|
+
- a **court**: its board, always, and the match it plays from ``starting`` until it ends,
|
|
59
|
+
let go after with ``gone``.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
courts: tuple[str, ...] = ()
|
|
63
|
+
matches: tuple[str, ...] = ()
|
|
64
|
+
competitions: tuple[str, ...] = ()
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def of(
|
|
68
|
+
cls,
|
|
69
|
+
courts: Optional[Iterable[str]] = None,
|
|
70
|
+
matches: Optional[Iterable[str]] = None,
|
|
71
|
+
competitions: Optional[Iterable[str]] = None,
|
|
72
|
+
) -> Follow:
|
|
73
|
+
"""Ids as they travel: trimmed, blank ones left out, each once. A bare string is one id."""
|
|
74
|
+
return cls(_clean(courts), _clean(matches), _clean(competitions))
|
|
75
|
+
|
|
76
|
+
def and_(self, other: Follow) -> Follow:
|
|
77
|
+
"""This and ``other`` together."""
|
|
78
|
+
return Follow.of(
|
|
79
|
+
self.courts + other.courts,
|
|
80
|
+
self.matches + other.matches,
|
|
81
|
+
self.competitions + other.competitions,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def ids(self, kind: GoneKind) -> tuple[str, ...]:
|
|
85
|
+
return {"court": self.courts, "match": self.matches, "competition": self.competitions}[kind]
|
|
86
|
+
|
|
87
|
+
def __bool__(self) -> bool:
|
|
88
|
+
return bool(self.courts or self.matches or self.competitions)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _clean(ids: Optional[Iterable[str]]) -> tuple[str, ...]:
|
|
92
|
+
if ids is None:
|
|
93
|
+
return ()
|
|
94
|
+
if isinstance(ids, str):
|
|
95
|
+
ids = [ids]
|
|
96
|
+
out: dict[str, None] = {}
|
|
97
|
+
for value in ids:
|
|
98
|
+
if isinstance(value, str) and value.strip():
|
|
99
|
+
out[value.strip()] = None
|
|
100
|
+
return tuple(out)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Events(Protocol):
|
|
104
|
+
def match(self, match: Match, previous: Optional[Match]) -> None: ...
|
|
105
|
+
def status(self, match: Match, previous_status: str) -> None: ...
|
|
106
|
+
def live(self, match: Match) -> None: ...
|
|
107
|
+
def ended(self, match: Match) -> None: ...
|
|
108
|
+
def gone(self, kind: GoneKind, id: str) -> None: ...
|
|
109
|
+
def board(self, court_id: str, fields: CourtFields, change: CourtChange) -> None: ...
|
|
110
|
+
def connection(self, connected: bool, reason: Optional[str]) -> None: ...
|
|
111
|
+
def error(self, error: StreamError) -> None: ...
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass(frozen=True)
|
|
115
|
+
class Refusal:
|
|
116
|
+
"""The server refused the upgrade: its status and its ``Retry-After`` in ms, if any."""
|
|
117
|
+
|
|
118
|
+
status: int
|
|
119
|
+
retry_after_ms: Optional[int]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def closed_because(code: Optional[int]) -> str:
|
|
123
|
+
""""stream closed", with the server's close code when it sent one: 1005 is no code given and
|
|
124
|
+
1006 a connection that dropped, and neither is the server's reason."""
|
|
125
|
+
return "stream closed" if code in (None, 1005, 1006) else f"stream closed ({code})"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _lists() -> dict[GoneKind, dict[str, None]]:
|
|
129
|
+
# Dicts as ordered sets: frames list ids in the order they were followed.
|
|
130
|
+
return {kind: {} for kind in _KINDS}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class StreamCore:
|
|
134
|
+
def __init__(
|
|
135
|
+
self,
|
|
136
|
+
follow: Follow,
|
|
137
|
+
send: Callable[[str], bool],
|
|
138
|
+
now_ms: Callable[[], int],
|
|
139
|
+
events: Events,
|
|
140
|
+
) -> None:
|
|
141
|
+
self._send = send
|
|
142
|
+
self._now = now_ms
|
|
143
|
+
self._target = events
|
|
144
|
+
self._lock = threading.RLock()
|
|
145
|
+
self._due: list[Callable[[], None]] = []
|
|
146
|
+
self._wanted = _lists()
|
|
147
|
+
self._heard = _lists()
|
|
148
|
+
self._refused = _lists()
|
|
149
|
+
for kind in _KINDS:
|
|
150
|
+
self._wanted[kind].update(dict.fromkeys(follow.ids(kind)))
|
|
151
|
+
self._held: dict[str, Match] = {}
|
|
152
|
+
self._boards: dict[str, CourtState] = {}
|
|
153
|
+
self._playing: dict[str, Optional[str]] = {}
|
|
154
|
+
self._connected = False
|
|
155
|
+
self._connection_id: Optional[str] = None
|
|
156
|
+
self._limits: Optional[StreamLimits] = None
|
|
157
|
+
self._offset_ms = 0
|
|
158
|
+
self._last_heard = now_ms()
|
|
159
|
+
|
|
160
|
+
# ── Handing out events ───────────────────────────────────────────────────────────────────
|
|
161
|
+
|
|
162
|
+
def _deliver(self, locked: Callable[[], None]) -> None:
|
|
163
|
+
"""Run ``locked`` under the lock, then hand out what it raised with the lock let go.
|
|
164
|
+
Only the stream's own thread calls this, so events keep their order."""
|
|
165
|
+
with self._lock:
|
|
166
|
+
locked()
|
|
167
|
+
out, self._due = self._due, []
|
|
168
|
+
for event in out:
|
|
169
|
+
event()
|
|
170
|
+
|
|
171
|
+
def _emit(self, name: str, *args: Any) -> None:
|
|
172
|
+
handler = getattr(self._target, name)
|
|
173
|
+
self._due.append(lambda: handler(*args))
|
|
174
|
+
|
|
175
|
+
# ── The connection ───────────────────────────────────────────────────────────────────────
|
|
176
|
+
|
|
177
|
+
def opened(self) -> None:
|
|
178
|
+
self._deliver(self._opened)
|
|
179
|
+
|
|
180
|
+
def _opened(self) -> None:
|
|
181
|
+
self._connected = True
|
|
182
|
+
self._last_heard = self._now()
|
|
183
|
+
# The server holds nothing for a connection that closed: say everything again.
|
|
184
|
+
for frame in _frames("subscribe", self._wanted):
|
|
185
|
+
self._send(frame)
|
|
186
|
+
self._emit("connection", True, None)
|
|
187
|
+
|
|
188
|
+
def down(self, reason: str, retry_in_ms: int, refusal: Optional[Refusal]) -> None:
|
|
189
|
+
def locked() -> None:
|
|
190
|
+
self._connected = False
|
|
191
|
+
# The id was that connection's; the next one says its own.
|
|
192
|
+
self._connection_id = None
|
|
193
|
+
error = (
|
|
194
|
+
None
|
|
195
|
+
if refusal is None
|
|
196
|
+
else refusal_error(refusal.status, retry_in_ms, "The StreamCom API")
|
|
197
|
+
)
|
|
198
|
+
self._emit("connection", False, str(error) if error else reason)
|
|
199
|
+
if error is not None:
|
|
200
|
+
self._emit("error", error)
|
|
201
|
+
|
|
202
|
+
self._deliver(locked)
|
|
203
|
+
|
|
204
|
+
def closed(self) -> None:
|
|
205
|
+
"""The stream was closed by its owner."""
|
|
206
|
+
|
|
207
|
+
def locked() -> None:
|
|
208
|
+
if not self._connected:
|
|
209
|
+
return
|
|
210
|
+
self._connected = False
|
|
211
|
+
self._emit("connection", False, "closed")
|
|
212
|
+
|
|
213
|
+
self._deliver(locked)
|
|
214
|
+
|
|
215
|
+
@property
|
|
216
|
+
def connected(self) -> bool:
|
|
217
|
+
return self._connected
|
|
218
|
+
|
|
219
|
+
@property
|
|
220
|
+
def connection_id(self) -> Optional[str]:
|
|
221
|
+
return self._connection_id
|
|
222
|
+
|
|
223
|
+
@property
|
|
224
|
+
def limits(self) -> Optional[StreamLimits]:
|
|
225
|
+
return self._limits
|
|
226
|
+
|
|
227
|
+
@property
|
|
228
|
+
def last_heard(self) -> int:
|
|
229
|
+
return self._last_heard
|
|
230
|
+
|
|
231
|
+
# ── Frames in ────────────────────────────────────────────────────────────────────────────
|
|
232
|
+
|
|
233
|
+
def message(self, raw: str) -> None:
|
|
234
|
+
"""One frame of the stream. One this version does not know is skipped, never fatal."""
|
|
235
|
+
self._deliver(lambda: self._message(raw))
|
|
236
|
+
|
|
237
|
+
def _message(self, raw: str) -> None:
|
|
238
|
+
received_at = self._now()
|
|
239
|
+
self._last_heard = received_at
|
|
240
|
+
try:
|
|
241
|
+
message = json.loads(raw)
|
|
242
|
+
except ValueError:
|
|
243
|
+
return
|
|
244
|
+
if not isinstance(message, dict) or message.get("type") not in _TYPES:
|
|
245
|
+
return
|
|
246
|
+
self._receive(message, received_at)
|
|
247
|
+
|
|
248
|
+
def _receive(self, message: dict[str, Any], received_at: int) -> None:
|
|
249
|
+
if "server_time" in message:
|
|
250
|
+
stamp = _ms(message["server_time"])
|
|
251
|
+
# A stamp that will not parse says nothing about the clock.
|
|
252
|
+
if stamp is not None:
|
|
253
|
+
self._offset_ms = stamp - received_at
|
|
254
|
+
kind = message["type"]
|
|
255
|
+
if kind == "welcome":
|
|
256
|
+
connection_id = message.get("connection_id")
|
|
257
|
+
self._connection_id = connection_id if isinstance(connection_id, str) else None
|
|
258
|
+
self._limits = _limits(message.get("limits"), self._limits)
|
|
259
|
+
return
|
|
260
|
+
if kind == "match":
|
|
261
|
+
self._receive_match(message.get("match"))
|
|
262
|
+
return
|
|
263
|
+
if kind == "gone":
|
|
264
|
+
gone = message.get("kind")
|
|
265
|
+
# A kind added after this version names nothing this stream holds: skipped.
|
|
266
|
+
if gone in _LISTS and isinstance(message.get("id"), str):
|
|
267
|
+
self._receive_gone(gone, message["id"])
|
|
268
|
+
return
|
|
269
|
+
if kind == "ping":
|
|
270
|
+
return
|
|
271
|
+
|
|
272
|
+
# The board: v1's messages, one CourtState per court.
|
|
273
|
+
court_id = message.get("court_id")
|
|
274
|
+
if not isinstance(court_id, str):
|
|
275
|
+
return
|
|
276
|
+
state = self._boards.get(court_id)
|
|
277
|
+
if state is None:
|
|
278
|
+
# A board starts with a snapshot; an update carries the whole document too. A clock
|
|
279
|
+
# or a status for a court with nothing held has nothing to land on.
|
|
280
|
+
if kind not in ("court-snapshot", "court-update"):
|
|
281
|
+
return
|
|
282
|
+
state = CourtState(court_id)
|
|
283
|
+
self._boards[court_id] = state
|
|
284
|
+
self._heard["court"][court_id] = None
|
|
285
|
+
# Which match the court is playing: on a snapshot, and on every update and clock too.
|
|
286
|
+
if kind == "court-snapshot" or "match_id" in message:
|
|
287
|
+
match_id = message.get("match_id")
|
|
288
|
+
self._playing[court_id] = match_id if isinstance(match_id, str) else None
|
|
289
|
+
# A snapshot replaces everything held, so only an update can reveal a gap.
|
|
290
|
+
gap = kind == "court-update" and state.is_gap(int(message.get("sequence", -1)))
|
|
291
|
+
change = state.apply(message)
|
|
292
|
+
if gap:
|
|
293
|
+
self._send(json.dumps({"type": "resync", "court_id": court_id}, separators=(",", ":")))
|
|
294
|
+
if change is None:
|
|
295
|
+
return
|
|
296
|
+
fields = state.read(self._offset_ms, self._now(), self._connected)
|
|
297
|
+
if fields is not None:
|
|
298
|
+
self._emit("board", court_id, fields, change)
|
|
299
|
+
|
|
300
|
+
def _receive_match(self, match: Any) -> None:
|
|
301
|
+
if not isinstance(match, dict) or not isinstance(match.get("id"), str):
|
|
302
|
+
return
|
|
303
|
+
previous = self._held.get(match["id"])
|
|
304
|
+
competition = match.get("competition")
|
|
305
|
+
if isinstance(competition, dict) and isinstance(competition.get("id"), str):
|
|
306
|
+
self._heard["competition"][competition["id"]] = None
|
|
307
|
+
self._heard["match"][match["id"]] = None
|
|
308
|
+
if previous is not None and previous == match:
|
|
309
|
+
return
|
|
310
|
+
self._held[match["id"]] = match # type: ignore[assignment]
|
|
311
|
+
self._emit("match", match, previous)
|
|
312
|
+
if previous is None or previous.get("status") == match.get("status"):
|
|
313
|
+
return
|
|
314
|
+
self._emit("status", match, previous.get("status"))
|
|
315
|
+
if match.get("status") == "live":
|
|
316
|
+
self._emit("live", match)
|
|
317
|
+
if match.get("status") == "ended":
|
|
318
|
+
self._emit("ended", match)
|
|
319
|
+
|
|
320
|
+
def _receive_gone(self, kind: GoneKind, id: str) -> None:
|
|
321
|
+
if id in self._wanted[kind] and id not in self._heard[kind] and id not in self._refused[kind]:
|
|
322
|
+
self._refused[kind][id] = None
|
|
323
|
+
self._emit("error", unreadable_error(kind, id))
|
|
324
|
+
if kind == "court":
|
|
325
|
+
self._boards.pop(id, None)
|
|
326
|
+
self._playing.pop(id, None)
|
|
327
|
+
if kind == "match":
|
|
328
|
+
self._held.pop(id, None)
|
|
329
|
+
self._emit("gone", kind, id)
|
|
330
|
+
|
|
331
|
+
# ── What is followed ─────────────────────────────────────────────────────────────────────
|
|
332
|
+
|
|
333
|
+
def subscribe(self, what: Follow) -> None:
|
|
334
|
+
self._deliver(lambda: self._change("subscribe", what))
|
|
335
|
+
|
|
336
|
+
def unsubscribe(self, what: Follow) -> None:
|
|
337
|
+
self._deliver(lambda: self._change("unsubscribe", what))
|
|
338
|
+
|
|
339
|
+
@property
|
|
340
|
+
def subscription(self) -> Follow:
|
|
341
|
+
with self._lock:
|
|
342
|
+
return Follow(*(tuple(self._wanted[kind]) for kind in _KINDS))
|
|
343
|
+
|
|
344
|
+
def _change(self, kind: str, what: Follow) -> None:
|
|
345
|
+
subscribing = kind == "subscribe"
|
|
346
|
+
delta = _lists()
|
|
347
|
+
for gone_kind in _KINDS:
|
|
348
|
+
for id in what.ids(gone_kind):
|
|
349
|
+
if subscribing == (id in self._wanted[gone_kind]):
|
|
350
|
+
continue
|
|
351
|
+
delta[gone_kind][id] = None
|
|
352
|
+
if subscribing:
|
|
353
|
+
self._wanted[gone_kind][id] = None
|
|
354
|
+
else:
|
|
355
|
+
self._wanted[gone_kind].pop(id, None)
|
|
356
|
+
self._refused[gone_kind].pop(id, None)
|
|
357
|
+
if not any(delta.values()):
|
|
358
|
+
return
|
|
359
|
+
if not subscribing:
|
|
360
|
+
self._forget(delta)
|
|
361
|
+
if self._connected:
|
|
362
|
+
for frame in _frames(kind, delta):
|
|
363
|
+
self._send(frame)
|
|
364
|
+
|
|
365
|
+
def _forget(self, dropped: dict[GoneKind, dict[str, None]]) -> None:
|
|
366
|
+
"""Drop what only the unsubscribed lists brought, without telling anybody."""
|
|
367
|
+
for id, match in list(self._held.items()):
|
|
368
|
+
competition = _competition_id(match)
|
|
369
|
+
by_competition = competition is not None and competition in self._wanted["competition"]
|
|
370
|
+
named = id in self._wanted["match"]
|
|
371
|
+
dropped_here = id in dropped["match"] or (
|
|
372
|
+
competition is not None and competition in dropped["competition"]
|
|
373
|
+
)
|
|
374
|
+
if dropped_here and not named and not by_competition:
|
|
375
|
+
del self._held[id]
|
|
376
|
+
for court_id in dropped["court"]:
|
|
377
|
+
# The server keeps feeding a court a followed match is being played on.
|
|
378
|
+
still_followed = any(
|
|
379
|
+
_court_id(match) == court_id and match.get("status") in _FOLLOWED
|
|
380
|
+
for match in self._held.values()
|
|
381
|
+
)
|
|
382
|
+
if not still_followed:
|
|
383
|
+
self._boards.pop(court_id, None)
|
|
384
|
+
self._playing.pop(court_id, None)
|
|
385
|
+
|
|
386
|
+
# ── Reads ────────────────────────────────────────────────────────────────────────────────
|
|
387
|
+
|
|
388
|
+
def match(self, id: str) -> Optional[Match]:
|
|
389
|
+
with self._lock:
|
|
390
|
+
return self._held.get(id)
|
|
391
|
+
|
|
392
|
+
def matches(self) -> list[Match]:
|
|
393
|
+
with self._lock:
|
|
394
|
+
return list(self._held.values())
|
|
395
|
+
|
|
396
|
+
def board(self, court_id: str, now_ms: int) -> Optional[CourtFields]:
|
|
397
|
+
with self._lock:
|
|
398
|
+
state = self._boards.get(court_id)
|
|
399
|
+
return None if state is None else state.read(self._offset_ms, now_ms, self._connected)
|
|
400
|
+
|
|
401
|
+
def board_of(self, match_id: str, now_ms: int) -> Optional[CourtFields]:
|
|
402
|
+
with self._lock:
|
|
403
|
+
match = self._held.get(match_id)
|
|
404
|
+
court_id = _court_id(match) if match else None
|
|
405
|
+
return None if court_id is None else self.board(court_id, now_ms)
|
|
406
|
+
|
|
407
|
+
def match_on(self, court_id: str) -> Optional[Match]:
|
|
408
|
+
with self._lock:
|
|
409
|
+
id = self._playing.get(court_id)
|
|
410
|
+
return None if id is None else self._held.get(id)
|
|
411
|
+
|
|
412
|
+
def courts(self) -> list[str]:
|
|
413
|
+
with self._lock:
|
|
414
|
+
return list(self._boards)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _frames(kind: str, what: dict[GoneKind, dict[str, None]]) -> list[str]:
|
|
418
|
+
"""``subscribe`` / ``unsubscribe`` frames for these lists, at most 500 ids per list each."""
|
|
419
|
+
lists = [(_LISTS[gone], list(what[gone])) for gone in _KINDS]
|
|
420
|
+
longest = max(len(ids) for _, ids in lists)
|
|
421
|
+
out = []
|
|
422
|
+
for at in range(0, longest, PER_MESSAGE):
|
|
423
|
+
message: dict[str, Any] = {"type": kind}
|
|
424
|
+
for name, ids in lists:
|
|
425
|
+
if len(ids) > at:
|
|
426
|
+
message[name] = ids[at : at + PER_MESSAGE]
|
|
427
|
+
out.append(json.dumps(message, separators=(",", ":")))
|
|
428
|
+
return out
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _limits(raw: Any, held: Optional[StreamLimits]) -> Optional[StreamLimits]:
|
|
432
|
+
"""Limits that will not read keep what the last welcome said."""
|
|
433
|
+
if not isinstance(raw, dict):
|
|
434
|
+
return held
|
|
435
|
+
if not all(isinstance(raw.get(key), int) for key in _LIMIT_KEYS):
|
|
436
|
+
return held
|
|
437
|
+
return {key: raw[key] for key in _LIMIT_KEYS} # type: ignore[return-value]
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _competition_id(match: Match) -> Optional[str]:
|
|
441
|
+
competition = match.get("competition")
|
|
442
|
+
return competition.get("id") if isinstance(competition, dict) else None
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _court_id(match: Match) -> Optional[str]:
|
|
446
|
+
court = match.get("court")
|
|
447
|
+
return court.get("id") if isinstance(court, dict) else None
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _ms(value: Any) -> Optional[int]:
|
|
451
|
+
if not isinstance(value, str):
|
|
452
|
+
return None
|
|
453
|
+
try:
|
|
454
|
+
return epoch_ms(datetime.fromisoformat(value))
|
|
455
|
+
except ValueError:
|
|
456
|
+
return None
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""The steps of the shown view, each held until the picture reaches the moment it arrived. The
|
|
2
|
+
npm package's ``DelayLine``, with the same cases (``sdks/cases/delay.json``)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections import deque
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from typing import Generic, Optional, TypeVar
|
|
9
|
+
|
|
10
|
+
T = TypeVar("T")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class DelayLine(Generic[T]):
|
|
14
|
+
"""Pure: every call takes the time, in epoch ms. The stream pushes every step it took on the
|
|
15
|
+
wire (an open, a frame, a drop, a subscription change) and plays what :meth:`take` hands back
|
|
16
|
+
into the shown copy of its state, at the moment that step arrived. With no delay a step is due
|
|
17
|
+
the moment it is pushed."""
|
|
18
|
+
|
|
19
|
+
def __init__(self) -> None:
|
|
20
|
+
self._steps: deque[tuple[T, int]] = deque()
|
|
21
|
+
self._delay = 0
|
|
22
|
+
# When the last step shown arrived: what the shown state is the hall at.
|
|
23
|
+
self._shown_at: Optional[int] = None
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def delay_ms(self) -> int:
|
|
27
|
+
"""How far the view runs behind the hall, in ms."""
|
|
28
|
+
return self._delay
|
|
29
|
+
|
|
30
|
+
def align(self, picture_at_ms: int, now_ms: int, max_delay_ms: int) -> int:
|
|
31
|
+
"""The picture on screen was taken at ``picture_at_ms``: the delay becomes now minus that,
|
|
32
|
+
and a moment in the future is no delay. Returns the delay."""
|
|
33
|
+
delay = now_ms - picture_at_ms
|
|
34
|
+
if delay > max_delay_ms:
|
|
35
|
+
moment = datetime.fromtimestamp(picture_at_ms / 1000, timezone.utc).isoformat()
|
|
36
|
+
raise ValueError(
|
|
37
|
+
f"LiveStream.align_to: {moment} is {delay / 1000:.0f} s ago, more than max_delay "
|
|
38
|
+
f"({max_delay_ms / 1000:.0f} s). Is it UTC?"
|
|
39
|
+
)
|
|
40
|
+
self._delay = max(0, delay)
|
|
41
|
+
return self._delay
|
|
42
|
+
|
|
43
|
+
def push(self, step: T, now_ms: int) -> None:
|
|
44
|
+
self._steps.append((step, now_ms))
|
|
45
|
+
|
|
46
|
+
def take(self, now_ms: int) -> Optional[tuple[T, int]]:
|
|
47
|
+
"""The next step whose moment the picture has reached, with when it arrived, or ``None``."""
|
|
48
|
+
if not self._steps or self._steps[0][1] + self._delay > now_ms:
|
|
49
|
+
return None
|
|
50
|
+
head = self._steps.popleft()
|
|
51
|
+
self._shown_at = head[1]
|
|
52
|
+
return head
|
|
53
|
+
|
|
54
|
+
def next_in_ms(self, now_ms: int) -> Optional[int]:
|
|
55
|
+
"""In how many ms the next step is due, or ``None`` when nothing waits."""
|
|
56
|
+
if not self._steps:
|
|
57
|
+
return None
|
|
58
|
+
return max(0, self._steps[0][1] + self._delay - now_ms)
|
|
59
|
+
|
|
60
|
+
def view_ms(self, now_ms: int) -> int:
|
|
61
|
+
"""The moment the shown view reads its clocks at: the picture's, but never before the last
|
|
62
|
+
step shown, so a delay that grows holds the clocks still instead of walking them back."""
|
|
63
|
+
view = now_ms - self._delay
|
|
64
|
+
return view if self._shown_at is None else max(view, self._shown_at)
|
|
65
|
+
|
|
66
|
+
def clear(self) -> None:
|
|
67
|
+
self._steps.clear()
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def parse_time(value: str) -> datetime:
|
|
7
|
+
"""An API timestamp (ISO-8601 with an offset) as a timezone-aware ``datetime``."""
|
|
8
|
+
return datetime.fromisoformat(value)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def format_time(value: datetime) -> str:
|
|
12
|
+
"""As the API and every other SDK write a moment: UTC, always milliseconds, always ``Z``."""
|
|
13
|
+
if value.tzinfo is None:
|
|
14
|
+
raise ValueError(
|
|
15
|
+
"a moment to filter on must be timezone-aware, e.g. datetime.now(timezone.utc)"
|
|
16
|
+
)
|
|
17
|
+
utc = value.astimezone(timezone.utc)
|
|
18
|
+
return utc.strftime("%Y-%m-%dT%H:%M:%S.") + f"{utc.microsecond // 1000:03d}Z"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.0.0"
|