python-ballchasing 0.6.0__tar.gz → 0.6.1__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 (34) hide show
  1. {python_ballchasing-0.6.0/python_ballchasing.egg-info → python_ballchasing-0.6.1}/PKG-INFO +1 -1
  2. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/__init__.py +1 -1
  3. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/api.py +49 -14
  4. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/exceptions.py +20 -0
  5. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/models.py +8 -5
  6. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/pyproject.toml +1 -1
  7. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1/python_ballchasing.egg-info}/PKG-INFO +1 -1
  8. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/tests/data/openapi.json +129 -7
  9. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/tests/test_openapi.py +88 -1
  10. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/LICENSE +0 -0
  11. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/MANIFEST.in +0 -0
  12. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/README.md +0 -0
  13. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/constants.py +0 -0
  14. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/rate_limit.py +0 -0
  15. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/stats_info.tsv +0 -0
  16. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/__init__.py +0 -0
  17. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/_base.py +0 -0
  18. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/deep_group.py +0 -0
  19. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/deep_replay.py +0 -0
  20. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/methods.py +0 -0
  21. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/shallow_group.py +0 -0
  22. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/shallow_replay.py +0 -0
  23. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/typed/shared.py +0 -0
  24. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/util/__init__.py +0 -0
  25. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/util/dates.py +0 -0
  26. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/util/iterators.py +0 -0
  27. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/util/replays.py +0 -0
  28. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/ballchasing/util/stats.py +0 -0
  29. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/python_ballchasing.egg-info/SOURCES.txt +0 -0
  30. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/python_ballchasing.egg-info/dependency_links.txt +0 -0
  31. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/python_ballchasing.egg-info/requires.txt +0 -0
  32. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/python_ballchasing.egg-info/top_level.txt +0 -0
  33. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/setup.cfg +0 -0
  34. {python_ballchasing-0.6.0 → python_ballchasing-0.6.1}/tests/test_fixes.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-ballchasing
3
- Version: 0.6.0
3
+ Version: 0.6.1
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
@@ -50,7 +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
+ from .exceptions import QuotaExceededError, DailyDownloadLimitError, UploadQuotaError, AccountRestrictedError
54
54
 
55
55
  Api = BallchasingApi # For importing like `import ballchasing; api = ballchasing.Api`
56
56
 
@@ -10,11 +10,11 @@ from typing import BinaryIO, Iterable, Iterator
10
10
  from urllib.parse import parse_qs, urlparse
11
11
 
12
12
  from requests import sessions, Response
13
- from requests.exceptions import ConnectionError, HTTPError, Timeout
13
+ from requests.exceptions import ConnectionError, HTTPError, RequestException, Timeout
14
14
 
15
15
  from ballchasing.constants import GroupSortBy, SortDir, AnySeason, AnyRank, AnyReplaySortBy, AnySortDir, \
16
16
  AnyVisibility, AnyGroupSortBy, AnyPlayerIdentification, AnyTeamIdentification, AnyMatchResult, NoneOrMore
17
- from ballchasing.exceptions import DailyDownloadLimitError, UploadQuotaError
17
+ from ballchasing.exceptions import AccountRestrictedError, DailyDownloadLimitError, UploadQuotaError
18
18
  from ballchasing.rate_limit import RateLimiter, RateLimitCategory, resolve_category, rate_limited
19
19
  from ballchasing.typed import DeepReplay, ShallowReplay, DeepGroup, ShallowGroup
20
20
  from .typed.models import BaseGroup, BasicGroup
@@ -156,6 +156,7 @@ class BallchasingApi:
156
156
  :raises ConnectionError: if the connection fails after max retries.
157
157
  :raises DailyDownloadLimitError: on a 429 for the daily limit on other people's replay files.
158
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).
159
160
  :raises HTTPError: if the request fails with a status code other than 2xx, 429, or allow_status_codes.
