python-ballchasing 0.5.4__tar.gz → 0.6.0__tar.gz

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.
Files changed (45) hide show
  1. python_ballchasing-0.6.0/MANIFEST.in +1 -0
  2. {python_ballchasing-0.5.4/python_ballchasing.egg-info → python_ballchasing-0.6.0}/PKG-INFO +18 -2
  3. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/README.md +17 -1
  4. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/__init__.py +1 -0
  5. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/api.py +212 -31
  6. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/constants.py +12 -9
  7. python_ballchasing-0.6.0/ballchasing/exceptions.py +37 -0
  8. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/rate_limit.py +13 -1
  9. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/stats_info.tsv +29 -1
  10. python_ballchasing-0.6.0/ballchasing/typed/__init__.py +2 -0
  11. python_ballchasing-0.6.0/ballchasing/typed/_base.py +106 -0
  12. python_ballchasing-0.6.0/ballchasing/typed/deep_group.py +26 -0
  13. python_ballchasing-0.6.0/ballchasing/typed/deep_replay.py +23 -0
  14. python_ballchasing-0.6.0/ballchasing/typed/methods.py +145 -0
  15. python_ballchasing-0.6.0/ballchasing/typed/models.py +954 -0
  16. python_ballchasing-0.6.0/ballchasing/typed/shallow_group.py +3 -0
  17. python_ballchasing-0.6.0/ballchasing/typed/shallow_replay.py +6 -0
  18. python_ballchasing-0.6.0/ballchasing/typed/shared.py +7 -0
  19. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/util/iterators.py +1 -1
  20. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/util/stats.py +3 -3
  21. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/pyproject.toml +6 -1
  22. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0/python_ballchasing.egg-info}/PKG-INFO +18 -2
  23. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/python_ballchasing.egg-info/SOURCES.txt +8 -5
  24. python_ballchasing-0.6.0/python_ballchasing.egg-info/top_level.txt +1 -0
  25. python_ballchasing-0.6.0/tests/data/openapi.json +6217 -0
  26. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/tests/test_fixes.py +4 -4
  27. python_ballchasing-0.6.0/tests/test_openapi.py +548 -0
  28. python_ballchasing-0.5.4/ballchasing/typed/__init__.py +0 -5
  29. python_ballchasing-0.5.4/ballchasing/typed/deep_group.py +0 -440
  30. python_ballchasing-0.5.4/ballchasing/typed/deep_replay.py +0 -286
  31. python_ballchasing-0.5.4/ballchasing/typed/shallow_group.py +0 -18
  32. python_ballchasing-0.5.4/ballchasing/typed/shallow_replay.py +0 -67
  33. python_ballchasing-0.5.4/ballchasing/typed/shared.py +0 -244
  34. python_ballchasing-0.5.4/python_ballchasing.egg-info/top_level.txt +0 -4
  35. python_ballchasing-0.5.4/scripts/get_maps.py +0 -147
  36. python_ballchasing-0.5.4/scripts/make_types.py +0 -194
  37. python_ballchasing-0.5.4/scripts/test.py +0 -52
  38. python_ballchasing-0.5.4/scripts/test_typed.py +0 -88
  39. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/LICENSE +0 -0
  40. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/util/__init__.py +0 -0
  41. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/util/dates.py +0 -0
  42. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/ballchasing/util/replays.py +0 -0
  43. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/python_ballchasing.egg-info/dependency_links.txt +0 -0
  44. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/python_ballchasing.egg-info/requires.txt +0 -0
  45. {python_ballchasing-0.5.4 → python_ballchasing-0.6.0}/setup.cfg +0 -0
@@ -0,0 +1 @@
1
+ include tests/data/openapi.json
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-ballchasing
3
- Version: 0.5.4
3
+ Version: 0.6.0
4
4
  Summary: A Python wrapper around the Ballchasing API
5
5
  Author-email: Rolv-Arild Braaten <rolv_arild@hotmail.com>
6
6
  License: MIT License
@@ -94,7 +94,8 @@ for group in groups:
94
94
  ---
95
95
  Additionally, there's the option to put responses (replays, groups) into typed objects for better type hinting and validation.
