python-ballchasing 0.5.4__py3-none-any.whl → 0.6.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.
- ballchasing/__init__.py +1 -0
- ballchasing/api.py +212 -31
- ballchasing/constants.py +12 -9
- ballchasing/exceptions.py +37 -0
- ballchasing/rate_limit.py +13 -1
- ballchasing/stats_info.tsv +29 -1
- ballchasing/typed/__init__.py +2 -5
- ballchasing/typed/_base.py +106 -0
- ballchasing/typed/deep_group.py +26 -440
- ballchasing/typed/deep_replay.py +23 -286
- ballchasing/typed/methods.py +145 -0
- ballchasing/typed/models.py +954 -0
- ballchasing/typed/shallow_group.py +3 -18
- ballchasing/typed/shallow_replay.py +5 -66
- ballchasing/typed/shared.py +6 -243
- ballchasing/util/iterators.py +1 -1
- ballchasing/util/stats.py +3 -3
- {python_ballchasing-0.5.4.dist-info → python_ballchasing-0.6.0.dist-info}/METADATA +18 -2
- python_ballchasing-0.6.0.dist-info/RECORD +25 -0
- {python_ballchasing-0.5.4.dist-info → python_ballchasing-0.6.0.dist-info}/WHEEL +1 -1
- python_ballchasing-0.6.0.dist-info/top_level.txt +1 -0
- python_ballchasing-0.5.4.dist-info/RECORD +0 -26
- python_ballchasing-0.5.4.dist-info/top_level.txt +0 -3
- scripts/get_maps.py +0 -147
- scripts/make_types.py +0 -194
- scripts/test.py +0 -52
- scripts/test_typed.py +0 -88
- tests/test_fixes.py +0 -439
- {python_ballchasing-0.5.4.dist-info → python_ballchasing-0.6.0.dist-info}/licenses/LICENSE +0 -0
ballchasing/__init__.py
CHANGED
|
@@ -50,6 +50,7 @@ except Exception:
|
|
|
50
50
|
# Import the main classes and constants to make them easily accessible to users.
|
|
51
51
|
from .api import BallchasingApi
|
|
52
52
|
from .rate_limit import RateLimiter, RateLimitCategory, rate_limited
|
|
53
|
+
from .exceptions import QuotaExceededError, DailyDownloadLimitError, UploadQuotaError
|
|
53
54
|
|
|
54
55
|
Api = BallchasingApi # For importing like `import ballchasing; api = ballchasing.Api`
|
|
55
56
|
|
ballchasing/api.py
CHANGED
|
@@ -1,20 +1,23 @@
|
|
|
1
|
+
import json
|
|
1
2
|
import logging
|
|
3
|
+
import math
|
|
2
4
|
import os
|
|
3
5
|
import time
|
|
4
6
|
from concurrent.futures import ThreadPoolExecutor
|
|
5
7
|
from datetime import datetime
|
|
6
8
|
from pathlib import Path
|
|
7
|
-
from typing import BinaryIO, Iterator
|
|
9
|
+
from typing import BinaryIO, Iterable, Iterator
|
|
8
10
|
from urllib.parse import parse_qs, urlparse
|
|
9
11
|
|
|
10
12
|
from requests import sessions, Response
|
|
11
|
-
from requests.exceptions import ConnectionError, Timeout
|
|
13
|
+
from requests.exceptions import ConnectionError, HTTPError, Timeout
|
|
12
14
|
|
|
13
15
|
from ballchasing.constants import GroupSortBy, SortDir, AnySeason, AnyRank, AnyReplaySortBy, AnySortDir, \
|
|
14
16
|
AnyVisibility, AnyGroupSortBy, AnyPlayerIdentification, AnyTeamIdentification, AnyMatchResult, NoneOrMore
|
|
17
|
+
from ballchasing.exceptions import DailyDownloadLimitError, UploadQuotaError
|
|
15
18
|
from ballchasing.rate_limit import RateLimiter, RateLimitCategory, resolve_category, rate_limited
|
|
16
19
|
from ballchasing.typed import DeepReplay, ShallowReplay, DeepGroup, ShallowGroup
|
|
17
|
-
from .typed.
|
|
20
|
+
from .typed.models import BaseGroup, BasicGroup
|
|
18
21
|
from .util.dates import to_rfc3339
|
|
19
22
|
from .util.iterators import deduplicate as deduplicator
|
|
20
23
|
from .util.stats import parse_replay_stats
|
|
@@ -23,12 +26,21 @@ logger = logging.getLogger("ballchasing")
|
|
|
23
26
|
|
|
24
27
|
DEFAULT_URL = "https://ballchasing.com/api"
|
|
25
28
|
|
|
29
|
+
# Limits from the OpenAPI document (tests check them against it)
|
|
30
|
+
PAGE_SIZE = 200 # Max `count` of GET /replays and GET /groups
|
|
31
|
+
DUPLICATE_REPLAYS_PAGE_SIZE = 1000 # Max `count` of GET /groups/{id}/duplicate-replays
|
|
32
|
+
MAX_ASSIGN_REPLAYS = 150 # Max assign_replays per PATCH /groups/{id}
|
|
33
|
+
MAX_UNASSIGN_REPLAYS = 300 # Max unassign_replays per PATCH /groups/{id}
|
|
34
|
+
|
|
26
35
|
PATRON_RATE_LIMIT_SLEEP_TIMES = {
|
|
27
36
|
"regular": 3600 / 1000,
|
|
28
37
|
"gold": 3600 / 2000,
|
|
29
38
|
"diamond": 3600 / 5000,
|
|
30
39
|
"champion": 1 / 8,
|
|
31
40
|
"gc": 1 / 16,
|
|
41
|
+
"legend": 1 / 16,
|
|
42
|
+
"org": 1 / 16,
|
|
43
|
+
"bot": 1 / 16,
|
|
32
44
|
}
|
|
33
45
|
|
|
34
46
|
|
|
@@ -128,6 +140,7 @@ class BallchasingApi:
|
|
|
128
140
|
method: str,
|
|
129
141
|
allow_status_codes: tuple[int, ...] = (),
|
|
130
142
|
category: RateLimitCategory | str | None = None,
|
|
143
|
+
auth_key: str | None = None,
|
|
131
144
|
**params
|
|
132
145
|
) -> Response:
|
|
133
146
|
"""
|
|
@@ -137,13 +150,16 @@ class BallchasingApi:
|
|
|
137
150
|
:param method: the method to use.
|
|
138
151
|
:param allow_status_codes: additional HTTP status codes to treat as successful responses.
|
|
139
152
|
:param category: rate limit category for this request.
|
|
153
|
+
:param auth_key: key to authenticate this request with instead of self.auth_key (e.g. a group upload token).
|
|
140
154
|
:param params: parameters for request (e.g. params, json, files, stream).
|
|
141
155
|
:return: the request result.
|
|
142
156
|
:raises ConnectionError: if the connection fails after max retries.
|
|
157
|
+
:raises DailyDownloadLimitError: on a 429 for the daily limit on other people's replay files.
|
|
158
|
+
:raises UploadQuotaError: on a 429 for the account's upload quota.
|
|
143
159
|
:raises HTTPError: if the request fails with a status code other than 2xx, 429, or allow_status_codes.
|
|
144
160
|
"""
|
|
145
161
|
cat = RateLimitCategory(category) if category else resolve_category(url_or_endpoint)
|
|
146
|
-
headers = {"Authorization": self.auth_key}
|
|
162
|
+
headers = {"Authorization": self.auth_key if auth_key is None else auth_key}
|
|
147
163
|
url = f"{self.base_url}{url_or_endpoint}" if url_or_endpoint.startswith("/") else url_or_endpoint
|
|
148
164
|
max_retries = 8
|
|
149
165
|
retries = 0
|
|
@@ -152,12 +168,28 @@ class BallchasingApi:
|
|
|
152
168
|
# Wait if global cooldown is active or if proactive pacing applies
|
|
153
169
|
self.rate_limiter.before_request(cat)
|
|
154
170
|
|
|
171
|
+
# Uploaded file objects are read by each attempt: rewind them before retrying
|
|
172
|
+
file_objects = [f[1] if isinstance(f, tuple) else f for f in (params.get("files") or {}).values()]
|
|
173
|
+
file_positions = []
|
|
174
|
+
for f in file_objects:
|
|
175
|
+
try:
|
|
176
|
+
if f.seekable(): # Not e.g. a pipe or a socket: those can't be resent
|
|
177
|
+
file_positions.append((f, f.tell()))
|
|
178
|
+
except (AttributeError, OSError, ValueError):
|
|
179
|
+
pass
|
|
180
|
+
attempt = 0
|
|
181
|
+
|
|
155
182
|
while True:
|
|
156
183
|
try:
|
|
184
|
+
if attempt > 0:
|
|
185
|
+
for f, position in file_positions:
|
|
186
|
+
f.seek(position)
|
|
187
|
+
attempt += 1
|
|
157
188
|
r: Response = self._session.request(method=method, url=url, headers=headers, **params)
|
|
158
189
|
if 200 <= r.status_code < 300 or r.status_code in allow_status_codes:
|
|
159
190
|
return r
|
|
160
191
|
elif r.status_code == 429:
|
|
192
|
+
self._raise_for_quota(r)
|
|
161
193
|
self.rate_limit_count += 1
|
|
162
194
|
rate_limit_retries += 1
|
|
163
195
|
retry_after = r.headers.get("Retry-After", '0')
|
|
@@ -190,6 +222,24 @@ class BallchasingApi:
|
|
|
190
222
|
time.sleep(s)
|
|
191
223
|
retries += 1
|
|
192
224
|
|
|
225
|
+
@staticmethod
|
|
226
|
+
def _raise_for_quota(r: Response) -> None:
|
|
227
|
+
"""Raise for the 429s that are quotas (not worth retrying soon) rather than rate limits."""
|
|
228
|
+
try:
|
|
229
|
+
body = r.json()
|
|
230
|
+
except ValueError:
|
|
231
|
+
return
|
|
232
|
+
if not isinstance(body, dict):
|
|
233
|
+
return
|
|
234
|
+
if "limit" in body and "reset" in body:
|
|
235
|
+
raise DailyDownloadLimitError(
|
|
236
|
+
f"Daily limit on other people's replay files reached ({body.get('count')}/{body.get('limit')}), "
|
|
237
|
+
f"resets at {body.get('reset')}", response=r, body=body)
|
|
238
|
+
if "max_uploads" in body:
|
|
239
|
+
raise UploadQuotaError(
|
|
240
|
+
f"Upload quota reached ({body.get('max_uploads')} per {body.get('window')}): {body.get('error')}",
|
|
241
|
+
response=r, body=body)
|
|
242
|
+
|
|
193
243
|
@rate_limited(RateLimitCategory.PING)
|
|
194
244
|
def ping(self) -> dict:
|
|
195
245
|
"""
|
|
@@ -205,7 +255,8 @@ class BallchasingApi:
|
|
|
205
255
|
self._ping_result = result
|
|
206
256
|
return result
|
|
207
257
|
|
|
208
|
-
def _iterable_from_request(self, url, params, prefetch=True
|
|
258
|
+
def _iterable_from_request(self, url, params, prefetch=True, *, page_size=PAGE_SIZE,
|
|
259
|
+
category=RateLimitCategory.LIST):
|
|
209
260
|
# Shared by get_replays and get_groups.
|
|
210
261
|
# When prefetch=True, the next page is requested in a background
|
|
211
262
|
# thread *before* yielding, so network I/O overlaps with the
|
|
@@ -217,15 +268,15 @@ class BallchasingApi:
|
|
|
217
268
|
return
|
|
218
269
|
|
|
219
270
|
def fetch_page(p):
|
|
220
|
-
return self._request(url, "GET", params=p, category=
|
|
271
|
+
return self._request(url, "GET", params=p, category=category).json()
|
|
221
272
|
|
|
222
273
|
with ThreadPoolExecutor(max_workers=1) as executor:
|
|
223
|
-
params["count"] = min(remaining,
|
|
274
|
+
params["count"] = min(remaining, page_size)
|
|
224
275
|
future = executor.submit(fetch_page, dict(params))
|
|
225
276
|
|
|
226
277
|
while remaining > 0:
|
|
227
278
|
d = future.result()
|
|
228
|
-
batch = d.get("list", [])[:min(remaining,
|
|
279
|
+
batch = d.get("list", [])[:min(remaining, page_size)]
|
|
229
280
|
remaining -= len(batch)
|
|
230
281
|
|
|
231
282
|
next_url = d.get("next")
|
|
@@ -236,7 +287,7 @@ class BallchasingApi:
|
|
|
236
287
|
params["after"] = after_param
|
|
237
288
|
else:
|
|
238
289
|
has_next = False
|
|
239
|
-
params["count"] = min(remaining,
|
|
290
|
+
params["count"] = min(remaining, page_size)
|
|
240
291
|
if prefetch and has_next:
|
|
241
292
|
future = executor.submit(fetch_page, dict(params))
|
|
242
293
|
|
|
@@ -270,6 +321,7 @@ class BallchasingApi:
|
|
|
270
321
|
count: int = 150,
|
|
271
322
|
sort_by: AnyReplaySortBy | None = None,
|
|
272
323
|
sort_dir: AnySortDir = SortDir.DESCENDING,
|
|
324
|
+
roulette: bool = False,
|
|
273
325
|
deep: bool = False,
|
|
274
326
|
typed: bool | None = None,
|
|
275
327
|
deduplicate: bool = False,
|
|
@@ -279,10 +331,11 @@ class BallchasingApi:
|
|
|
279
331
|
This endpoint lets you filter and retrieve replays. The implementation returns an iterator.
|
|
280
332
|
|
|
281
333
|
:param title: filter replays by title.
|
|
282
|
-
:param player_name: filter replays by a player’s name.
|
|
334
|
+
:param player_name: filter replays by a player’s name (word or word prefix, case insensitive).
|
|
335
|
+
Quote it (e.g. '"Can't Fly"') to match the exact name. Multiple names: replays with all.
|
|
283
336
|
:param player_id: filter replays by a player’s platform id in the $platform:$id, e.g. steam:76561198141161044,
|
|
284
337
|
ps4:gamertag, … You can filter replays by multiple player ids, e.g ?player-id=steam:1&player-id=steam:2
|
|
285
|
-
:param playlist: filter replays by one or more playlists.
|
|
338
|
+
:param playlist: filter replays by one or more playlists. Prefix one with "!" to exclude it (e.g. "!private").
|
|
286
339
|
:param season: filter replays by season. Must be a number between 1 and 14 (for old seasons)
|
|
287
340
|
or f1, f2, … for the new free to play seasons
|
|
288
341
|
:param match_result: filter your replays by result.
|
|
@@ -290,7 +343,8 @@ class BallchasingApi:
|
|
|
290
343
|
:param max_rank: filter your replays based on players maximum rank.
|
|
291
344
|
:param pro: only include replays containing at least one pro player.
|
|
292
345
|
:param uploader: only include replays uploaded by the specified user. Accepts either the
|
|
293
|
-
numerical 76*************44 steam id, or the special value 'me'
|
|
346
|
+
numerical 76*************44 steam id, or the special value 'me'.
|
|
347
|
+
'is:player' keeps the replays whose uploader played in them, '!is:player' the others
|
|
294
348
|
:param group_id: only include replays belonging to the specified group. This only include replays immediately
|
|
295
349
|
under the specified group, but not replays in child groups
|
|
296
350
|
:param map_id: only include replays in the specified map. Check get_maps for the list of valid map codes
|
|
@@ -304,8 +358,10 @@ class BallchasingApi:
|
|
|
304
358
|
RFC3339 format, e.g. '2020-01-02T15:00:05+01:00'
|
|
305
359
|
:param count: returns at most count replays. Since the implementation uses an iterator it supports iterating
|
|
306
360
|
past the limit of 200 set by the API
|
|
307
|
-
:param sort_by: sort replays according the selected field ('replay-date', '
|
|
361
|
+
:param sort_by: sort replays according the selected field ('replay-date', 'created').
|
|
362
|
+
The former name 'upload-date' is accepted and sent as 'created'.
|
|
308
363
|
:param sort_dir: sort direction ('asc', 'desc')
|
|
364
|
+
:param roulette: return one random replay among the matching ones (ignores count).
|
|
309
365
|
:param deep: whether to get full stats for each replay (will be much slower).
|
|
310
366
|
:param typed: whether to return a typed object (default is self.typed).
|
|
311
367
|
:param deduplicate: whether to deduplicate replays that seem to be the same game.
|
|
@@ -313,13 +369,16 @@ class BallchasingApi:
|
|
|
313
369
|
:return: an iterator over the replays returned by the API.
|
|
314
370
|
"""
|
|
315
371
|
url = f"{self.base_url}/replays"
|
|
372
|
+
if sort_by == "upload-date":
|
|
373
|
+
sort_by = "created" # Renamed in the API, "upload-date" now gives a 400
|
|
316
374
|
params = {"title": title, "player-name": player_name, "player-id": player_id, "playlist": playlist,
|
|
317
375
|
"season": season, "match-result": match_result, "min-rank": min_rank, "max-rank": max_rank,
|
|
318
376
|
"pro": str(pro).lower() if isinstance(pro, bool) else pro, "uploader": uploader, "group": group_id,
|
|
319
377
|
"map": map_id,
|
|
320
378
|
"created-before": to_rfc3339(created_before), "created-after": to_rfc3339(created_after),
|
|
321
379
|
"replay-date-after": to_rfc3339(replay_after), "replay-date-before": to_rfc3339(replay_before),
|
|
322
|
-
"count": count, "sort-by": sort_by, "sort-dir": sort_dir
|
|
380
|
+
"count": count, "sort-by": sort_by, "sort-dir": sort_dir,
|
|
381
|
+
"roulette": "true" if roulette else None}
|
|
323
382
|
|
|
324
383
|
if typed is None:
|
|
325
384
|
typed = self.typed
|
|
@@ -332,7 +391,7 @@ class BallchasingApi:
|
|
|
332
391
|
# Deep replays have match and replay IDs to deduplicate with. For shallow replays we check dates.
|
|
333
392
|
iterator = deduplicator(iterator, check_dates=not deep)
|
|
334
393
|
if deep:
|
|
335
|
-
iterator = (self.get_replay(r["id"]) for r in iterator)
|
|
394
|
+
iterator = (self.get_replay(r["id"], typed=False) for r in iterator)
|
|
336
395
|
if typed:
|
|
337
396
|
if deep:
|
|
338
397
|
iterator = (DeepReplay(**r) for r in iterator)
|
|
@@ -341,15 +400,24 @@ class BallchasingApi:
|
|
|
341
400
|
yield from iterator
|
|
342
401
|
|
|
343
402
|
@rate_limited(RateLimitCategory.CORE)
|
|
344
|
-
def get_replay(
|
|
403
|
+
def get_replay(
|
|
404
|
+
self,
|
|
405
|
+
replay_id: str,
|
|
406
|
+
*,
|
|
407
|
+
group: str | None = None,
|
|
408
|
+
typed: bool | None = None
|
|
409
|
+
) -> dict | DeepReplay:
|
|
345
410
|
"""
|
|
346
411
|
Retrieve a given replay’s details and stats.
|
|
347
412
|
|
|
348
413
|
:param replay_id: the replay id.
|
|
414
|
+
:param group: id of a shared group holding the replay. Its owner's replays in it can then be read whatever
|
|
415
|
+
their visibility, as on the group's page.
|
|
349
416
|
:param typed: whether to return a typed object (default is self.typed).
|
|
350
417
|
:return: the result of the GET request.
|
|
351
418
|
"""
|
|
352
|
-
result = self._request(f"/replays/{replay_id}", "GET",
|
|
419
|
+
result = self._request(f"/replays/{replay_id}", "GET", params={"group": group},
|
|
420
|
+
category=RateLimitCategory.CORE).json()
|
|
353
421
|
if typed is None:
|
|
354
422
|
typed = self.typed
|
|
355
423
|
if typed:
|
|
@@ -384,13 +452,16 @@ class BallchasingApi:
|
|
|
384
452
|
payload["group"] = group
|
|
385
453
|
self._request(f"/replays/{replay_id}", "PATCH", json=payload, category=RateLimitCategory.CORE)
|
|
386
454
|
|
|
387
|
-
@rate_limited(RateLimitCategory.
|
|
455
|
+
@rate_limited(RateLimitCategory.UPLOAD)
|
|
388
456
|
def upload_replay(
|
|
389
457
|
self,
|
|
390
458
|
replay_file: str | Path | BinaryIO,
|
|
391
459
|
*,
|
|
392
460
|
visibility: AnyVisibility | None = None,
|
|
393
461
|
group: str | None = None,
|
|
462
|
+
title: str | None = None,
|
|
463
|
+
match: dict | str | None = None,
|
|
464
|
+
upload_token: str | None = None,
|
|
394
465
|
raise_on_duplicate: bool = False,
|
|
395
466
|
) -> dict:
|
|
396
467
|
"""
|
|
@@ -399,10 +470,17 @@ class BallchasingApi:
|
|
|
399
470
|
:param replay_file: replay file to upload. Can be a file path (str or Path) or a file-like object.
|
|
400
471
|
:param visibility: to set the visibility of the uploaded replay ('public', 'unlisted', 'private').
|
|
401
472
|
:param group: to upload the replay to an existing group.
|
|
473
|
+
:param title: title of the new replay (at most 1024 characters; an invalid one is silently ignored by the API).
|
|
474
|
+
:param match: the game's match data, as Psyonix's match history API returns it (an RLAPI `Match` object,
|
|
475
|
+
as a dict or JSON string). It needs `MatchGUID`; an invalid value is ignored by the API.
|
|
476
|
+
:param upload_token: a group upload token (starts with "g/") to authenticate the upload with instead of the
|
|
477
|
+
API key: the replay goes to that group. See get_group_upload_token.
|
|
402
478
|
:param raise_on_duplicate: if True, raise an HTTPError when a 409 Conflict (duplicate replay)
|
|
403
479
|
is returned. If False (default), returns the API response dict with the
|
|
404
|
-
existing replay id.
|
|
405
|
-
|
|
480
|
+
existing replay id. (With a group upload token, a replay its owner already has
|
|
481
|
+
outside the group gives a 409 without an id.)
|
|
482
|
+
:return: the result of the POST request (dict containing replay 'id' and 'location').
|
|
483
|
+
:raises UploadQuotaError: if the account reached its upload quota.
|
|
406
484
|
"""
|
|
407
485
|
if isinstance(replay_file, (str, Path)):
|
|
408
486
|
with open(replay_file, "rb") as f:
|
|
@@ -410,15 +488,30 @@ class BallchasingApi:
|
|
|
410
488
|
f,
|
|
411
489
|
visibility=visibility,
|
|
412
490
|
group=group,
|
|
491
|
+
title=title,
|
|
492
|
+
match=match,
|
|
493
|
+
upload_token=upload_token,
|
|
413
494
|
raise_on_duplicate=raise_on_duplicate,
|
|
414
495
|
)
|
|
496
|
+
if isinstance(replay_file, tuple): # A requests-style (file name, file object[, content type])
|
|
497
|
+
replay_file, file_name = replay_file[1], replay_file[0]
|
|
498
|
+
else:
|
|
499
|
+
file_name = getattr(replay_file, "name", None)
|
|
500
|
+
file_name = os.path.basename(file_name) if isinstance(file_name, str) else ""
|
|
501
|
+
if not file_name.endswith(".replay"): # The API refuses other file names (e.g. for a BytesIO)
|
|
502
|
+
file_name = "upload.replay"
|
|
503
|
+
files = {"file": (file_name, replay_file)}
|
|
504
|
+
if match is not None:
|
|
505
|
+
files["match"] = (None, match if isinstance(match, str) else json.dumps(match), "application/json")
|
|
415
506
|
r = self._request(
|
|
416
507
|
"/v2/upload",
|
|
417
508
|
"POST",
|
|
418
|
-
files=
|
|
509
|
+
files=files,
|
|
510
|
+
data={"title": title} if title is not None else None,
|
|
419
511
|
params={"group": group, "visibility": visibility},
|
|
420
512
|
allow_status_codes=(409,),
|
|
421
|
-
category=RateLimitCategory.
|
|
513
|
+
category=RateLimitCategory.UPLOAD,
|
|
514
|
+
auth_key=upload_token,
|
|
422
515
|
)
|
|
423
516
|
if r.status_code == 409 and raise_on_duplicate:
|
|
424
517
|
r.raise_for_status()
|
|
@@ -493,7 +586,8 @@ class BallchasingApi:
|
|
|
493
586
|
name: str,
|
|
494
587
|
player_identification: AnyPlayerIdentification,
|
|
495
588
|
team_identification: AnyTeamIdentification,
|
|
496
|
-
parent: str | None = None
|
|
589
|
+
parent: str | None = None,
|
|
590
|
+
dedup: bool | None = None,
|
|
497
591
|
) -> dict:
|
|
498
592
|
"""
|
|
499
593
|
Use this API to create a new replay group.
|
|
@@ -508,7 +602,9 @@ class BallchasingApi:
|
|
|
508
602
|
every single game. In some tournaments/leagues, teams allow player rotations,
|
|
509
603
|
or a sub can replace another player, in which case use `by-player-clusters`.
|
|
510
604
|
:param parent: if set, the new group will be created as a child of the specified group
|
|
511
|
-
:
|
|
605
|
+
:param dedup: whether to count each game once (API default: True) or every replay, when several replays
|
|
606
|
+
hold the same game.
|
|
607
|
+
:return: the result of the POST request (dict containing group 'id' and 'link').
|
|
512
608
|
"""
|
|
513
609
|
json = {
|
|
514
610
|
"name": name,
|
|
@@ -517,6 +613,8 @@ class BallchasingApi:
|
|
|
517
613
|
}
|
|
518
614
|
if parent is not None:
|
|
519
615
|
json["parent"] = parent
|
|
616
|
+
if dedup is not None:
|
|
617
|
+
json["dedup"] = dedup
|
|
520
618
|
return self._request(f"/groups", "POST", json=json, category=RateLimitCategory.CORE).json()
|
|
521
619
|
|
|
522
620
|
@rate_limited(RateLimitCategory.CORE)
|
|
@@ -524,16 +622,20 @@ class BallchasingApi:
|
|
|
524
622
|
self,
|
|
525
623
|
group_id: str,
|
|
526
624
|
*,
|
|
625
|
+
dedup: bool | None = None,
|
|
527
626
|
typed: bool | None = None
|
|
528
627
|
) -> dict | DeepGroup:
|
|
529
628
|
"""
|
|
530
629
|
This endpoint retrieves a specific replay group info and stats given its id.
|
|
531
630
|
|
|
532
631
|
:param group_id: the group id.
|
|
632
|
+
:param dedup: count each game once (True) or every replay (False) for this request.
|
|
633
|
+
Default (None) uses the group's own dedup setting.
|
|
533
634
|
:param typed: whether to return a typed object (default is self.typed).
|
|
534
635
|
:return: the group info with stats.
|
|
535
636
|
"""
|
|
536
|
-
|
|
637
|
+
params = {"dedup": None if dedup is None else ("on" if dedup else "off")}
|
|
638
|
+
result = self._request(f"/groups/{group_id}", "GET", params=params, category=RateLimitCategory.CORE).json()
|
|
537
639
|
if typed is None:
|
|
538
640
|
typed = self.typed
|
|
539
641
|
if typed:
|
|
@@ -549,6 +651,9 @@ class BallchasingApi:
|
|
|
549
651
|
team_identification: AnyTeamIdentification | None = None,
|
|
550
652
|
parent: str | None = None,
|
|
551
653
|
shared: bool | None = None,
|
|
654
|
+
dedup: bool | None = None,
|
|
655
|
+
assign_replays: Iterable[str] | None = None,
|
|
656
|
+
unassign_replays: Iterable[str] | None = None,
|
|
552
657
|
**params
|
|
553
658
|
) -> None:
|
|
554
659
|
"""
|
|
@@ -559,7 +664,15 @@ class BallchasingApi:
|
|
|
559
664
|
:param team_identification: how to identify the same team ('by-distinct-players', 'by-player-clusters').
|
|
560
665
|
:param parent: parent group id to assign, or "" to unparent.
|
|
561
666
|
:param shared: whether to mark the group as shared.
|
|
667
|
+
:param dedup: count each game once (True) or every replay (False), in this group and its sub-groups.
|
|
668
|
+
:param assign_replays: ids of replays to put directly in this group (yours, or other people's public and
|
|
669
|
+
unlisted ones). They leave the other groups of yours they were directly in.
|
|
670
|
+
:param unassign_replays: ids of replays to take out of your groups.
|
|
562
671
|
:param params: additional parameters for the PATCH request.
|
|
672
|
+
|
|
673
|
+
The API takes at most 150 replays to assign and 300 to unassign per request; longer lists are sent in
|
|
674
|
+
several requests (the other fields go with the first one). The API applies each request completely or not
|
|
675
|
+
at all, but with several requests an error (e.g. an invalid replay id) can leave the earlier ones applied.
|
|
563
676
|
"""
|
|
564
677
|
payload = dict(params)
|
|
565
678
|
if player_identification is not None:
|
|
@@ -570,7 +683,21 @@ class BallchasingApi:
|
|
|
570
683
|
payload["parent"] = parent
|
|
571
684
|
if shared is not None:
|
|
572
685
|
payload["shared"] = shared
|
|
573
|
-
|
|
686
|
+
if dedup is not None:
|
|
687
|
+
payload["dedup"] = dedup
|
|
688
|
+
def to_list(ids): # One id, or any iterable of them (`or` would fail on e.g. a numpy array)
|
|
689
|
+
return [] if ids is None else [ids] if isinstance(ids, str) else list(ids)
|
|
690
|
+
|
|
691
|
+
assign, unassign = to_list(assign_replays), to_list(unassign_replays)
|
|
692
|
+
while True:
|
|
693
|
+
if assign:
|
|
694
|
+
payload["assign_replays"], assign = assign[:MAX_ASSIGN_REPLAYS], assign[MAX_ASSIGN_REPLAYS:]
|
|
695
|
+
if unassign:
|
|
696
|
+
payload["unassign_replays"], unassign = unassign[:MAX_UNASSIGN_REPLAYS], unassign[MAX_UNASSIGN_REPLAYS:]
|
|
697
|
+
self._request(f"/groups/{group_id}", "PATCH", json=payload, category=RateLimitCategory.CORE)
|
|
698
|
+
if not assign and not unassign:
|
|
699
|
+
break
|
|
700
|
+
payload = {}
|
|
574
701
|
|
|
575
702
|
@rate_limited(RateLimitCategory.CORE)
|
|
576
703
|
def delete_group(self, group_id: str) -> None:
|
|
@@ -582,6 +709,47 @@ class BallchasingApi:
|
|
|
582
709
|
"""
|
|
583
710
|
self._request(f"/groups/{group_id}", "DELETE", category=RateLimitCategory.CORE)
|
|
584
711
|
|
|
712
|
+
@rate_limited(RateLimitCategory.CORE)
|
|
713
|
+
def get_group_duplicate_replays(self, group_id: str, *, count: int | None = None) -> Iterator[dict]:
|
|
714
|
+
"""
|
|
715
|
+
List the group's replays that hold a game already held in another of its replays: the replays not counted
|
|
716
|
+
when the group counts each game once. The same whatever the group's dedup setting.
|
|
717
|
+
|
|
718
|
+
:param group_id: the group id.
|
|
719
|
+
:param count: return at most count rows (default: all of them).
|
|
720
|
+
:return: an iterator of {"replay_id": ..., "same_game_as": ...} dicts, sorted by replay_id.
|
|
721
|
+
:raises HTTPError: 422 if the group holds more replays than its owner's limit for stats.
|
|
722
|
+
"""
|
|
723
|
+
params = {"count": math.inf if count is None else count}
|
|
724
|
+
yield from self._iterable_from_request(f"{self.base_url}/groups/{group_id}/duplicate-replays", params,
|
|
725
|
+
page_size=DUPLICATE_REPLAYS_PAGE_SIZE, category=RateLimitCategory.CORE)
|
|
726
|
+
|
|
727
|
+
@rate_limited(RateLimitCategory.CORE)
|
|
728
|
+
def get_group_upload_token(self, group_id: str) -> dict | None:
|
|
729
|
+
"""
|
|
730
|
+
Get the upload token of one of your groups: a key that uploads replays straight into that group
|
|
731
|
+
(pass it as upload_token to upload_replay). Available to Gold patrons and up (others get a 404).
|
|
732
|
+
|
|
733
|
+
:param group_id: the group id.
|
|
734
|
+
:return: a dict with 'token', 'created_at', 'generation' (and 'updated_at' if replaced),
|
|
735
|
+
or None if the group has no token yet (see create_group_upload_token).
|
|
736
|
+
"""
|
|
737
|
+
r = self._request(f"/groups/{group_id}/token", "GET", category=RateLimitCategory.CORE)
|
|
738
|
+
if r.status_code == 204:
|
|
739
|
+
return None
|
|
740
|
+
return r.json()
|
|
741
|
+
|
|
742
|
+
@rate_limited(RateLimitCategory.CORE)
|
|
743
|
+
def create_group_upload_token(self, group_id: str) -> dict:
|
|
744
|
+
"""
|
|
745
|
+
Create the upload token of one of your groups, or REPLACE it: the previous token stops working at once,
|
|
746
|
+
breaking the tools that use it. Available to Gold patrons and up (others get a 404).
|
|
747
|
+
|
|
748
|
+
:param group_id: the group id.
|
|
749
|
+
:return: a dict with 'token', 'created_at', 'generation' (and 'updated_at' if replaced).
|
|
750
|
+
"""
|
|
751
|
+
return self._request(f"/groups/{group_id}/token", "POST", category=RateLimitCategory.CORE).json()
|
|
752
|
+
|
|
585
753
|
def get_group_replays(
|
|
586
754
|
self,
|
|
587
755
|
group: str | dict | BasicGroup,
|
|
@@ -636,6 +804,8 @@ class BallchasingApi:
|
|
|
636
804
|
:param replay_id: the replay id.
|
|
637
805
|
:param path: the path to download the replay to. Can be a file path or a directory.
|
|
638
806
|
:return: the Path to the downloaded file.
|
|
807
|
+
:raises DailyDownloadLimitError: if the daily limit on other people's replay files is reached.
|
|
808
|
+
:raises HTTPError: e.g. 410 if the server lost the replay file (retrying will not help).
|
|
639
809
|
"""
|
|
640
810
|
dest = Path(path)
|
|
641
811
|
if dest.is_dir():
|
|
@@ -653,18 +823,29 @@ class BallchasingApi:
|
|
|
653
823
|
:param group_id: the base group id.
|
|
654
824
|
:param folder: the folder in which to create the group folder.
|
|
655
825
|
:param keep_tree_structure: whether to create new folders for child groups.
|
|
826
|
+
|
|
827
|
+
Replays whose file the server lost (410) are skipped with a warning.
|
|
656
828
|
"""
|
|
657
829
|
folder = Path(folder) / group_id
|
|
658
830
|
if keep_tree_structure:
|
|
659
831
|
folder.mkdir(parents=True, exist_ok=True)
|
|
660
|
-
for child_group in self.get_groups(group=group_id):
|
|
832
|
+
for child_group in self.get_groups(group=group_id, typed=False):
|
|
661
833
|
self.download_group(child_group["id"], folder, keep_tree_structure=True)
|
|
662
|
-
for replay in self.get_replays(group_id=group_id):
|
|
663
|
-
self.
|
|
834
|
+
for replay in self.get_replays(group_id=group_id, typed=False):
|
|
835
|
+
self._download_replay_unless_lost(replay["id"], folder)
|
|
664
836
|
else:
|
|
665
837
|
folder.mkdir(parents=True, exist_ok=True)
|
|
666
|
-
for replay in self.get_group_replays(group_id):
|
|
667
|
-
self.
|
|
838
|
+
for replay in self.get_group_replays(group_id, typed=False):
|
|
839
|
+
self._download_replay_unless_lost(replay["id"], folder)
|
|
840
|
+
|
|
841
|
+
def _download_replay_unless_lost(self, replay_id: str, folder: Path) -> Path | None:
|
|
842
|
+
try:
|
|
843
|
+
return self.download_replay(replay_id, folder)
|
|
844
|
+
except HTTPError as e:
|
|
845
|
+
if e.response is not None and e.response.status_code == 410:
|
|
846
|
+
logger.warning(f"Skipping replay {replay_id}: the server lost its file (410)")
|
|
847
|
+
return None
|
|
848
|
+
raise
|
|
668
849
|
|
|
669
850
|
@rate_limited(RateLimitCategory.CORE)
|
|
670
851
|
def get_maps(self):
|
ballchasing/constants.py
CHANGED
|
@@ -15,7 +15,8 @@ AnyPlaylist: TypeAlias = str | Literal[
|
|
|
15
15
|
"ranked-duels", "ranked-doubles", "ranked-solo-standard", "ranked-standard",
|
|
16
16
|
"snowday", "rocketlabs", "hoops", "rumble", "tournament", "dropshot",
|
|
17
17
|
"ranked-hoops", "ranked-rumble", "ranked-dropshot", "ranked-snowday",
|
|
18
|
-
"dropshot-rumble", "heatseeker", "gridiron", "spooky-cube"
|
|
18
|
+
"dropshot-rumble", "heatseeker", "gridiron", "spooky-cube",
|
|
19
|
+
"anniversary", "third-party", "ghost-hunt", "beach-ball", "spike-rush", "rocket-labs"
|
|
19
20
|
]
|
|
20
21
|
|
|
21
22
|
|
|
@@ -23,14 +24,15 @@ class Playlist:
|
|
|
23
24
|
ALL = (UNRANKED_DUELS, UNRANKED_DOUBLES, UNRANKED_STANDARD, UNRANKED_CHAOS, PRIVATE, SEASON, OFFLINE, LOCAL_LOBBY,
|
|
24
25
|
RANKED_DUELS, RANKED_DOUBLES, RANKED_SOLO_STANDARD, RANKED_STANDARD, SNOWDAY, ROCKETLABS, HOOPS, RUMBLE,
|
|
25
26
|
TOURNAMENT, DROPSHOT, RANKED_HOOPS, RANKED_RUMBLE, RANKED_DROPSHOT, RANKED_SNOWDAY, DROPSHOT_RUMBLE,
|
|
26
|
-
HEATSEEKER, GRIDIRON, SPOOKY_CUBE
|
|
27
|
+
HEATSEEKER, GRIDIRON, SPOOKY_CUBE, ANNIVERSARY, THIRD_PARTY, GHOST_HUNT, BEACH_BALL, SPIKE_RUSH,
|
|
28
|
+
ROCKET_LABS) = _get_literals(AnyPlaylist)
|
|
27
29
|
# Categories as listed on ballchasing:
|
|
28
30
|
RANKED = (RANKED_DUELS, RANKED_DOUBLES, RANKED_STANDARD, RANKED_SOLO_STANDARD)
|
|
29
31
|
UNRANKED = (UNRANKED_DUELS, UNRANKED_DOUBLES, UNRANKED_STANDARD, UNRANKED_CHAOS)
|
|
30
32
|
EXTRA_MODES = (RANKED_HOOPS, RANKED_RUMBLE, RANKED_DROPSHOT, RANKED_SNOWDAY)
|
|
31
|
-
OTHER_MODES = (SNOWDAY, ROCKETLABS, HOOPS, RUMBLE, TOURNAMENT, DROPSHOT,
|
|
32
|
-
GRIDIRON, SPOOKY_CUBE)
|
|
33
|
-
MISC = (PRIVATE, SEASON, OFFLINE, LOCAL_LOBBY)
|
|
33
|
+
OTHER_MODES = (SNOWDAY, ROCKETLABS, HOOPS, RUMBLE, TOURNAMENT, DROPSHOT, DROPSHOT_RUMBLE, HEATSEEKER,
|
|
34
|
+
GRIDIRON, SPOOKY_CUBE, ANNIVERSARY, GHOST_HUNT, BEACH_BALL, SPIKE_RUSH, ROCKET_LABS)
|
|
35
|
+
MISC = (PRIVATE, SEASON, OFFLINE, LOCAL_LOBBY, THIRD_PARTY)
|
|
34
36
|
|
|
35
37
|
|
|
36
38
|
AnyRank: TypeAlias = str | Literal[
|
|
@@ -73,7 +75,7 @@ AnySeason: TypeAlias = str | Literal[
|
|
|
73
75
|
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
|
|
74
76
|
"f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9",
|
|
75
77
|
"f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19",
|
|
76
|
-
"f20", "f21", "f22"
|
|
78
|
+
"f20", "f21", "f22", "f23", "f24"
|
|
77
79
|
]
|
|
78
80
|
|
|
79
81
|
|
|
@@ -85,7 +87,7 @@ class Season:
|
|
|
85
87
|
SEASON_1_FTP, SEASON_2_FTP, SEASON_3_FTP, SEASON_4_FTP, SEASON_5_FTP, SEASON_6_FTP, SEASON_7_FTP,
|
|
86
88
|
SEASON_8_FTP, SEASON_9_FTP, SEASON_10_FTP, SEASON_11_FTP, SEASON_12_FTP, SEASON_13_FTP, SEASON_14_FTP,
|
|
87
89
|
SEASON_15_FTP, SEASON_16_FTP, SEASON_17_FTP, SEASON_18_FTP, SEASON_19_FTP, SEASON_20_FTP, SEASON_21_FTP,
|
|
88
|
-
SEASON_22_FTP
|
|
90
|
+
SEASON_22_FTP, SEASON_23_FTP, SEASON_24_FTP
|
|
89
91
|
) = _get_literals(AnySeason)
|
|
90
92
|
LEGACY = ALL[:14]
|
|
91
93
|
FREE_TO_PLAY = ALL[14:]
|
|
@@ -98,11 +100,12 @@ class MatchResult:
|
|
|
98
100
|
WIN, LOSS = _get_literals(AnyMatchResult)
|
|
99
101
|
|
|
100
102
|
|
|
101
|
-
AnyReplaySortBy: TypeAlias = str | Literal["replay-date", "
|
|
103
|
+
AnyReplaySortBy: TypeAlias = str | Literal["replay-date", "created"]
|
|
102
104
|
|
|
103
105
|
|
|
104
106
|
class ReplaySortBy:
|
|
105
|
-
REPLAY_DATE,
|
|
107
|
+
REPLAY_DATE, CREATED = _get_literals(AnyReplaySortBy)
|
|
108
|
+
UPLOAD_DATE = CREATED # The API used to call it "upload-date", which it now rejects with a 400
|
|
106
109
|
|
|
107
110
|
|
|
108
111
|
AnyGroupSortBy: TypeAlias = str | Literal["created", "name"]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from requests import HTTPError
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class QuotaExceededError(HTTPError):
|
|
5
|
+
"""
|
|
6
|
+
A 429 response that is a quota, not a rate limit: retrying soon will not help, so it is raised instead of retried.
|
|
7
|
+
|
|
8
|
+
Subclasses ``requests.HTTPError``, so existing ``except HTTPError`` handlers still catch it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, message: str, *, response=None, body: dict | None = None):
|
|
12
|
+
super().__init__(message, response=response)
|
|
13
|
+
self.body = body or {}
|
|
14
|
+
retry_after = response.headers.get("Retry-After") if response is not None else None
|
|
15
|
+
self.retry_after: int | None = int(retry_after) if retry_after and retry_after.isdigit() else None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DailyDownloadLimitError(QuotaExceededError):
|
|
19
|
+
"""
|
|
20
|
+
The daily limit on downloading replay files uploaded by other people is reached.
|
|
21
|
+
It resets at 00:00 UTC (``reset``); your own replays are not limited.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, *, response=None, body: dict | None = None):
|
|
25
|
+
super().__init__(message, response=response, body=body)
|
|
26
|
+
self.limit: int | None = self.body.get("limit")
|
|
27
|
+
self.count: int | None = self.body.get("count")
|
|
28
|
+
self.reset: str | None = self.body.get("reset")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class UploadQuotaError(QuotaExceededError):
|
|
32
|
+
"""The account reached its upload quota for the ``window`` ("day" or "week")."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, message: str, *, response=None, body: dict | None = None):
|
|
35
|
+
super().__init__(message, response=response, body=body)
|
|
36
|
+
self.max_uploads: int | None = self.body.get("max_uploads")
|
|
37
|
+
self.window: str | None = self.body.get("window")
|