160
161
  """
161
162
  cat = RateLimitCategory(category) if category else resolve_category(url_or_endpoint)
@@ -210,6 +211,9 @@ class BallchasingApi:
210
211
  f"Rate limited at {url} [{cat.value}] ({self.rate_limit_count} total rate limits), retrying in {wait_time:.1f}s..."
211
212
  )
212
213
  time.sleep(wait_time)
214
+ elif r.status_code == 403:
215
+ self._raise_for_restriction(r)
216
+ r.raise_for_status()
213
217
  elif r.status_code in (502, 503, 504):
214
218
  raise ConnectionError(f"Server error {r.status_code}: {r.reason or 'Transient gateway error'}")
215
219
  else:
@@ -227,7 +231,7 @@ class BallchasingApi:
227
231
  """Raise for the 429s that are quotas (not worth retrying soon) rather than rate limits."""
228
232
  try:
229
233
  body = r.json()
230
- except ValueError:
234
+ except (ValueError, RequestException): # Not JSON, or the body could not be read
231
235
  return
232
236
  if not isinstance(body, dict):
233
237
  return
@@ -240,6 +244,17 @@ class BallchasingApi:
240
244
  f"Upload quota reached ({body.get('max_uploads')} per {body.get('window')}): {body.get('error')}",
241
245
  response=r, body=body)
242
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
+
243
258
  @rate_limited(RateLimitCategory.PING)
244
259
  def ping(self) -> dict:
245
260
  """
@@ -824,27 +839,47 @@ class BallchasingApi:
824
839
  :param folder: the folder in which to create the group folder.
825
840
  :param keep_tree_structure: whether to create new folders for child groups.
826
841
 
827
- Replays whose file the server lost (410) are skipped with a warning.
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.
828
845
  """
829
- folder = Path(folder) / group_id
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)
830
855
  if keep_tree_structure:
831
- folder.mkdir(parents=True, exist_ok=True)
832
856
  for child_group in self.get_groups(group=group_id, typed=False):
833
- self.download_group(child_group["id"], folder, keep_tree_structure=True)
834
- for replay in self.get_replays(group_id=group_id, typed=False):
835
- self._download_replay_unless_lost(replay["id"], folder)
857
+ self._download_group(child_group["id"], folder, True, state)
858
+ replays = self.get_replays(group_id=group_id, typed=False)
836
859
  else:
837
- folder.mkdir(parents=True, exist_ok=True)
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:
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
842
873
  try:
843
874
  return self.download_replay(replay_id, folder)
844
875
  except HTTPError as e:
845
876
  if e.response is not None and e.response.status_code == 410:
846
877
  logger.warning(f"Skipping replay {replay_id}: the server lost its file (410)")
847
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
848
883
  raise
849
884
 
850
885
  @rate_limited(RateLimitCategory.CORE)
@@ -35,3 +35,23 @@ class UploadQuotaError(QuotaExceededError):
35
35
  super().__init__(message, response=response, body=body)
36
36
  self.max_uploads: int | None = self.body.get("max_uploads")
37
37
  self.window: str | None = self.body.get("window")
38
+
39
+
40
+ class AccountRestrictedError(HTTPError):
41
+ """
42
+ A 403 for a restriction ballchasing put on the account (``code``). Do not retry while it is active.
43
+
44
+ - ``account_banned``: every API call is refused, uploads included.
45
+ - ``api_access_blocked``: reads are refused (except the ping); writes and uploads still work.
46
+ - ``files_suspended``: replay files uploaded by other players are refused; your own still download.
47
+
48
+ Subclasses ``requests.HTTPError``, so existing ``except HTTPError`` handlers still catch it.
49
+ """
50
+ ACCOUNT_BANNED = "account_banned"
51
+ API_ACCESS_BLOCKED = "api_access_blocked"
52
+ FILES_SUSPENDED = "files_suspended"
53
+
54
+ def __init__(self, message: str, *, response=None, body: dict | None = None):
55
+ super().__init__(message, response=response)
56
+ self.body = body or {}
57
+ self.code: str | None = self.body.get("code")
@@ -843,13 +843,16 @@ class ReplayFileDownloads(_BaseModel, _DictToTypeMixin):
843
843
  Downloads of original replay files uploaded by **other accounts**, today (UTC), against the account's daily
844
844
  limit (see Download a replay file). One count for the API (`GET /api/replays/{id}/file`), the site's download
845
845
  button and group zips together; each replay counts once a day, and the replays the account uploaded never count.
846
- Once `used` reaches `max`, downloading a replay not downloaded yet today answers 429 until `resets_at`. Reading
847
- it (pinging) never changes it.
846
+ Once `used` reaches a `max` above 0, downloading a replay not downloaded yet today answers 429 until
847
+ `resets_at`. A `max` of 0 means downloading other accounts' replays is turned off for the account: those
848
+ downloads answer 403, also after `resets_at`. Reading it (pinging) never changes it.
848
849
  """