96
96
  It also attempts to fill in missing variables not returned by ballchasing (e.g. if a team has 0 goals they won't have a "goal" entry in the response)
97
- The classes can also be found under the `typing` folder and used as a reference for what the API returns.
97
+ The classes are generated from the API's [OpenAPI document](https://ballchasing.com/doc/api/openapi.json) into
98
+ `ballchasing/typed/models.py`, with each field's description, and can be used as a reference for what the API returns.
98
99
 
99
100
  ```python
100
101
  # When creating the API, you can specify a default setting for typing (defaults to False)
@@ -107,3 +108,18 @@ print(replay.blue.players[0].name) # Example of easy attribute access
107
108
  group = api.get_group("g2-vs-bds-hwbf2eyolb", typed=True)
108
109
  print(group.players[0].name)
109
110
  ```
111
+
112
+ Fields the API adds after a release don't break the typed objects: they are kept in the object's `_extra` dict
113
+ (and included by `to_dict()`) until the classes get a field for them.
114
+
115
+ ---
116
+ The client is checked against a snapshot of the [OpenAPI document](https://ballchasing.com/doc/api/openapi.json) in
117
+ `tests/data/openapi.json`. To see what changed in the API since, update the snapshot and regenerate the typed models:
118
+
119
+ ```shell
120
+ python scripts/check_api_spec.py # exits with 1 if something changed
121
+ python scripts/check_api_spec.py --update # then run the tests to see what else the client is missing
122
+ python scripts/generate_models.py # regenerate models.py alone (e.g. after changing the generator)
123
+ ```
124
+
125
+ Methods of the typed classes are written by hand in `ballchasing/typed/methods.py`.
@@ -77,7 +77,8 @@ for group in groups:
77
77
  ---
78
78
  Additionally, there's the option to put responses (replays, groups) into typed objects for better type hinting and validation.
79
79
  It also attempts to fill in missing variables not returned by ballchasing (e.g. if a team has 0 goals they won't have a "goal" entry in the response)
80
- The classes can also be found under the `typing` folder and used as a reference for what the API returns.
80
+ The classes are generated from the API's [OpenAPI document](https://ballchasing.com/doc/api/openapi.json) into
81
+ `ballchasing/typed/models.py`, with each field's description, and can be used as a reference for what the API returns.
81
82
 
82
83
  ```python
83
84
  # When creating the API, you can specify a default setting for typing (defaults to False)
@@ -90,3 +91,18 @@ print(replay.blue.players[0].name) # Example of easy attribute access
90
91
  group = api.get_group("g2-vs-bds-hwbf2eyolb", typed=True)
91
92
  print(group.players[0].name)
92
93
  ```
94
+
95
+ Fields the API adds after a release don't break the typed objects: they are kept in the object's `_extra` dict
96
+ (and included by `to_dict()`) until the classes get a field for them.
97
+
98
+ ---
99
+ The client is checked against a snapshot of the [OpenAPI document](https://ballchasing.com/doc/api/openapi.json) in
100
+ `tests/data/openapi.json`. To see what changed in the API since, update the snapshot and regenerate the typed models:
101
+
102
+ ```shell
103
+ python scripts/check_api_spec.py # exits with 1 if something changed
104
+ python scripts/check_api_spec.py --update # then run the tests to see what else the client is missing
105
+ python scripts/generate_models.py # regenerate models.py alone (e.g. after changing the generator)
106
+ ```
107
+
108
+ Methods of the typed classes are written by hand in `ballchasing/typed/methods.py`.
@@ -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
 
@@ -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.shared import BaseGroup, BasicGroup
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=RateLimitCategory.LIST).json()
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, 200)
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, 200)]
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, 200)
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', 'upload-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(self, replay_id: str, *, typed: bool | None = None) -> dict | DeepReplay:
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", category=RateLimitCategory.CORE).json()
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.CORE)
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
- :return: the result of the POST request (dict containing replay 'id').
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={"file": replay_file},
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.CORE,
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
- :return: the result of the POST request.
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
- result = self._request(f"/groups/{group_id}", "GET", category=RateLimitCategory.CORE).json()
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
- self._request(f"/groups/{group_id}", "PATCH", json=payload, category=RateLimitCategory.CORE)
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.download_replay(replay["id"], folder)
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.download_replay(replay["id"], folder)
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):
@@ -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) = _get_literals(AnyPlaylist)
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, ROCKETLABS, DROPSHOT_RUMBLE, HEATSEEKER,
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", "upload-date"]
103
+ AnyReplaySortBy: TypeAlias = str | Literal["replay-date", "created"]
102
104
 
103
105
 
104
106
  class ReplaySortBy:
105
- REPLAY_DATE, UPLOAD_DATE = _get_literals(AnyReplaySortBy)
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"]