python-ballchasing 0.6.0__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 CHANGED
@@ -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
 
ballchasing/api.py CHANGED
@@ -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)
ballchasing/exceptions.py CHANGED
@@ -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
@@ -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
@@ -1,7 +1,7 @@
1
- ballchasing/__init__.py,sha256=iH9IeimwznBAXqOAzeDnmcwmBpKRdIjZHoqQz-iPpgA,2856
2
- ballchasing/api.py,sha256=qyWHebEVrTvAe9zbNOhvjF7UiDCJ_t29_IDTPrr5Lnc,41503
1
+ ballchasing/__init__.py,sha256=QyB5NKS2jCbk9g9jeV1wuUI8zI4s_g3r-_yFl25HWaM,2880
2
+ ballchasing/api.py,sha256=qvuXQW7UwdVbzy35OrIJqeXak1sumEXuiPuvfx9THgs,43655
3
3
  ballchasing/constants.py,sha256=dHI8uRJ6Vrz6pMzOcRbaGaWnyV1chhHEJriDMTQN0NM,13081
4
- ballchasing/exceptions.py,sha256=Y_fdxe8-bxTuKJvlEFzQG0b_z7mjn5EATbg5VlMACcY,1616
4
+ ballchasing/exceptions.py,sha256=PMEQRyBQCT5HU6PYVm_lZHfoO8POE9RKwxhJzNKPs_k,2496
5
5
  ballchasing/rate_limit.py,sha256=QWpCnpbkm7exFI5IeHCOjAXyaZSmQ_rVLvAGodO9x7E,10263
6
6
  ballchasing/stats_info.tsv,sha256=Ap-OW4OsrG_6C2pldBMvPG5kqupaeds-3gt9HZOcLAY,14831
7
7
  ballchasing/typed/__init__.py,sha256=JDVUyRTXHkIvws9P-3cA2XWC6Ye985IYy2DVXfxO3T4,197
@@ -9,7 +9,7 @@ ballchasing/typed/_base.py,sha256=UQK6AbFXIOCn-Detgzc0XwgsFCP0MClgt4Onzw4jtYw,45
9
9
  ballchasing/typed/deep_group.py,sha256=7OIB6ykcA6xehGNVS07gfQ2aykphhzijS9QhH9eeVk0,1513
10
10
  ballchasing/typed/deep_replay.py,sha256=-mDKUUFoT6k7gW07Jc_BtsE0zEy4iCMs16bgw6NWxv0,938
11
11
  ballchasing/typed/methods.py,sha256=TSHqIbESx7TSVxweqVJLA-MgZLo6Rmin5qv18mXhco4,4735
12
- ballchasing/typed/models.py,sha256=ykdpC5nalqgyYaTxA_-vQ45JWT2wzFtRI79agG3dGqo,29588
12
+ ballchasing/typed/models.py,sha256=TY5YBiawUfZbRbaorTWZ-hDblorTc5cYGymJCdi3-og,29959
13
13
  ballchasing/typed/shallow_group.py,sha256=xHAy-45N2OkogTXYxRfrHV9_Oxs2xSGrkZEIzlxuQ14,234
14
14
  ballchasing/typed/shallow_replay.py,sha256=eRs1D9CyVTHz9iiSE8Zsoldm9fJvopD2jbS-Qn_Hw2A,357
15
15
  ballchasing/typed/shared.py,sha256=pigqS6Vp3tj7TBd5M8p-nZKYIAKV00osB-NynbanGTs,355
@@ -18,8 +18,8 @@ ballchasing/util/dates.py,sha256=gUSldK6-jMNbGLaBiYwmiKUR0h0ulzPiiDCZdFbBq2s,883
18
18
  ballchasing/util/iterators.py,sha256=P5uUocfv0vqoV4NKtxpGYS83MmfhntqNyNRbfcaU160,4258
19
19
  ballchasing/util/replays.py,sha256=4OmDqrNrjHKz6G9iVVz01UWq3KGJGEYbWJ-nNaDqK0E,8380
20
20
  ballchasing/util/stats.py,sha256=WhyLhKwUbHErjaabK5RhEL8nvDz-wCCE1HGxcZ9Ea0U,2592
21
- python_ballchasing-0.6.0.dist-info/licenses/LICENSE,sha256=ua0R_J89EfdcyYXy_6TMz6BoSxABvyBYCfgfOKu12FE,1075
22
- python_ballchasing-0.6.0.dist-info/METADATA,sha256=4poYYz_mhDWAD2CtfUyEiw4BIac0NZYUMzU6tk8JbgQ,4621
23
- python_ballchasing-0.6.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
24
- python_ballchasing-0.6.0.dist-info/top_level.txt,sha256=YmO-pVNVRUMdF138yyv1K23a2FVsiEEX1dtyfWPzwmI,12
25
- python_ballchasing-0.6.0.dist-info/RECORD,,
21
+ python_ballchasing-0.6.1.dist-info/licenses/LICENSE,sha256=ua0R_J89EfdcyYXy_6TMz6BoSxABvyBYCfgfOKu12FE,1075
22
+ python_ballchasing-0.6.1.dist-info/METADATA,sha256=OlWKQN1AVmtd8m5UieHV13P2RY3KnZnY86NJATl9pKY,4621
23
+ python_ballchasing-0.6.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
24
+ python_ballchasing-0.6.1.dist-info/top_level.txt,sha256=YmO-pVNVRUMdF138yyv1K23a2FVsiEEX1dtyfWPzwmI,12
25
+ python_ballchasing-0.6.1.dist-info/RECORD,,