Debian Codegraph @

beetsplug/tidal/session.py

raw
1 from __future__ import annotations
2
3 import json
4 from http import HTTPStatus
5 from pathlib import Path
6 from time import sleep
7 from typing import TYPE_CHECKING
8
9 import requests
10 from requests_oauthlib import OAuth2Session
11 from urllib3.util.retry import Retry
12
13 from beets.logging import getLogger
14 from beetsplug._utils.requests import RateLimitAdapter, TimeoutAndRetrySession
15
16 if TYPE_CHECKING:
17 from beetsplug._typing import JSONDict
18
19 API_BASE = "https://openapi.tidal.com/v2"
20
21 log = getLogger("beets.tidal")
22
23
24 class TidalSession(OAuth2Session, TimeoutAndRetrySession):
25 """Tidal API session with automatic OAuth2 PKCE authentication.
26
27 Handles:
28 - Initial interactive PKCE flow (Tidal required)
29 - Automatic token refresh
30 - Rate limiting (~4 req/s)
31 - Token persistence
32 - API base URL prefixing
33 """
34
35 token_path: Path
36
37 def __init__(self, client_id: str, token_path: str | Path) -> None:
38 self.token_path = Path(token_path)
39
40 # Load token & init parent
41 token = self.load_token()
42 super().__init__(
43 client_id,
44 token=token,
45 scope="search.read",
46 auto_refresh_url="https://auth.tidal.com/v1/oauth2/token",
47 redirect_uri="https://localhost",
48 auto_refresh_kwargs={"client_id": client_id},
49 token_updater=self.save_token,
50 pkce="S256",
51 )
52
53 # Retry on server errors
54 retry = Retry(
55 total=6,
56 backoff_factor=0.5,
57 status_forcelist=[
58 HTTPStatus.INTERNAL_SERVER_ERROR,
59 HTTPStatus.BAD_GATEWAY,
60 HTTPStatus.SERVICE_UNAVAILABLE,
61 HTTPStatus.GATEWAY_TIMEOUT,
62 ],
63 )
64 # Rate limit to ~4/s as tidal will penalize heavily if not respected
65 adapter = RateLimitAdapter(rate_limit=0.25, max_retries=retry)
66 self.mount("https://auth.tidal.com/", adapter)
67 self.mount(API_BASE, adapter)
68
69 def load_token(self) -> JSONDict | None:
70 """Load token from JSON file."""
71 if self.token_path.exists():
72 with open(self.token_path) as f:
73 return json.load(f)
74 return None
75
76 def save_token(self, token: JSONDict) -> None:
77 """Save token to JSON file."""
78 with open(self.token_path, "w") as f:
79 json.dump(token, f, indent=2)
80
81 def request(
82 self, method: str | bytes, url: str | bytes, *args, **kwargs
83 ) -> requests.Response:
84 """Override for Tidal-specific base URL and rate limits."""
85 if isinstance(url, str) and not url.startswith("http"):
86 url = API_BASE + url
87
88 try:
89 res = super().request(method, url, *args, **kwargs)
90 except requests.exceptions.HTTPError as e:
91 res = e.response
92 if res.status_code == 429:
93 self._handle_rate_limit(res)
94 return self.request(method, url, *args, **kwargs)
95 raise
96 return res
97
98 def _handle_rate_limit(self, response: requests.Response) -> None:
99 remaining = int(response.headers.get("Retry-After", 0))
100 if remaining > 0:
101 log.debug(
102 "Rate limit exceeded. Retrying after {0} seconds.", remaining
103 )
104 sleep(remaining)
105 else:
106 raise Exception(
107 "Rate limit handling failed: Retry-After header is missing or invalid"
108 )
109 return