849
- #: Distinct replays of other accounts downloaded today (UTC). Can be above `max` after the account's tier went
850
- #: down during the day.
850
+ #: Distinct replays of other accounts downloaded today (UTC). Can be above `max` after the account's limit went
851
+ #: down during the day. For an account that shares its daily limit with other accounts, the distinct replays
852
+ #: they downloaded together today.
851
853
  used: int = 0
852
- #: The account's daily limit (absent when unlimited).
854
+ #: The account's daily limit (absent when unlimited; `0` when downloading other accounts' replays is turned off
855
+ #: for the account, see above).
853
856
  max: int = 0
854
857
  #: `true` when the account has no daily limit (`max` is then absent).
855
858
  unlimited: bool = False
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-ballchasing"
7
- version = "0.6.0"
7
+ version = "0.6.1"
8
8
  authors = [
9
9
  { name = "Rolv-Arild Braaten", email = "rolv_arild@hotmail.com" },
10
10
  ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-ballchasing
3
- Version: 0.6.0
3
+ Version: 0.6.1
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
@@ -112,6 +112,9 @@
112
112
  "401": {
113
113
  "$ref": "#/components/responses/Unauthorized"
114
114
  },
115
+ "403": {
116
+ "$ref": "#/components/responses/Restricted"
117
+ },
115
118
  "500": {
116
119
  "$ref": "#/components/responses/ServerError"
117
120
  }
@@ -317,14 +320,33 @@
317
320
  "$ref": "#/components/responses/Unauthorized"
318
321
  },
