python-ballchasing 0.5.4__py3-none-any.whl → 0.6.1__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 +251 -35
- ballchasing/constants.py +12 -9
- ballchasing/exceptions.py +57 -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 +957 -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.1.dist-info}/METADATA +18 -2
- python_ballchasing-0.6.1.dist-info/RECORD +25 -0
- {python_ballchasing-0.5.4.dist-info → python_ballchasing-0.6.1.dist-info}/WHEEL +1 -1
- python_ballchasing-0.6.1.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.1.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, AccountRestrictedError
|
|
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, RequestException, 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 AccountRestrictedError, 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,17 @@ 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.
|
|
159
|
+
:raises AccountRestrictedError: on a 403 for a restriction put on the account (never retried).
|
|
143
160
|
:raises HTTPError: if the request fails with a status code other than 2xx, 429, or allow_status_codes.
|
|
144
161
|
"""
|
|
145
162
|
cat = RateLimitCategory(category) if category else resolve_category(url_or_endpoint)
|
|
146
|
-
headers = {"Authorization": self.auth_key}
|
|
163
|
+
headers = {"Authorization": self.auth_key if auth_key is None else auth_key}
|
|
147
164
|
url = f"{self.base_url}{url_or_endpoint}" if url_or_endpoint.startswith("/") else url_or_endpoint
|
|
148
165
|
max_retries = 8
|
|
149
166
|
retries = 0
|
|
@@ -152,12 +169,28 @@ class BallchasingApi:
|
|
|
152
169
|
# Wait if global cooldown is active or if proactive pacing applies
|
|
153
170
|
self.rate_limiter.before_request(cat)
|
|
154
171
|
|
|
172
|
+
# Uploaded file objects are read by each attempt: rewind them before retrying
|
|
173
|
+
file_objects = [f[1] if isinstance(f, tuple) else f for f in (params.get("files") or {}).values()]
|
|
174
|
+
file_positions = []
|
|
175
|
+
for f in file_objects:
|
|
176
|
+
try:
|
|
177
|
+
if f.seekable(): # Not e.g. a pipe or a socket: those can't be resent
|
|
178
|
+
file_positions.append((f, f.tell()))
|
|
179
|
+
except (AttributeError, OSError, ValueError):
|
|
180
|
+
pass
|
|
181
|
+
attempt = 0
|
|
182
|
+
|
|
155
183
|
while True:
|
|
156
184
|
try:
|
|
185
|
+
if attempt > 0:
|
|
186
|
+
for f, position in file_positions:
|
|
187
|
+
f.seek(position)
|
|
188
|
+
attempt += 1
|
|
157
189
|
r: Response = self._session.request(method=method, url=url, headers=headers, **params)
|
|
158
190
|
if 200 <= r.status_code < 300 or r.status_code in allow_status_codes:
|
|
159
191
|
return r
|
|
160
192
|
elif r.status_code == 429:
|
|
193
|
+
self._raise_for_quota(r)
|
|
161
194
|
self.rate_limit_count += 1
|
|
162
195
|
rate_limit_retries += 1
|
|
163
196
|
retry_after = r.headers.get("Retry-After", '0')
|
|
@@ -178,6 +211,9 @@ class BallchasingApi:
|
|
|
178
211
|
f"Rate limited at {url} [{cat.value}] ({self.rate_limit_count} total rate limits), retrying in {wait_time:.1f}s..."
|
|
179
212
|
)
|
|
180
213
|
time.sleep(wait_time)
|
|
214
|
+
elif r.status_code == 403:
|
|
215
|
+
self._raise_for_restriction(r)
|
|
216
|
+
r.raise_for_status()
|
|
181
217
|
elif r.status_code in (502, 503, 504):
|
|
182
218
|
raise ConnectionError(f"Server error {r.status_code}: {r.reason or 'Transient gateway error'}")
|
|
183
219
|
else:
|
|
@@ -190,6 +226,35 @@ class BallchasingApi:
|
|
|
190
226
|
time.sleep(s)
|
|
191
227
|
retries += 1
|
|
192
228
|
|
|
229
|
+
@staticmethod
|
|
230
|
+
def _raise_for_quota(r: Response) -> None:
|
|
231
|
+
"""Raise for the 429s that are quotas (not worth retrying soon) rather than rate limits."""
|
|
232
|
+
try:
|
|
233
|
+
body = r.json()
|
|
234
|
+
except (ValueError, RequestException): # Not JSON, or the body could not be read
|
|
235
|
+
return
|
|
236
|
+
if not isinstance(body, dict):
|
|
237
|
+
return
|
|
238
|
+
if "limit" in body and "reset" in body:
|
|
239
|
+
raise DailyDownloadLimitError(
|
|
240
|
+
f"Daily limit on other people's replay files reached ({body.get('count')}/{body.get('limit')}), "
|
|
241
|
+
f"resets at {body.get('reset')}", response=r, body=body)
|
|
242
|
+
if "max_uploads" in body:
|
|
243
|
+
raise UploadQuotaError(
|
|
244
|
+
f"Upload quota reached ({body.get('max_uploads')} per {body.get('window')}): {body.get('error')}",
|
|
245
|
+
response=r, body=body)
|
|
246
|
+
|
|
247
|
+
@staticmethod
|
|
248
|
+
def _raise_for_restriction(r: Response) -> None:
|
|
249
|
+
"""Raise for the 403s that are restrictions on the account (they have a ``code``)."""
|
|
250
|
+
try:
|
|
251
|
+
body = r.json()
|
|
252
|
+
except (ValueError, RequestException): # Not JSON, or the body could not be read
|
|
253
|
+
return
|
|
254
|
+
if isinstance(body, dict) and body.get("code"):
|
|
255
|
+
raise AccountRestrictedError(
|
|
256
|
+
f"403 Account restricted ({body['code']}) for url: {r.url}: {body.get('error')}", response=r, body=body)
|
|
257
|
+
|
|
193
258
|
@rate_limited(RateLimitCategory.PING)
|
|
194
259
|
def ping(self) -> dict:
|
|
195
260
|
"""
|
|
@@ -205,7 +270,8 @@ class BallchasingApi:
|
|
|
205
270
|
self._ping_result = result
|
|
206
271
|
return result
|
|
207
272
|
|
|
208
|
-
def _iterable_from_request(self, url, params, prefetch=True
|
|
273
|
+
def _iterable_from_request(self, url, params, prefetch=True, *, page_size=PAGE_SIZE,
|
|
274
|
+
category=RateLimitCategory.LIST):
|
|
209
275
|
# Shared by get_replays and get_groups.
|
|
210
276
|
# When prefetch=True, the next page is requested in a background
|
|
211
277
|
# thread *before* yielding, so network I/O overlaps with the
|
|
@@ -217,15 +283,15 @@ class BallchasingApi:
|
|
|
217
283
|
return
|
|
218
284
|
|
|
219
285
|
def fetch_page(p):
|
|
220
|
-
return self._request(url, "GET", params=p, category=
|
|
286
|
+
return self._request(url, "GET", params=p, category=category).json()
|
|
221
287
|
|
|
222
288
|
with ThreadPoolExecutor(max_workers=1) as executor:
|
|
223
|
-
params["count"] = min(remaining,
|
|
289
|
+
params["count"] = min(remaining, page_size)
|
|
224
290
|
future = executor.submit(fetch_page, dict(params))
|
|
225
291
|
|
|
226
292
|
while remaining > 0:
|
|
227
293
|
d = future.result()
|
|
228
|
-
batch = d.get("list", [])[:min(remaining,
|
|
294
|
+
batch = d.get("list", [])[:min(remaining, page_size)]
|
|
229
295
|
remaining -= len(batch)
|
|
230
296
|
|
|
231
297
|
next_url = d.get("next")
|
|
@@ -236,7 +302,7 @@ class BallchasingApi:
|
|
|
236
302
|
params["after"] = after_param
|
|
237
303
|
else:
|
|
238
304
|
has_next = False
|
|
239
|
-
params["count"] = min(remaining,
|
|
305
|
+
params["count"] = min(remaining, page_size)
|
|
240
306
|
if prefetch and has_next:
|
|
241
307
|
future = executor.submit(fetch_page, dict(params))
|
|
242
308
|
|
|
@@ -270,6 +336,7 @@ class BallchasingApi:
|
|
|
270
336
|
count: int = 150,
|
|
271
337
|
sort_by: AnyReplaySortBy | None = None,
|
|
272
338
|
sort_dir: AnySortDir = SortDir.DESCENDING,
|
|
339
|
+
roulette: bool = False,
|
|
273
340
|
deep: bool = False,
|
|
274
341
|
typed: bool | None = None,
|
|
275
342
|
deduplicate: bool = False,
|
|
@@ -279,10 +346,11 @@ class BallchasingApi:
|
|
|
279
346
|
This endpoint lets you filter and retrieve replays. The implementation returns an iterator.
|
|
280
347
|
|
|
281
348
|
:param title: filter replays by title.
|
|
282
|
-
:param player_name: filter replays by a player’s name.
|
|
349
|
+
:param player_name: filter replays by a player’s name (word or word prefix, case insensitive).
|
|
350
|
+
Quote it (e.g. '"Can't Fly"') to match the exact name. Multiple names: replays with all.
|
|
283
351
|
:param player_id: filter replays by a player’s platform id in the $platform:$id, e.g. steam:76561198141161044,
|
|
284
352
|
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.
|
|
353
|
+
:param playlist: filter replays by one or more playlists. Prefix one with "!" to exclude it (e.g. "!private").
|
|
286
354
|
:param season: filter replays by season. Must be a number between 1 and 14 (for old seasons)
|
|
287
355
|
or f1, f2, … for the new free to play seasons
|
|
288
356
|
:param match_result: filter your replays by result.
|
|
@@ -290,7 +358,8 @@ class BallchasingApi:
|
|
|
290
358
|
:param max_rank: filter your replays based on players maximum rank.
|
|
291
359
|
:param pro: only include replays containing at least one pro player.
|
|
292
360
|
:param uploader: only include replays uploaded by the specified user. Accepts either the
|
|
293
|
-
numerical 76*************44 steam id, or the special value 'me'
|
|
361
|
+
numerical 76*************44 steam id, or the special value 'me'.
|
|
362
|
+
'is:player' keeps the replays whose uploader played in them, '!is:player' the others
|
|
294
363
|
:param group_id: only include replays belonging to the specified group. This only include replays immediately
|
|
295
364
|
under the specified group, but not replays in child groups
|
|
296
365
|
:param map_id: only include replays in the specified map. Check get_maps for the list of valid map codes
|
|
@@ -304,8 +373,10 @@ class BallchasingApi:
|
|
|
304
373
|
RFC3339 format, e.g. '2020-01-02T15:00:05+01:00'
|
|
305
374
|
:param count: returns at most count replays. Since the implementation uses an iterator it supports iterating
|
|
306
375
|
past the limit of 200 set by the API
|
|
307
|
-
:param sort_by: sort replays according the selected field ('replay-date', '
|
|
376
|
+
:param sort_by: sort replays according the selected field ('replay-date', 'created').
|
|
377
|
+
The former name 'upload-date' is accepted and sent as 'created'.
|
|
308
378
|
:param sort_dir: sort direction ('asc', 'desc')
|
|
379
|
+
:param roulette: return one random replay among the matching ones (ignores count).
|
|
309
380
|
:param deep: whether to get full stats for each replay (will be much slower).
|
|
310
381
|
:param typed: whether to return a typed object (default is self.typed).
|
|
311
382
|
:param deduplicate: whether to deduplicate replays that seem to be the same game.
|
|
@@ -313,13 +384,16 @@ class BallchasingApi:
|
|
|
313
384
|
:return: an iterator over the replays returned by the API.
|
|
314
385
|
"""
|
|
315
386
|
url = f"{self.base_url}/replays"
|
|
387
|
+
if sort_by == "upload-date":
|
|
388
|
+
sort_by = "created" # Renamed in the API, "upload-date" now gives a 400
|
|
316
389
|
params = {"title": title, "player-name": player_name, "player-id": player_id, "playlist": playlist,
|
|
317
390
|
"season": season, "match-result": match_result, "min-rank": min_rank, "max-rank": max_rank,
|
|
318
391
|
"pro": str(pro).lower() if isinstance(pro, bool) else pro, "uploader": uploader, "group": group_id,
|
|
319
392
|
"map": map_id,
|
|
320
393
|
"created-before": to_rfc3339(created_before), "created-after": to_rfc3339(created_after),
|
|
321
394
|
"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
|
|
395
|
+
"count": count, "sort-by": sort_by, "sort-dir": sort_dir,
|
|
396
|
+
"roulette": "true" if roulette else None}
|
|
323
397
|
|
|
324
398
|
if typed is None:
|
|
325
399
|
typed = self.typed
|
|
@@ -332,7 +406,7 @@ class BallchasingApi:
|
|
|
332
406
|
# Deep replays have match and replay IDs to deduplicate with. For shallow replays we check dates.
|
|
333
407
|
iterator = deduplicator(iterator, check_dates=not deep)
|
|
334
408
|
if deep:
|
|
335
|
-
iterator = (self.get_replay(r["id"]) for r in iterator)
|
|
409
|
+
iterator = (self.get_replay(r["id"], typed=False) for r in iterator)
|
|
336
410
|
if typed:
|
|
337
411
|
if deep:
|
|
338
412
|
iterator = (DeepReplay(**r) for r in iterator)
|
|
@@ -341,15 +415,24 @@ class BallchasingApi:
|
|
|
341
415
|
yield from iterator
|
|
342
416
|
|
|
343
417
|
@rate_limited(RateLimitCategory.CORE)
|
|
344
|
-
def get_replay(
|
|
418
|
+
def get_replay(
|
|
419
|
+
self,
|
|
420
|
+
replay_id: str,
|
|
421
|
+
*,
|
|
422
|
+
group: str | None = None,
|
|
423
|
+
typed: bool | None = None
|
|
424
|
+
) -> dict | DeepReplay:
|
|
345
425
|
"""
|
|
346
426
|
Retrieve a given replay’s details and stats.
|
|
347
427
|
|
|
348
428
|
:param replay_id: the replay id.
|
|
429
|
+
:param group: id of a shared group holding the replay. Its owner's replays in it can then be read whatever
|
|
430
|
+
their visibility, as on the group's page.
|
|
349
431
|
:param typed: whether to return a typed object (default is self.typed).
|
|
350
432
|
:return: the result of the GET request.
|
|
351
433
|
"""
|
|
352
|
-
result = self._request(f"/replays/{replay_id}", "GET",
|
|
434
|
+
result = self._request(f"/replays/{replay_id}", "GET", params={"group": group},
|
|
435
|
+
category=RateLimitCategory.CORE).json()
|
|
353
436
|
if typed is None:
|
|
354
437
|
typed = self.typed
|
|
355
438
|
if typed:
|
|
@@ -384,13 +467,16 @@ class BallchasingApi:
|
|
|
384
467
|
payload["group"] = group
|
|
385
468
|
self._request(f"/replays/{replay_id}", "PATCH", json=payload, category=RateLimitCategory.CORE)
|
|
386
469
|
|
|
387
|
-
@rate_limited(RateLimitCategory.
|
|
470
|
+
@rate_limited(RateLimitCategory.UPLOAD)
|
|
388
471
|
def upload_replay(
|
|
389
472
|
self,
|
|
390
473
|
replay_file: str | Path | BinaryIO,
|
|
391
474
|
*,
|
|
392
475
|
visibility: AnyVisibility | None = None,
|
|
393
476
|
group: str | None = None,
|
|
477
|
+
title: str | None = None,
|
|
478
|
+
match: dict | str | None = None,
|
|
479
|
+
upload_token: str | None = None,
|
|
394
480
|
raise_on_duplicate: bool = False,
|
|
395
481
|
) -> dict:
|
|
396
482
|
"""
|
|
@@ -399,10 +485,17 @@ class BallchasingApi:
|
|
|
399
485
|
:param replay_file: replay file to upload. Can be a file path (str or Path) or a file-like object.
|
|
400
486
|
:param visibility: to set the visibility of the uploaded replay ('public', 'unlisted', 'private').
|
|
401
487
|
:param group: to upload the replay to an existing group.
|
|
488
|
+
:param title: title of the new replay (at most 1024 characters; an invalid one is silently ignored by the API).
|
|
489
|
+
:param match: the game's match data, as Psyonix's match history API returns it (an RLAPI `Match` object,
|
|
490
|
+
as a dict or JSON string). It needs `MatchGUID`; an invalid value is ignored by the API.
|
|
491
|
+
:param upload_token: a group upload token (starts with "g/") to authenticate the upload with instead of the
|
|
492
|
+
API key: the replay goes to that group. See get_group_upload_token.
|
|
402
493
|
:param raise_on_duplicate: if True, raise an HTTPError when a 409 Conflict (duplicate replay)
|
|
403
494
|
is returned. If False (default), returns the API response dict with the
|
|
404
|
-
existing replay id.
|
|
405
|
-
|
|
495
|
+
existing replay id. (With a group upload token, a replay its owner already has
|
|
496
|
+
outside the group gives a 409 without an id.)
|
|
497
|
+
:return: the result of the POST request (dict containing replay 'id' and 'location').
|
|
498
|
+
:raises UploadQuotaError: if the account reached its upload quota.
|
|
406
499
|
"""
|
|
407
500
|
if isinstance(replay_file, (str, Path)):
|
|
408
501
|
with open(replay_file, "rb") as f:
|
|
@@ -410,15 +503,30 @@ class BallchasingApi:
|
|
|
410
503
|
f,
|
|
411
504
|
visibility=visibility,
|
|
412
505
|
group=group,
|
|
506
|
+
title=title,
|
|
507
|
+
match=match,
|
|
508
|
+
upload_token=upload_token,
|
|
413
509
|
raise_on_duplicate=raise_on_duplicate,
|
|
414
510
|
)
|
|
511
|
+
if isinstance(replay_file, tuple): # A requests-style (file name, file object[, content type])
|
|
512
|
+
replay_file, file_name = replay_file[1], replay_file[0]
|
|
513
|
+
else:
|
|
514
|
+
file_name = getattr(replay_file, "name", None)
|
|
515
|
+
file_name = os.path.basename(file_name) if isinstance(file_name, str) else ""
|
|
516
|
+
if not file_name.endswith(".replay"): # The API refuses other file names (e.g. for a BytesIO)
|
|
517
|
+
file_name = "upload.replay"
|
|
518
|
+
files = {"file": (file_name, replay_file)}
|
|
519
|
+
if match is not None:
|
|
520
|
+
files["match"] = (None, match if isinstance(match, str) else json.dumps(match), "application/json")
|
|
415
521
|
r = self._request(
|
|
416
522
|
"/v2/upload",
|
|
417
523
|
"POST",
|
|
418
|
-
files=
|
|
524
|
+
files=files,
|
|
525
|
+
data={"title": title} if title is not None else None,
|
|
419
526
|
params={"group": group, "visibility": visibility},
|
|
420
527
|
allow_status_codes=(409,),
|
|
421
|
-
category=RateLimitCategory.
|
|
528
|
+
category=RateLimitCategory.UPLOAD,
|
|
529
|
+
auth_key=upload_token,
|
|
422
530
|
)
|
|
423
531
|
if r.status_code == 409 and raise_on_duplicate:
|
|
424
532
|
r.raise_for_status()
|
|
@@ -493,7 +601,8 @@ class BallchasingApi:
|
|
|
493
601
|
name: str,
|
|
494
602
|
player_identification: AnyPlayerIdentification,
|
|
495
603
|
team_identification: AnyTeamIdentification,
|
|
496
|
-
parent: str | None = None
|
|
604
|
+
parent: str | None = None,
|
|
605
|
+
dedup: bool | None = None,
|
|
497
606
|
) -> dict:
|
|
498
607
|
"""
|
|
499
608
|
Use this API to create a new replay group.
|
|
@@ -508,7 +617,9 @@ class BallchasingApi:
|
|
|
508
617
|
every single game. In some tournaments/leagues, teams allow player rotations,
|
|
509
618
|
or a sub can replace another player, in which case use `by-player-clusters`.
|
|
510
619
|
:param parent: if set, the new group will be created as a child of the specified group
|
|
511
|
-
:
|
|
620
|
+
:param dedup: whether to count each game once (API default: True) or every replay, when several replays
|
|
621
|
+
hold the same game.
|
|
622
|
+
:return: the result of the POST request (dict containing group 'id' and 'link').
|
|
512
623
|
"""
|
|
513
624
|
json = {
|
|
514
625
|
"name": name,
|
|
@@ -517,6 +628,8 @@ class BallchasingApi:
|
|
|
517
628
|
}
|
|
518
629
|
if parent is not None:
|
|
519
630
|
json["parent"] = parent
|
|
631
|
+
if dedup is not None:
|
|
632
|
+
json["dedup"] = dedup
|
|
520
633
|
return self._request(f"/groups", "POST", json=json, category=RateLimitCategory.CORE).json()
|
|
521
634
|
|
|
522
635
|
@rate_limited(RateLimitCategory.CORE)
|
|
@@ -524,16 +637,20 @@ class BallchasingApi:
|
|
|
524
637
|
self,
|
|
525
638
|
group_id: str,
|
|
526
639
|
*,
|
|
640
|
+
dedup: bool | None = None,
|
|
527
641
|
typed: bool | None = None
|
|
528
642
|
) -> dict | DeepGroup:
|
|
529
643
|
"""
|
|
530
644
|
This endpoint retrieves a specific replay group info and stats given its id.
|
|
531
645
|
|
|
532
646
|
:param group_id: the group id.
|
|
647
|
+
:param dedup: count each game once (True) or every replay (False) for this request.
|
|
648
|
+
Default (None) uses the group's own dedup setting.
|
|
533
649
|
:param typed: whether to return a typed object (default is self.typed).
|
|
534
650
|
:return: the group info with stats.
|
|
535
651
|
"""
|
|
536
|
-
|
|
652
|
+
params = {"dedup": None if dedup is None else ("on" if dedup else "off")}
|
|
653
|
+
result = self._request(f"/groups/{group_id}", "GET", params=params, category=RateLimitCategory.CORE).json()
|
|
537
654
|
if typed is None:
|
|
538
655
|
typed = self.typed
|
|
539
656
|
if typed:
|
|
@@ -549,6 +666,9 @@ class BallchasingApi:
|
|
|
549
666
|
team_identification: AnyTeamIdentification | None = None,
|
|
550
667
|
parent: str | None = None,
|
|
551
668
|
shared: bool | None = None,
|
|
669
|
+
dedup: bool | None = None,
|
|
670
|
+
assign_replays: Iterable[str] | None = None,
|
|
671
|
+
unassign_replays: Iterable[str] | None = None,
|
|
552
672
|
**params
|
|
553
673
|
) -> None:
|
|
554
674
|
"""
|
|
@@ -559,7 +679,15 @@ class BallchasingApi:
|
|
|
559
679
|
:param team_identification: how to identify the same team ('by-distinct-players', 'by-player-clusters').
|
|
560
680
|
:param parent: parent group id to assign, or "" to unparent.
|
|
561
681
|
:param shared: whether to mark the group as shared.
|
|
682
|
+
:param dedup: count each game once (True) or every replay (False), in this group and its sub-groups.
|
|
683
|
+
:param assign_replays: ids of replays to put directly in this group (yours, or other people's public and
|
|
684
|
+
unlisted ones). They leave the other groups of yours they were directly in.
|
|
685
|
+
:param unassign_replays: ids of replays to take out of your groups.
|
|
562
686
|
:param params: additional parameters for the PATCH request.
|
|
687
|
+
|
|
688
|
+
The API takes at most 150 replays to assign and 300 to unassign per request; longer lists are sent in
|
|
689
|
+
several requests (the other fields go with the first one). The API applies each request completely or not
|
|
690
|
+
at all, but with several requests an error (e.g. an invalid replay id) can leave the earlier ones applied.
|
|
563
691
|
"""
|
|
564
692
|
payload = dict(params)
|
|
565
693
|
if player_identification is not None:
|
|
@@ -570,7 +698,21 @@ class BallchasingApi:
|
|
|
570
698
|
payload["parent"] = parent
|
|
571
699
|
if shared is not None:
|
|
572
700
|
payload["shared"] = shared
|
|
573
|
-
|
|
701
|
+
if dedup is not None:
|
|
702
|
+
payload["dedup"] = dedup
|
|
703
|
+
def to_list(ids): # One id, or any iterable of them (`or` would fail on e.g. a numpy array)
|
|
704
|
+
return [] if ids is None else [ids] if isinstance(ids, str) else list(ids)
|
|
705
|
+
|
|
706
|
+
assign, unassign = to_list(assign_replays), to_list(unassign_replays)
|
|
707
|
+
while True:
|
|
708
|
+
if assign:
|
|
709
|
+
payload["assign_replays"], assign = assign[:MAX_ASSIGN_REPLAYS], assign[MAX_ASSIGN_REPLAYS:]
|
|
710
|
+
if unassign:
|
|
711
|
+
payload["unassign_replays"], unassign = unassign[:MAX_UNASSIGN_REPLAYS], unassign[MAX_UNASSIGN_REPLAYS:]
|
|
712
|
+
self._request(f"/groups/{group_id}", "PATCH", json=payload, category=RateLimitCategory.CORE)
|
|
713
|
+
if not assign and not unassign:
|
|
714
|
+
break
|
|
715
|
+
payload = {}
|
|
574
716
|
|
|
575
717
|
@rate_limited(RateLimitCategory.CORE)
|
|
576
718
|
def delete_group(self, group_id: str) -> None:
|
|
@@ -582,6 +724,47 @@ class BallchasingApi:
|
|
|
582
724
|
"""
|
|
583
725
|
self._request(f"/groups/{group_id}", "DELETE", category=RateLimitCategory.CORE)
|
|
584
726
|
|
|
727
|
+
@rate_limited(RateLimitCategory.CORE)
|
|
728
|
+
def get_group_duplicate_replays(self, group_id: str, *, count: int | None = None) -> Iterator[dict]:
|
|
729
|
+
"""
|
|
730
|
+
List the group's replays that hold a game already held in another of its replays: the replays not counted
|
|
731
|
+
when the group counts each game once. The same whatever the group's dedup setting.
|
|
732
|
+
|
|
733
|
+
:param group_id: the group id.
|
|
734
|
+
:param count: return at most count rows (default: all of them).
|
|
735
|
+
:return: an iterator of {"replay_id": ..., "same_game_as": ...} dicts, sorted by replay_id.
|
|
736
|
+
:raises HTTPError: 422 if the group holds more replays than its owner's limit for stats.
|
|
737
|
+
"""
|
|
738
|
+
params = {"count": math.inf if count is None else count}
|
|
739
|
+
yield from self._iterable_from_request(f"{self.base_url}/groups/{group_id}/duplicate-replays", params,
|
|
740
|
+
page_size=DUPLICATE_REPLAYS_PAGE_SIZE, category=RateLimitCategory.CORE)
|
|
741
|
+
|
|
742
|
+
@rate_limited(RateLimitCategory.CORE)
|
|
743
|
+
def get_group_upload_token(self, group_id: str) -> dict | None:
|
|
744
|
+
"""
|
|
745
|
+
Get the upload token of one of your groups: a key that uploads replays straight into that group
|
|
746
|
+
(pass it as upload_token to upload_replay). 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
|
+
or None if the group has no token yet (see create_group_upload_token).
|
|
751
|
+
"""
|
|
752
|
+
r = self._request(f"/groups/{group_id}/token", "GET", category=RateLimitCategory.CORE)
|
|
753
|
+
if r.status_code == 204:
|
|
754
|
+
return None
|
|
755
|
+
return r.json()
|
|
756
|
+
|
|
757
|
+
@rate_limited(RateLimitCategory.CORE)
|
|
758
|
+
def create_group_upload_token(self, group_id: str) -> dict:
|
|
759
|
+
"""
|
|
760
|
+
Create the upload token of one of your groups, or REPLACE it: the previous token stops working at once,
|
|
761
|
+
breaking the tools that use it. Available to Gold patrons and up (others get a 404).
|
|
762
|
+
|
|
763
|
+
:param group_id: the group id.
|
|
764
|
+
:return: a dict with 'token', 'created_at', 'generation' (and 'updated_at' if replaced).
|
|
765
|
+
"""
|
|
766
|
+
return self._request(f"/groups/{group_id}/token", "POST", category=RateLimitCategory.CORE).json()
|
|
767
|
+
|
|
585
768
|
def get_group_replays(
|
|
586
769
|
self,
|
|
587
770
|
group: str | dict | BasicGroup,
|
|
@@ -636,6 +819,8 @@ class BallchasingApi:
|
|
|
636
819
|
:param replay_id: the replay id.
|
|
637
820
|
:param path: the path to download the replay to. Can be a file path or a directory.
|
|
638
821
|
:return: the Path to the downloaded file.
|
|
822
|
+
:raises DailyDownloadLimitError: if the daily limit on other people's replay files is reached.
|
|
823
|
+
:raises HTTPError: e.g. 410 if the server lost the replay file (retrying will not help).
|
|
639
824
|
"""
|
|
640
825
|
dest = Path(path)
|
|
641
826
|
if dest.is_dir():
|
|
@@ -653,18 +838,49 @@ class BallchasingApi:
|
|
|
653
838
|
:param group_id: the base group id.
|
|
654
839
|
:param folder: the folder in which to create the group folder.
|
|
655
840
|
:param keep_tree_structure: whether to create new folders for child groups.
|
|
841
|
+
|
|
842
|
+
Replays whose file the server lost (410) are skipped with a warning. If the account's downloads of other
|
|
843
|
+
players' replays are suspended (403 ``files_suspended``), the rest of those are skipped without requesting
|
|
844
|
+
them, and the account's own replays in the group still download.
|
|
656
845
|
"""
|
|
657
|
-
|
|
846
|
+
state = {"suspended": False, "skipped": 0}
|
|
847
|
+
self._download_group(group_id, Path(folder), keep_tree_structure, state)
|
|
848
|
+
if state["skipped"]:
|
|
849
|
+
logger.warning(f"Skipped {state['skipped']} replays of other players in group {group_id}: downloads of "
|
|
850
|
+
f"those are suspended for this account (403 files_suspended)")
|
|
851
|
+
|
|
852
|
+
def _download_group(self, group_id: str, folder: Path, keep_tree_structure: bool, state: dict):
|
|
853
|
+
folder = folder / group_id
|
|
854
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
658
855
|
if keep_tree_structure:
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
for replay in self.get_replays(group_id=group_id):
|
|
663
|
-
self.download_replay(replay["id"], folder)
|
|
856
|
+
for child_group in self.get_groups(group=group_id, typed=False):
|
|
857
|
+
self._download_group(child_group["id"], folder, True, state)
|
|
858
|
+
replays = self.get_replays(group_id=group_id, typed=False)
|
|
664
859
|
else:
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
860
|
+
replays = self.get_group_replays(group_id, typed=False)
|
|
861
|
+
for replay in replays:
|
|
862
|
+
self._download_group_replay(replay, folder, state)
|
|
863
|
+
|
|
864
|
+
def _download_group_replay(self, replay: dict, folder: Path, state: dict) -> Path | None:
|
|
865
|
+
replay_id = replay["id"]
|
|
866
|
+
if state["suspended"]:
|
|
867
|
+
# Other players' replays would be refused too: don't send them. Without a ping (do_initial_ping=False),
|
|
868
|
+
# the account's own replays can't be told apart, so those are skipped as well.
|
|
869
|
+
steam_id = (self._ping_result or {}).get("steam_id")
|
|
870
|
+
if steam_id is None or (replay.get("uploader") or {}).get("steam_id") != steam_id:
|
|
871
|
+
state["skipped"] += 1
|
|
872
|
+
return None
|
|
873
|
+
try:
|
|
874
|
+
return self.download_replay(replay_id, folder)
|
|
875
|
+
except HTTPError as e:
|
|
876
|
+
if e.response is not None and e.response.status_code == 410:
|
|
877
|
+
logger.warning(f"Skipping replay {replay_id}: the server lost its file (410)")
|
|
878
|
+
return None
|
|
879
|
+
if isinstance(e, AccountRestrictedError) and e.code == AccountRestrictedError.FILES_SUSPENDED:
|
|
880
|
+
state["suspended"] = True
|
|
881
|
+
state["skipped"] += 1
|
|
882
|
+
return None
|
|
883
|
+
raise
|
|
668
884
|
|
|
669
885
|
@rate_limited(RateLimitCategory.CORE)
|
|
670
886
|
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"]
|