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,482 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import http.client
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import platform
|
|
7
|
+
import re
|
|
8
|
+
import ssl
|
|
9
|
+
import time
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from datetime import datetime, timedelta, timezone
|
|
15
|
+
# `List` where a class defines a method named `list`, which shadows the builtin there.
|
|
16
|
+
from typing import Any, Callable, Iterable, Iterator, List, Optional, TypeVar, Union, cast
|
|
17
|
+
|
|
18
|
+
from . import errors
|
|
19
|
+
from ._core import Follow
|
|
20
|
+
from .backoff import Backoff
|
|
21
|
+
from .stream import MAX_DELAY, SILENCE, LiveStream
|
|
22
|
+
from ._time import format_time, parse_time
|
|
23
|
+
from ._version import __version__
|
|
24
|
+
from .types import (
|
|
25
|
+
Club,
|
|
26
|
+
Competition,
|
|
27
|
+
CompetitionDetail,
|
|
28
|
+
Court,
|
|
29
|
+
CourtSnapshot,
|
|
30
|
+
Match,
|
|
31
|
+
MatchPage,
|
|
32
|
+
Timeline,
|
|
33
|
+
TimelineEvent,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
DEFAULT_API_URL = "https://api.streamcom.eu"
|
|
37
|
+
|
|
38
|
+
_log = logging.getLogger("streamcom_scoreboard")
|
|
39
|
+
|
|
40
|
+
T = TypeVar("T")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _NoRedirects(urllib.request.HTTPRedirectHandler):
|
|
44
|
+
"""Follow no redirect, so the key goes nowhere but the API."""
|
|
45
|
+
|
|
46
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _Transport:
|
|
51
|
+
"""GETs against the API, with the key in a header and never in a URL. Nothing is cached.
|
|
52
|
+
|
|
53
|
+
A request that got no answer, a 5xx and a 429 are tried again up to ``retries`` times: on
|
|
54
|
+
``backoff``, or after the 429's ``Retry-After`` when it says so and that is at most
|
|
55
|
+
``max_retry_wait`` seconds. Every route here is a read, so a repeat changes nothing.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
token: str,
|
|
61
|
+
base: str,
|
|
62
|
+
timeout: float,
|
|
63
|
+
retries: int,
|
|
64
|
+
backoff: Backoff,
|
|
65
|
+
max_retry_wait: float,
|
|
66
|
+
ssl_context: Optional[ssl.SSLContext],
|
|
67
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
68
|
+
) -> None:
|
|
69
|
+
self.token = token
|
|
70
|
+
self.base = base
|
|
71
|
+
self.timeout = timeout
|
|
72
|
+
self.ssl_context = ssl_context
|
|
73
|
+
self._retries = retries
|
|
74
|
+
self._backoff = backoff
|
|
75
|
+
self._max_retry_wait = max_retry_wait
|
|
76
|
+
self._sleep = sleep
|
|
77
|
+
handlers: list[urllib.request.BaseHandler] = [_NoRedirects()]
|
|
78
|
+
if ssl_context is not None:
|
|
79
|
+
handlers.append(urllib.request.HTTPSHandler(context=ssl_context))
|
|
80
|
+
self._opener = urllib.request.build_opener(*handlers)
|
|
81
|
+
self.agent = (
|
|
82
|
+
f"streamcom-scoreboard-client-python/{__version__} "
|
|
83
|
+
f"(Python {platform.python_version()})"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def get(self, path: str, query: Optional[dict[str, Any]] = None) -> Any:
|
|
87
|
+
"""A route under ``/api/v2``, its JSON answer."""
|
|
88
|
+
route = "/api/v2" + path
|
|
89
|
+
values = {k: v for k, v in (query or {}).items() if v is not None}
|
|
90
|
+
url = self.base + route + ("?" + urllib.parse.urlencode(values) if values else "")
|
|
91
|
+
status, raw, _ = self.fetch(url, route, "application/json", with_key=True)
|
|
92
|
+
try:
|
|
93
|
+
body = json.loads(raw) if raw else None
|
|
94
|
+
except ValueError:
|
|
95
|
+
body = None
|
|
96
|
+
if body is None:
|
|
97
|
+
raise errors.network(f"GET {route}: the answer was not JSON.", status)
|
|
98
|
+
return body
|
|
99
|
+
|
|
100
|
+
def fetch(self, url: str, label: str, accept: str, with_key: bool) -> tuple[int, bytes, Any]:
|
|
101
|
+
"""A 2xx answer to a GET, tried again as the class says; otherwise an ApiError."""
|
|
102
|
+
attempt = 0
|
|
103
|
+
while True:
|
|
104
|
+
try:
|
|
105
|
+
return self._once(url, label, accept, with_key)
|
|
106
|
+
except errors.ApiError as e:
|
|
107
|
+
wait = self._retry_in(e, attempt)
|
|
108
|
+
if wait is None:
|
|
109
|
+
raise
|
|
110
|
+
_log.info("%s; trying again in %.1f s", e, wait)
|
|
111
|
+
self._sleep(wait)
|
|
112
|
+
attempt += 1
|
|
113
|
+
|
|
114
|
+
def _retry_in(self, error: errors.ApiError, attempt: int) -> Optional[float]:
|
|
115
|
+
if attempt >= self._retries:
|
|
116
|
+
return None
|
|
117
|
+
retriable = (
|
|
118
|
+
(error.code == errors.ApiErrorCode.NETWORK and error.status is None)
|
|
119
|
+
or error.code == errors.ApiErrorCode.RATE_LIMITED
|
|
120
|
+
or (error.status is not None and error.status >= 500)
|
|
121
|
+
)
|
|
122
|
+
if not retriable:
|
|
123
|
+
return None
|
|
124
|
+
wait = self._backoff.delay_ms(attempt) / 1000
|
|
125
|
+
if error.retry_after_ms is not None:
|
|
126
|
+
if error.retry_after_ms / 1000 > self._max_retry_wait:
|
|
127
|
+
return None
|
|
128
|
+
wait = max(wait, error.retry_after_ms / 1000)
|
|
129
|
+
return wait
|
|
130
|
+
|
|
131
|
+
def _once(self, url: str, label: str, accept: str, with_key: bool) -> tuple[int, bytes, Any]:
|
|
132
|
+
headers = {"Accept": accept, "User-Agent": self.agent}
|
|
133
|
+
if with_key:
|
|
134
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
135
|
+
request = urllib.request.Request(url, headers=headers)
|
|
136
|
+
try:
|
|
137
|
+
try:
|
|
138
|
+
with self._opener.open(request, timeout=self.timeout) as answer:
|
|
139
|
+
return answer.status, answer.read(), answer.headers
|
|
140
|
+
except urllib.error.HTTPError as refused:
|
|
141
|
+
status, retry_after = refused.code, refused.headers.get("retry-after")
|
|
142
|
+
raw = refused.read()
|
|
143
|
+
# URLError and timeouts are OSErrors; a garbled status line is an HTTPException.
|
|
144
|
+
except (OSError, http.client.HTTPException) as e:
|
|
145
|
+
reason = getattr(e, "reason", None) or str(e) or type(e).__name__
|
|
146
|
+
raise errors.network(f"GET {label}: no answer ({reason}).") from e
|
|
147
|
+
try:
|
|
148
|
+
body = json.loads(raw) if raw else None
|
|
149
|
+
except ValueError:
|
|
150
|
+
body = None
|
|
151
|
+
raise errors.refusal(status, body, label, retry_after, datetime.now(timezone.utc))
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def stream_url(self) -> str:
|
|
155
|
+
return re.sub(r"^http", "ws", self.base, flags=re.IGNORECASE) + "/api/v2/stream"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _required(value: Optional[str], name: str, what: str) -> str:
|
|
159
|
+
if value is None or not str(value).strip():
|
|
160
|
+
got = "None" if value is None else "an empty string"
|
|
161
|
+
raise ValueError(f"StreamcomClient: `{name}` is required — {what}. It was {got}.")
|
|
162
|
+
return str(value).strip()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _id(value: str, what: str) -> str:
|
|
166
|
+
"""An id as one encoded path segment."""
|
|
167
|
+
return urllib.parse.quote(_required(value, "id", what), safe="")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _moment(value: Optional[datetime]) -> Optional[str]:
|
|
171
|
+
return None if value is None else format_time(value)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _pages(read: Callable[[Optional[str]], tuple[list[T], Optional[str]]]) -> Iterator[T]:
|
|
175
|
+
cursor: Optional[str] = None
|
|
176
|
+
while True:
|
|
177
|
+
# A page may be short, or even empty, and still not be the last.
|
|
178
|
+
items, cursor = read(cursor)
|
|
179
|
+
yield from items
|
|
180
|
+
if cursor is None:
|
|
181
|
+
return
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@dataclass(frozen=True)
|
|
185
|
+
class MatchSync:
|
|
186
|
+
"""What :meth:`MatchesApi.sync` found.
|
|
187
|
+
|
|
188
|
+
``matches``: every match that changed (or, on a first sync, every match the filters name),
|
|
189
|
+
once each; replace what you hold by id. ``since``: pass it as ``since`` next time, and store
|
|
190
|
+
it with the matches.
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
matches: list[Match]
|
|
194
|
+
since: datetime
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class MatchesApi:
|
|
198
|
+
"""``/api/v2/matches``: the match is the main object.
|
|
199
|
+
|
|
200
|
+
The filters combine freely. With none at all the API answers twelve hours either side of
|
|
201
|
+
now; with a competition, its whole season. ``status`` takes one status or several;
|
|
202
|
+
``from_``, ``to`` and ``updated_since`` take timezone-aware datetimes; ``limit`` is 1 to 200
|
|
203
|
+
per page (the API's default is 100).
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
SYNC_OVERLAP = timedelta(seconds=60)
|
|
207
|
+
"""How far a first :meth:`sync` that saw no match steps back from the moment it read."""
|
|
208
|
+
|
|
209
|
+
def __init__(self, transport: _Transport) -> None:
|
|
210
|
+
self._transport = transport
|
|
211
|
+
|
|
212
|
+
def list(
|
|
213
|
+
self,
|
|
214
|
+
*,
|
|
215
|
+
competition: Optional[str] = None,
|
|
216
|
+
series: Optional[str] = None,
|
|
217
|
+
club: Optional[str] = None,
|
|
218
|
+
team: Optional[str] = None,
|
|
219
|
+
court: Optional[str] = None,
|
|
220
|
+
venue: Optional[str] = None,
|
|
221
|
+
status: Union[str, Iterable[str], None] = None,
|
|
222
|
+
from_: Optional[datetime] = None,
|
|
223
|
+
to: Optional[datetime] = None,
|
|
224
|
+
updated_since: Optional[datetime] = None,
|
|
225
|
+
limit: Optional[int] = None,
|
|
226
|
+
cursor: Optional[str] = None,
|
|
227
|
+
) -> MatchPage:
|
|
228
|
+
"""One page of what the filters name. Follow ``next_cursor``, or use :meth:`all`."""
|
|
229
|
+
statuses = [status] if isinstance(status, str) else list(status or [])
|
|
230
|
+
query = {
|
|
231
|
+
"competition": competition,
|
|
232
|
+
"series": series,
|
|
233
|
+
"club": club,
|
|
234
|
+
"team": team,
|
|
235
|
+
"court": court,
|
|
236
|
+
"venue": venue,
|
|
237
|
+
"status": ",".join(statuses) or None,
|
|
238
|
+
"from": _moment(from_),
|
|
239
|
+
"to": _moment(to),
|
|
240
|
+
"updated_since": _moment(updated_since),
|
|
241
|
+
"limit": limit,
|
|
242
|
+
"cursor": cursor,
|
|
243
|
+
}
|
|
244
|
+
return cast(MatchPage, self._transport.get("/matches", query))
|
|
245
|
+
|
|
246
|
+
def all(self, **filters: Any) -> Iterator[Match]:
|
|
247
|
+
"""Every match the filters name, page after page as you walk it::
|
|
248
|
+
|
|
249
|
+
for match in streamcom.matches.all(competition="cp7k2pq9x"):
|
|
250
|
+
...
|
|
251
|
+
"""
|
|
252
|
+
|
|
253
|
+
def read(cursor: Optional[str]) -> tuple[list[Match], Optional[str]]:
|
|
254
|
+
page = self.list(**filters, cursor=cursor)
|
|
255
|
+
return page["matches"], page["next_cursor"]
|
|
256
|
+
|
|
257
|
+
return _pages(read)
|
|
258
|
+
|
|
259
|
+
def get(self, id: str) -> Match:
|
|
260
|
+
"""One match; a ``not_found`` :class:`ApiError` for one this key may not read."""
|
|
261
|
+
body = self._transport.get("/matches/" + _id(id, "a match id"))
|
|
262
|
+
return cast(Match, body["match"])
|
|
263
|
+
|
|
264
|
+
def timeline(
|
|
265
|
+
self, id: str, *, cursor: Optional[str] = None, limit: Optional[int] = None
|
|
266
|
+
) -> Timeline:
|
|
267
|
+
"""One page of what the board did. Empty without the ``events`` data scope."""
|
|
268
|
+
path = "/matches/" + _id(id, "a match id") + "/timeline"
|
|
269
|
+
return cast(Timeline, self._transport.get(path, {"cursor": cursor, "limit": limit}))
|
|
270
|
+
|
|
271
|
+
def events(self, id: str) -> Iterator[TimelineEvent]:
|
|
272
|
+
"""Every row of the timeline, page after page as you walk it."""
|
|
273
|
+
_id(id, "a match id")
|
|
274
|
+
|
|
275
|
+
def read(cursor: Optional[str]) -> tuple[list[TimelineEvent], Optional[str]]:
|
|
276
|
+
page = self.timeline(id, cursor=cursor)
|
|
277
|
+
return page["events"], page["next_cursor"]
|
|
278
|
+
|
|
279
|
+
return _pages(read)
|
|
280
|
+
|
|
281
|
+
def sync(self, since: Optional[datetime] = None, **filters: Any) -> MatchSync:
|
|
282
|
+
"""Keep a set of matches up to date.
|
|
283
|
+
|
|
284
|
+
The first call (``since`` is ``None``) reads every match the filters name; every later
|
|
285
|
+
call, with the ``since`` the previous one returned, only what changed since. Replace
|
|
286
|
+
what you hold by id; a match may come twice::
|
|
287
|
+
|
|
288
|
+
sync = streamcom.matches.sync(competition="cp7k2pq9x")
|
|
289
|
+
# later, every few minutes:
|
|
290
|
+
sync = streamcom.matches.sync(sync.since, competition="cp7k2pq9x")
|
|
291
|
+
|
|
292
|
+
The ``since`` returned is the newest ``updated_at`` the call saw, the one it was given
|
|
293
|
+
when it saw nothing, or, on a first call that saw nothing, :attr:`SYNC_OVERLAP` before
|
|
294
|
+
the read.
|
|
295
|
+
"""
|
|
296
|
+
if since is not None:
|
|
297
|
+
filters = {**filters, "updated_since": since}
|
|
298
|
+
held: dict[str, Match] = {}
|
|
299
|
+
read_at: Optional[datetime] = None
|
|
300
|
+
cursor: Optional[str] = None
|
|
301
|
+
while True:
|
|
302
|
+
page = self.list(**filters, cursor=cursor)
|
|
303
|
+
if read_at is None:
|
|
304
|
+
read_at = parse_time(page["server_time"])
|
|
305
|
+
for match in page["matches"]:
|
|
306
|
+
held[match["id"]] = match
|
|
307
|
+
cursor = page["next_cursor"]
|
|
308
|
+
if cursor is None:
|
|
309
|
+
break
|
|
310
|
+
newest = max((parse_time(m["updated_at"]) for m in held.values()), default=None)
|
|
311
|
+
assert read_at is not None
|
|
312
|
+
following = newest or since or read_at - self.SYNC_OVERLAP
|
|
313
|
+
return MatchSync(list(held.values()), following)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
class CompetitionsApi:
|
|
317
|
+
"""``/api/v2/competitions``."""
|
|
318
|
+
|
|
319
|
+
def __init__(self, transport: _Transport) -> None:
|
|
320
|
+
self._transport = transport
|
|
321
|
+
|
|
322
|
+
def list(
|
|
323
|
+
self,
|
|
324
|
+
*,
|
|
325
|
+
season: Optional[str] = None,
|
|
326
|
+
series: Optional[str] = None,
|
|
327
|
+
federation: Optional[str] = None,
|
|
328
|
+
updated_since: Optional[datetime] = None,
|
|
329
|
+
) -> List[Competition]:
|
|
330
|
+
"""The competitions this key reaches that the filters name. No pages: this is all."""
|
|
331
|
+
query = {
|
|
332
|
+
"season": season,
|
|
333
|
+
"series": series,
|
|
334
|
+
"federation": federation,
|
|
335
|
+
"updated_since": _moment(updated_since),
|
|
336
|
+
}
|
|
337
|
+
body = self._transport.get("/competitions", query)
|
|
338
|
+
return cast(List[Competition], body["competitions"])
|
|
339
|
+
|
|
340
|
+
def get(self, id: str) -> CompetitionDetail:
|
|
341
|
+
"""One competition with its teams and how much of it Streamcom covers."""
|
|
342
|
+
body = self._transport.get("/competitions/" + _id(id, "a competition id"))
|
|
343
|
+
return cast(CompetitionDetail, body["competition"])
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
class ClubsApi:
|
|
347
|
+
"""``/api/v2/clubs``."""
|
|
348
|
+
|
|
349
|
+
def __init__(self, transport: _Transport) -> None:
|
|
350
|
+
self._transport = transport
|
|
351
|
+
|
|
352
|
+
def get(self, id: str) -> Club:
|
|
353
|
+
"""A club's face and the teams of it this key may see."""
|
|
354
|
+
return cast(Club, self._transport.get("/clubs/" + _id(id, "a club id"))["club"])
|
|
355
|
+
|
|
356
|
+
def logo(self, logo_url: str) -> bytes:
|
|
357
|
+
"""The crest a ``logo_url`` names, as bytes (PNG, JPEG, SVG or WebP).
|
|
358
|
+
|
|
359
|
+
Follow the value as the API sent it; never compose the address: its ``v`` is what
|
|
360
|
+
expires a cached picture when a club uploads a new one. The route needs no key, so the
|
|
361
|
+
key goes only to the API's own address. A ``not_found`` :class:`ApiError` is a club with
|
|
362
|
+
no crest: draw nothing.
|
|
363
|
+
"""
|
|
364
|
+
url = _required(logo_url, "logo_url", "a `logo_url` from a match side or a club")
|
|
365
|
+
same_origin = url.startswith(self._transport.base + "/")
|
|
366
|
+
_, raw, _ = self._transport.fetch(url, url, "image/*", with_key=same_origin)
|
|
367
|
+
return raw
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
class CourtsApi:
|
|
371
|
+
"""``/api/v2/courts``."""
|
|
372
|
+
|
|
373
|
+
def __init__(self, transport: _Transport) -> None:
|
|
374
|
+
self._transport = transport
|
|
375
|
+
|
|
376
|
+
def list(self) -> List[Court]:
|
|
377
|
+
"""Every court this key may read."""
|
|
378
|
+
return cast(List[Court], self._transport.get("/courts")["courts"])
|
|
379
|
+
|
|
380
|
+
def get(self, id: str) -> CourtSnapshot:
|
|
381
|
+
"""The whole state of one court now. For joining, not polling: a key may make 60
|
|
382
|
+
requests a minute."""
|
|
383
|
+
return cast(CourtSnapshot, self._transport.get("/courts/" + _id(id, "a court id")))
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
_BEARER = re.compile(r"^Bearer\s+", re.IGNORECASE)
|
|
387
|
+
_WS = re.compile(r"^ws(s?):", re.IGNORECASE)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
class StreamcomClient:
|
|
391
|
+
"""Streamcom's public API v2 for one key: matches, competitions, clubs and courts::
|
|
392
|
+
|
|
393
|
+
streamcom = StreamcomClient(token=os.environ["STREAMCOM_TOKEN"])
|
|
394
|
+
for match in streamcom.matches.all(competition="cp7k2pq9x"):
|
|
395
|
+
print(match["home"]["name"], "–", match["away"]["name"], match["status"])
|
|
396
|
+
|
|
397
|
+
Reads only, with the key in an ``Authorization`` header and never in a URL. Every call
|
|
398
|
+
blocks until it answers, and a refusal raises an :class:`ApiError`. A client is safe to
|
|
399
|
+
share between threads; make one per key and keep it.
|
|
400
|
+
|
|
401
|
+
- ``token``: the API key as the portal's Data feed page showed it (a leading ``Bearer `` is
|
|
402
|
+
tolerated).
|
|
403
|
+
- ``url``: defaults to the production API; ``wss://`` is read as ``https://``.
|
|
404
|
+
- ``timeout``: how long one request may wait on the network, in seconds.
|
|
405
|
+
- ``retries``: how often a request that got no answer, a 5xx or a 429 is tried again (2 by
|
|
406
|
+
default; 0 never), on ``retry_backoff`` (0.5 to 8 s). A 429 waits for its ``Retry-After``,
|
|
407
|
+
unless that is longer than ``max_retry_wait`` seconds: then it raises at once.
|
|
408
|
+
- ``ssl_context``: your own TLS settings, for the REST routes and the stream.
|
|
409
|
+
"""
|
|
410
|
+
|
|
411
|
+
def __init__(
|
|
412
|
+
self,
|
|
413
|
+
token: Optional[str],
|
|
414
|
+
*,
|
|
415
|
+
url: str = DEFAULT_API_URL,
|
|
416
|
+
timeout: float = 30.0,
|
|
417
|
+
retries: int = 2,
|
|
418
|
+
retry_backoff: Backoff = Backoff(min=0.5, max=8.0),
|
|
419
|
+
max_retry_wait: float = 60.0,
|
|
420
|
+
ssl_context: Optional[ssl.SSLContext] = None,
|
|
421
|
+
) -> None:
|
|
422
|
+
given = _required(token, "token", "an API key from the portal's Data feed page")
|
|
423
|
+
key = _BEARER.sub("", given).strip()
|
|
424
|
+
given_url = _required(url, "url", "the API's address")
|
|
425
|
+
base = _WS.sub(lambda m: "https:" if m.group(1) else "http:", given_url).rstrip("/")
|
|
426
|
+
if retries < 0:
|
|
427
|
+
raise ValueError("StreamcomClient: `retries` is 0 or more.")
|
|
428
|
+
transport = _Transport(
|
|
429
|
+
key, base, timeout, retries, retry_backoff, max_retry_wait, ssl_context
|
|
430
|
+
)
|
|
431
|
+
self._transport = transport
|
|
432
|
+
self.matches = MatchesApi(transport)
|
|
433
|
+
"""Matches: a page, all of them, one, its timeline, and keeping a set up to date."""
|
|
434
|
+
self.competitions = CompetitionsApi(transport)
|
|
435
|
+
"""The competitions this key reaches."""
|
|
436
|
+
self.clubs = ClubsApi(transport)
|
|
437
|
+
"""A club's face and teams."""
|
|
438
|
+
self.courts = CourtsApi(transport)
|
|
439
|
+
"""The courts this key reads, and one court's whole board now."""
|
|
440
|
+
|
|
441
|
+
def stream(
|
|
442
|
+
self,
|
|
443
|
+
courts: Optional[Iterable[str]] = None,
|
|
444
|
+
matches: Optional[Iterable[str]] = None,
|
|
445
|
+
competitions: Optional[Iterable[str]] = None,
|
|
446
|
+
*,
|
|
447
|
+
silence: float = SILENCE,
|
|
448
|
+
backoff: Backoff = Backoff(),
|
|
449
|
+
open_timeout: float = 10.0,
|
|
450
|
+
max_delay: float = MAX_DELAY,
|
|
451
|
+
) -> LiveStream:
|
|
452
|
+
"""The live stream with this client's key and address, not yet open: add handlers, then
|
|
453
|
+
:meth:`LiveStream.open` it (or use it in a ``with`` block)::
|
|
454
|
+
|
|
455
|
+
stream = streamcom.stream(competitions=["cp7k2pq9x"])
|
|
456
|
+
|
|
457
|
+
@stream.on_live
|
|
458
|
+
def cue(match):
|
|
459
|
+
print(match["home"]["name"], "–", match["away"]["name"], "is live")
|
|
460
|
+
|
|
461
|
+
with stream:
|
|
462
|
+
stream.wait()
|
|
463
|
+
|
|
464
|
+
``silence``: seconds without any message before the connection counts as dead and is
|
|
465
|
+
redialled (35: three missed pings). ``backoff``: the redial schedule (1 to 30 s).
|
|
466
|
+
``open_timeout``: how long one dial may take. ``max_delay``: how far behind the hall
|
|
467
|
+
:meth:`LiveStream.align_to` may put the view (300 s), to show the board in step with a
|
|
468
|
+
delayed video.
|
|
469
|
+
"""
|
|
470
|
+
t = self._transport
|
|
471
|
+
return LiveStream(
|
|
472
|
+
t.stream_url,
|
|
473
|
+
{"Authorization": f"Bearer {t.token}"},
|
|
474
|
+
Follow.of(courts, matches, competitions),
|
|
475
|
+
user_agent=t.agent,
|
|
476
|
+
silence=silence,
|
|
477
|
+
backoff=backoff,
|
|
478
|
+
open_timeout=open_timeout,
|
|
479
|
+
ssl_context=t.ssl_context,
|
|
480
|
+
max_delay=max_delay,
|
|
481
|
+
)
|
|
482
|
+
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""The clock arithmetic: turning a clock anchor into the number on screen.
|
|
2
|
+
|
|
3
|
+
The same rules as the platform's, the npm package's and the Java SDK's, held to the shared cases
|
|
4
|
+
in ``sdks/cases/clock.json``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timedelta, timezone
|
|
11
|
+
from typing import Any, Literal, Mapping, Optional
|
|
12
|
+
|
|
13
|
+
from ._time import parse_time
|
|
14
|
+
|
|
15
|
+
DeliveryMode = Literal["anchored", "streamed"]
|
|
16
|
+
ClockDirection = Literal["down", "up"]
|
|
17
|
+
SourceStatus = Literal["online", "degraded", "offline"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class ClockReading:
|
|
22
|
+
"""What a clock shows at one moment.
|
|
23
|
+
|
|
24
|
+
``ticking`` says whether the value moves on its own (running, anchored and not stale). Drive
|
|
25
|
+
a render loop from it, never from ``Clock.running``: a streamed or frozen clock is running
|
|
26
|
+
too, and animating one invents numbers. ``stale`` is true when the feeding source is not
|
|
27
|
+
online, so the value is last-known, not live. ``display`` is the clock as the hall board
|
|
28
|
+
shows it (``"0:49"``, ``"9.3"``) where the API sent one.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
ms: int
|
|
32
|
+
ticking: bool
|
|
33
|
+
mode: DeliveryMode
|
|
34
|
+
stale: bool
|
|
35
|
+
display: Optional[str] = None
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def text(self) -> str:
|
|
39
|
+
"""``M:SS``, floored and never negative: 59999 ms is ``0:59``."""
|
|
40
|
+
return format_clock_text(self.ms)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def format_clock_text(ms: int) -> str:
|
|
44
|
+
"""``M:SS``, floored and clamped at zero. Minutes keep counting past the hour."""
|
|
45
|
+
total = max(0, ms) // 1000
|
|
46
|
+
return f"{total // 60}:{total % 60:02d}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Clock:
|
|
51
|
+
"""A clock as a scoreboard delivers it — game clock, shot clock, exclusion, added time — as
|
|
52
|
+
an anchor: ``remaining_ms`` was true at ``as_of``, on the source's clock.
|
|
53
|
+
|
|
54
|
+
Read it with :meth:`read`, never by ticking it yourself::
|
|
55
|
+
|
|
56
|
+
elapsed = max(0, now + offset - as_of)
|
|
57
|
+
down (the default): running ? remaining_ms - elapsed : remaining_ms
|
|
58
|
+
up: running ? remaining_ms + elapsed : remaining_ms
|
|
59
|
+
|
|
60
|
+
A ``streamed`` clock is shown as received. A clock on a source that is not online stands
|
|
61
|
+
still. A read taken before ``as_of`` answers the anchor, never more time than the board had.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
running: bool
|
|
65
|
+
remaining_ms: int
|
|
66
|
+
as_of: datetime
|
|
67
|
+
mode: Optional[DeliveryMode] = None
|
|
68
|
+
interval_ms: Optional[int] = None
|
|
69
|
+
tenths: Optional[bool] = None
|
|
70
|
+
direction: Optional[ClockDirection] = None
|
|
71
|
+
display: Optional[str] = None
|
|
72
|
+
"""The clock as the hall board shows it at ``remaining_ms`` (``"0:49"``, ``"9.3"``)."""
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
def from_wire(cls, value: Mapping[str, Any]) -> Clock:
|
|
76
|
+
"""A clock from the API's JSON, as a match, a snapshot or the board carries it."""
|
|
77
|
+
return cls(
|
|
78
|
+
running=value["running"] is True,
|
|
79
|
+
remaining_ms=int(value["remaining_ms"]),
|
|
80
|
+
as_of=parse_time(value["as_of"]),
|
|
81
|
+
mode=value.get("mode"),
|
|
82
|
+
interval_ms=value.get("interval_ms"),
|
|
83
|
+
tenths=value.get("tenths"),
|
|
84
|
+
direction=value.get("direction"),
|
|
85
|
+
display=value.get("display"),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def effective_mode(self, declared: Optional[DeliveryMode] = None) -> DeliveryMode:
|
|
89
|
+
"""This clock's own mode, else the declared one, else ``anchored``."""
|
|
90
|
+
return self.mode or declared or "anchored"
|
|
91
|
+
|
|
92
|
+
def interpolate(self, offset_ms: int, now: datetime) -> int:
|
|
93
|
+
"""The bare number at ``now`` in ms, never below zero, without a declared mode or a
|
|
94
|
+
source status. :meth:`read` is what a display wants."""
|
|
95
|
+
return self._interpolate(self.effective_mode(), offset_ms, epoch_ms(now))
|
|
96
|
+
|
|
97
|
+
def read(
|
|
98
|
+
self,
|
|
99
|
+
now: datetime,
|
|
100
|
+
*,
|
|
101
|
+
offset_ms: int = 0,
|
|
102
|
+
declared_mode: Optional[DeliveryMode] = None,
|
|
103
|
+
status: Optional[SourceStatus] = None,
|
|
104
|
+
) -> ClockReading:
|
|
105
|
+
"""The full reading at ``now`` (timezone-aware).
|
|
106
|
+
|
|
107
|
+
``offset_ms`` is the source's clock minus ours (positive: the source is ahead);
|
|
108
|
+
``declared_mode`` the mode the board's capabilities declare (the clock's own wins);
|
|
109
|
+
``status`` the health of the source feeding it, ``None`` reading as online. Anything but
|
|
110
|
+
``online``, ``degraded`` included, freezes the value at its anchor.
|
|
111
|
+
"""
|
|
112
|
+
return self.read_ms(epoch_ms(now), offset_ms, declared_mode, status)
|
|
113
|
+
|
|
114
|
+
def read_ms(
|
|
115
|
+
self,
|
|
116
|
+
now_ms: int,
|
|
117
|
+
offset_ms: int = 0,
|
|
118
|
+
declared_mode: Optional[DeliveryMode] = None,
|
|
119
|
+
status: Optional[str] = None,
|
|
120
|
+
) -> ClockReading:
|
|
121
|
+
""":meth:`read` at a moment in epoch milliseconds."""
|
|
122
|
+
mode = self.effective_mode(declared_mode)
|
|
123
|
+
if status is not None and status != "online":
|
|
124
|
+
return ClockReading(max(0, self.remaining_ms), False, mode, True, self.display)
|
|
125
|
+
return ClockReading(
|
|
126
|
+
self._interpolate(mode, offset_ms, now_ms),
|
|
127
|
+
self.running and mode == "anchored",
|
|
128
|
+
mode,
|
|
129
|
+
False,
|
|
130
|
+
self.display,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def _interpolate(self, mode: str, offset_ms: int, now_ms: int) -> int:
|
|
134
|
+
if not self.running or mode == "streamed":
|
|
135
|
+
return max(0, self.remaining_ms)
|
|
136
|
+
elapsed = max(0, now_ms + offset_ms - epoch_ms(self.as_of))
|
|
137
|
+
sign = 1 if self.direction == "up" else -1
|
|
138
|
+
return max(0, self.remaining_ms + sign * elapsed)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def epoch_ms(at: datetime) -> int:
|
|
145
|
+
"""A timezone-aware moment in whole epoch milliseconds, floored, as every SDK counts them."""
|
|
146
|
+
if at.tzinfo is None:
|
|
147
|
+
raise ValueError(
|
|
148
|
+
"a clock is read at a timezone-aware moment, e.g. datetime.now(timezone.utc)"
|
|
149
|
+
)
|
|
150
|
+
# Exact integer arithmetic; a float timestamp can be a millisecond off.
|
|
151
|
+
return (at - _EPOCH) // timedelta(milliseconds=1)
|