319
322
  "403": {
320
- "description": "The account behind the key is deleted.",
323
+ "description": "The account behind the key is deleted, or banned by the site's owner (`code: account_banned`; do not retry while the ban is active). An account whose API access is blocked can still upload.",
321
324
  "content": {
322
325
  "application/json": {
323
326
  "schema": {
324
- "$ref": "#/components/schemas/Error"
327
+ "anyOf": [
328
+ {
329
+ "$ref": "#/components/schemas/Error"
330
+ },
331
+ {
332
+ "$ref": "#/components/schemas/RestrictedError"
333
+ }
334
+ ]
325
335
  },
326
- "example": {
327
- "error": "this account is deleted"
336
+ "examples": {
337
+ "deleted": {
338
+ "summary": "Account deleted",
339
+ "value": {
340
+ "error": "this account is deleted"
341
+ }
342
+ },
343
+ "banned": {
344
+ "summary": "Account banned",
345
+ "value": {
346
+ "code": "account_banned",
347
+ "error": "This account has been banned from the API and from uploading because it was used together with other accounts to go past the download limits, which the terms of use do not allow. Do not retry these requests while this restriction is active."
348
+ }
349
+ }
328
350
  }
329
351
  }
330
352
  }
@@ -947,6 +969,9 @@
947
969
  "401": {
948
970
  "$ref": "#/components/responses/Unauthorized"
949
971
  },
972
+ "403": {
973
+ "$ref": "#/components/responses/Restricted"
974
+ },
950
975
  "429": {
951
976
  "$ref": "#/components/responses/TooManyRequests"
952
977
  },
@@ -1548,6 +1573,9 @@
1548
1573
  "401": {
1549
1574
  "$ref": "#/components/responses/Unauthorized"
1550
1575
  },
1576
+ "403": {
1577
+ "$ref": "#/components/responses/Restricted"
1578
+ },
1551
1579
  "404": {
1552
1580
  "$ref": "#/components/responses/NotFound"
1553
1581
  },
@@ -1662,6 +1690,9 @@
1662
1690
  "401": {
1663
1691
  "$ref": "#/components/responses/Unauthorized"
1664
1692
  },
1693
+ "403": {
1694
+ "$ref": "#/components/responses/Restricted"
1695
+ },
1665
1696
  "404": {
1666
1697
  "description": "No such replay (or not yours, for `title` and `visibility`), or no such group of yours.",
1667
1698
  "content": {
@@ -1746,6 +1777,9 @@
1746
1777
  "401": {
1747
1778
  "$ref": "#/components/responses/Unauthorized"
1748
1779
  },
1780
+ "403": {
1781
+ "$ref": "#/components/responses/Restricted"
1782
+ },
1749
1783
  "404": {
1750
1784
  "$ref": "#/components/responses/NotFound"
1751
1785
  },
@@ -1850,6 +1884,9 @@
1850
1884
  "401": {
1851
1885
  "$ref": "#/components/responses/Unauthorized"
1852
1886
  },
1887
+ "403": {
1888
+ "$ref": "#/components/responses/Restricted"
1889
+ },
1853
1890
  "404": {
1854
1891
  "$ref": "#/components/responses/NotFound"
1855
1892
  },
@@ -2121,6 +2158,9 @@
2121
2158
  "401": {
2122
2159
  "$ref": "#/components/responses/Unauthorized"
2123
2160
  },
2161
+ "403": {
2162
+ "$ref": "#/components/responses/Restricted"
2163
+ },
2124
2164
  "429": {
2125
2165
  "$ref": "#/components/responses/TooManyRequests"
2126
2166
  },
@@ -2244,6 +2284,9 @@
2244
2284
  "401": {
2245
2285
  "$ref": "#/components/responses/Unauthorized"
2246
2286
  },
2287
+ "403": {
2288
+ "$ref": "#/components/responses/Restricted"
2289
+ },
2247
2290
  "413": {
2248
2291
  "$ref": "#/components/responses/PayloadTooLarge"
2249
2292
  },
@@ -2967,6 +3010,9 @@
2967
3010
  "401": {
2968
3011
  "$ref": "#/components/responses/Unauthorized"
2969
3012
  },
3013
+ "403": {
3014
+ "$ref": "#/components/responses/Restricted"
3015
+ },
2970
3016
  "404": {
2971
3017
  "$ref": "#/components/responses/NotFound"
2972
3018
  },
@@ -3110,6 +3156,9 @@
3110
3156
  "401": {
3111
3157
  "$ref": "#/components/responses/Unauthorized"
3112
3158
  },
3159
+ "403": {
3160
+ "$ref": "#/components/responses/Restricted"
3161
+ },
3113
3162
  "404": {
3114
3163
  "description": "No such group, or not yours.",
3115
3164
  "content": {
@@ -3183,6 +3232,9 @@
3183
3232
  "401": {
3184
3233
  "$ref": "#/components/responses/Unauthorized"
3185
3234
  },
3235
+ "403": {
3236
+ "$ref": "#/components/responses/Restricted"
3237
+ },
3186
3238
  "404": {
3187
3239
  "$ref": "#/components/responses/NotFound"
3188
3240
  },
@@ -3306,6 +3358,9 @@
3306
3358
  "401": {
3307
3359
  "$ref": "#/components/responses/Unauthorized"
3308
3360
  },
3361
+ "403": {
3362
+ "$ref": "#/components/responses/Restricted"
3363
+ },
3309
3364
  "404": {
3310
3365
  "$ref": "#/components/responses/NotFound"
3311
3366
  },
@@ -3402,6 +3457,9 @@
3402
3457
  "401": {
3403
3458
  "$ref": "#/components/responses/Unauthorized"
3404
3459
  },
3460
+ "403": {
3461
+ "$ref": "#/components/responses/Restricted"
3462
+ },
3405
3463
  "404": {
3406
3464
  "description": "No such group, not yours, or group upload tokens are not available to your account.\n",
3407
3465
  "content": {
@@ -3498,6 +3556,9 @@
3498
3556
  "401": {
3499
3557
  "$ref": "#/components/responses/Unauthorized"
3500
3558
  },
3559
+ "403": {
3560
+ "$ref": "#/components/responses/Restricted"
3561
+ },
3501
3562
  "404": {
3502
3563
  "description": "No such group, not yours, or group upload tokens are not available to your account.\n",
3503
3564
  "content": {
@@ -3676,6 +3737,9 @@
3676
3737
  "401": {
3677
3738
  "$ref": "#/components/responses/Unauthorized"
3678
3739
  },
3740
+ "403": {
3741
+ "$ref": "#/components/responses/Restricted"
3742
+ },
3679
3743
  "429": {
3680
3744
  "$ref": "#/components/responses/TooManyRequests"
3681
3745
  },
@@ -3733,7 +3797,7 @@
3733
3797
  },
3734
3798
  "ReplayFileDownloads": {
3735
3799
  "type": "object",
3736
- "description": "Downloads of original replay files uploaded by **other accounts**, today (UTC), against the account's daily limit\n(see [Download a replay file](#tag/replays/download-replay-file)). One count for the API (`GET /api/replays/{id}/file`),\nthe site's download button and group zips together; each replay counts once a day, and the replays the account\nuploaded never count. Once `used` reaches `max`, downloading a replay not downloaded yet today answers 429 until\n`resets_at`. Reading it (pinging) never changes it.\n",
3800
+ "description": "Downloads of original replay files uploaded by **other accounts**, today (UTC), against the account's daily limit\n(see [Download a replay file](#tag/replays/download-replay-file)). One count for the API (`GET /api/replays/{id}/file`),\nthe site's download button and group zips together; each replay counts once a day, and the replays the account\nuploaded never count. Once `used` reaches a `max` above 0, downloading a replay not downloaded yet today answers 429\nuntil `resets_at`. A `max` of 0 means downloading other accounts' replays is turned off for the account: those\ndownloads answer 403, also after `resets_at`. Reading it (pinging) never changes it.\n",
3737
3801
  "required": [
3738
3802
  "used",
3739
3803
  "resets_at"
@@ -3741,11 +3805,11 @@
3741
3805
  "properties": {
3742
3806
  "used": {
3743
3807
  "type": "integer",
3744
- "description": "Distinct replays of other accounts downloaded today (UTC). Can be above `max` after the account's tier went\ndown during the day.\n"
3808
+ "description": "Distinct replays of other accounts downloaded today (UTC). Can be above `max` after the account's limit went\ndown during the day. For an account that shares its daily limit with other accounts, the distinct replays they\ndownloaded together today.\n"
3745
3809
  },
3746
3810
  "max": {
3747
3811
  "type": "integer",
3748
- "description": "The account's daily limit (absent when unlimited)."
3812
+ "description": "The account's daily limit (absent when unlimited; `0` when downloading other accounts' replays is turned off for the account, see above)."
3749
3813
  },
3750
3814
  "unlimited": {
3751
3815
  "type": "boolean",
@@ -3854,6 +3918,31 @@
3854
3918
  }
3855
3919
  }
3856
3920
  },
3921
+ "RestrictedError": {
3922
+ "description": "A restriction the site's owner put on the account.",
3923
+ "allOf": [
3924
+ {
3925
+ "$ref": "#/components/schemas/Error"
3926
+ },
3927
+ {
3928
+ "type": "object",
3929
+ "required": [
3930
+ "code"
3931
+ ],
3932
+ "properties": {
3933
+ "code": {
3934
+ "type": "string",
3935
+ "enum": [
3936
+ "account_banned",
3937
+ "api_access_blocked",
3938
+ "files_suspended"
3939
+ ],
3940
+ "description": "Which restriction refused the request. Do not retry the refused requests while it is active: `account_banned` refuses every API call; `api_access_blocked` refuses reads (`GET`/`HEAD`) except `GET /api/`, writes and uploads still work; `files_suspended` refuses replay files uploaded by other players, your own still download."
3941
+ }
3942
+ }
3943
+ }
3944
+ ]
3945
+ },
3857
3946
  "Visibility": {
3858
3947
  "type": "string",
3859
3948
  "enum": [
@@ -6102,6 +6191,39 @@
6102
6191
  }
6103
6192
  }
6104
6193
  },
6194
+ "Restricted": {
6195
+ "description": "The account is restricted (see `code`). Do not retry these requests while the restriction is active. A shared or lowered daily limit is not a 403: it shows up as the usual 429 with its own message.",
6196
+ "content": {
6197
+ "application/json": {
6198
+ "schema": {
6199
+ "$ref": "#/components/schemas/RestrictedError"
6200
+ },
6201
+ "examples": {
6202
+ "banned": {
6203
+ "summary": "Account banned",
6204
+ "value": {
6205
+ "code": "account_banned",
6206
+ "error": "This account has been banned from the API and from uploading because it was used together with other accounts to go past the download limits, which the terms of use do not allow. Do not retry these requests while this restriction is active."
6207
+ }
6208
+ },
6209
+ "apiBlocked": {
6210
+ "summary": "API reads blocked",
6211
+ "value": {
6212
+ "code": "api_access_blocked",
6213
+ "error": "API access is turned off for this account because it was used together with other accounts to go past the download limits, which the terms of use do not allow. Uploading still works. Do not retry these requests while this restriction is active."
6214
+ }
6215
+ },
6216
+ "filesSuspended": {
6217
+ "summary": "Other players' files suspended",
6218
+ "value": {
6219
+ "code": "files_suspended",
6220
+ "error": "Downloads of replay files uploaded by other players are turned off for this account because it was used together with other accounts to go past the download limits, which the terms of use do not allow. You can still download your own replays. Do not retry these requests while this restriction is active."
6221
+ }
6222
+ }
6223
+ }
6224
+ }
6225
+ }
6226
+ },
6105
6227
  "ServerError": {
6106
6228
  "description": "Server fault.",
6107
6229
  "content": {
@@ -14,7 +14,8 @@ from requests.exceptions import HTTPError
14
14
 
15
15
  from ballchasing import constants
16
16
  from ballchasing.api import BallchasingApi, PATRON_RATE_LIMIT_SLEEP_TIMES
17
- from ballchasing.exceptions import DailyDownloadLimitError, QuotaExceededError, UploadQuotaError
17
+ from ballchasing.exceptions import AccountRestrictedError, DailyDownloadLimitError, QuotaExceededError, \
18
+ UploadQuotaError
18
19
  from ballchasing.rate_limit import RateLimiter, RateLimitCategory, CATEGORY_HOURLY_SLEEP_TIMES
19
20
  from ballchasing.typed import DeepReplay, ShallowReplay, DeepGroup, ShallowGroup
20
21
  from ballchasing.util.stats import get_stats_info, parse_replay_stats
@@ -308,6 +309,92 @@ class TestQuotas:
308
309
  api.download_group("g", tmp_path)
309
310
 
310
311
 
312
+ class TestAccountRestrictions:
313
+ """403s with a ``code``: restrictions put on the account, which must not be retried."""
314
+ CODES = (AccountRestrictedError.ACCOUNT_BANNED, AccountRestrictedError.API_ACCESS_BLOCKED,
315
+ AccountRestrictedError.FILES_SUSPENDED)
316
+
317
+ def test_codes_match_spec(self):
318
+ schema = SPEC["components"]["schemas"]["RestrictedError"]
319
+ assert enum_values(properties(schema)["code"]) == set(self.CODES)
320
+
321
+ def test_every_endpoint_documents_restrictions(self):
322
+ for path, item in SPEC["paths"].items():
323
+ for method, op in item.items():
324
+ if method in ("get", "post", "put", "patch", "delete"):
325
+ response = resolve(op["responses"]["403"])
326
+ schema = json.dumps(response["content"]["application/json"]["schema"])
327
+ assert "RestrictedError" in schema, f"{method.upper()} {path}"
328
+
329
+ @pytest.mark.parametrize("code", CODES)
330
+ def test_restriction_raises_without_retrying(self, api, code):
331
+ body = {"code": code, "error": "Do not retry these requests while this restriction is active."}
332
+ with patch.object(api._session, "request", return_value=make_mock_response(403, json_data=body)) as m, \
333
+ patch("time.sleep") as sleep:
334
+ with pytest.raises(AccountRestrictedError) as e:
335
+ api.get_maps()
336
+ assert m.call_count == 1 and sleep.call_count == 0
337
+ assert e.value.code == code and isinstance(e.value, HTTPError)
338
+ assert code in str(e.value) and body["error"] in str(e.value)
339
+
340
+ def test_upload_restriction_raises(self, api):
341
+ body = {"code": "account_banned", "error": "banned"}
342
+ with patch.object(api._session, "request", return_value=make_mock_response(403, json_data=body)):
343
+ with pytest.raises(AccountRestrictedError):
344
+ api.upload_replay(io.BytesIO(b"data"))
345
+
346
+ def test_403_without_code_is_plain_http_error(self, api):
347
+ resp = make_mock_response(403, json_data={"error": "this account is deleted"})
348
+ with patch.object(api._session, "request", return_value=resp):
349
+ with pytest.raises(HTTPError) as e:
350
+ api.upload_replay(io.BytesIO(b"data"))
351
+ assert not isinstance(e.value, AccountRestrictedError)
352
+
353
+ def test_download_group_skips_suspended_files(self, api, tmp_path, caplog):
354
+ api._ping_result = {"steam_id": "me"}
355
+ listing = [{"id": "theirs1", "uploader": {"steam_id": "other"}}, {"id": "mine1", "uploader": {"steam_id": "me"}},
356
+ {"id": "theirs2", "uploader": {"steam_id": "other"}}, {"id": "mine2", "uploader": {"steam_id": "me"}}]
357
+ replays = make_mock_response(json_data={"list": listing})
358
+ suspended = make_mock_response(403, json_data={"code": "files_suspended", "error": "x"})
359
+ ok1, ok2 = make_mock_response(content=b"1"), make_mock_response(content=b"2")
360
+ with patch.object(api, "get_groups", return_value=iter([])), \
361
+ patch.object(api._session, "request", side_effect=[replays, suspended, ok1, ok2]) as m:
362
+ api.download_group("g", tmp_path)
363
+ # theirs2 is skipped without a request: it would be refused too
364
+ assert m.call_count == 4
365
+ assert "theirs2" not in str(m.call_args_list)
366
+ assert sorted(p.name for p in (tmp_path / "g").iterdir()) == ["mine1.replay", "mine2.replay"]
367
+ assert "Skipped 2 replays" in caplog.text
368
+
369
+ def test_download_group_without_ping_stops_requesting_after_suspension(self, api, tmp_path):
370
+ replays = make_mock_response(json_data={"list": [{"id": "a"}, {"id": "b"}, {"id": "c"}]})
371
+ suspended = make_mock_response(403, json_data={"code": "files_suspended", "error": "x"})
372
+ with patch.object(api, "get_groups", return_value=iter([])), \
373
+ patch.object(api._session, "request", side_effect=[replays, suspended]) as m:
374
+ api.download_group("g", tmp_path) # Own replays can't be told apart without the ping's steam_id
375
+ assert m.call_count == 2
376
+
377
+ def test_unreadable_error_body_is_plain_http_error(self, api):
378
+ from requests.exceptions import ChunkedEncodingError
379
+ resp = make_mock_response(403)
380
+ with patch.object(api._session, "request", return_value=resp) as m, \
381
+ patch.object(type(resp), "json", side_effect=ChunkedEncodingError("dropped")):
382
+ with pytest.raises(HTTPError) as e:
383
+ api.get_maps()
384
+ assert not isinstance(e.value, AccountRestrictedError) and m.call_count == 1
385
+ assert BallchasingApi._raise_for_quota(make_mock_response(429)) is None # Then a plain rate limit
386
+
387
+ @pytest.mark.parametrize("code", ["account_banned", "api_access_blocked"])
388
+ def test_download_group_stops_on_other_restrictions(self, api, tmp_path, code):
389
+ replays = make_mock_response(json_data={"list": [{"id": "r"}, {"id": "s"}]})
390
+ restricted = make_mock_response(403, json_data={"code": code, "error": "x"})
391
+ with patch.object(api, "get_groups", return_value=iter([])), \
392
+ patch.object(api._session, "request", side_effect=[replays, restricted]) as m:
393
+ with pytest.raises(AccountRestrictedError):
394
+ api.download_group("g", tmp_path)
395
+ assert m.call_count == 2
396
+
397
+
311
398
  class TestRateLimitTiers:
312
399
  @pytest.mark.parametrize("tier", ["legend", "org", "bot"])
313
400
  def test_new_tiers_get_gc_limits(self, tier):