Initial commit: LastRecc discovery feed and weekly engine
This commit is contained in:
40 files changed
+6972
No files matched your search
+152
@@ -0,0 +1,152 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
|
||||
|
||||
class HttpError(RuntimeError):
|
||||
def __init__(self, status: int, url: str, body: str = ""):
|
||||
# Never put API keys / Subsonic tokens from the query string into logs.
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
safe_url = urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
|
||||
self.status = status
|
||||
self.url = safe_url
|
||||
self.body = body
|
||||
super().__init__(f"HTTP {status} for {safe_url}: {body[:240]}")
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""A simple shared token bucket. Good enough for personal API use."""
|
||||
|
||||
def __init__(self, rate_per_second: float):
|
||||
self.interval = 1.0 / max(rate_per_second, 0.1)
|
||||
self._next = 0.0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def wait(self) -> None:
|
||||
with self._lock:
|
||||
now = time.monotonic()
|
||||
if now < self._next:
|
||||
delay = self._next - now
|
||||
else:
|
||||
delay = 0.0
|
||||
self._next = max(now, self._next) + self.interval
|
||||
if delay:
|
||||
time.sleep(delay)
|
||||
|
||||
|
||||
class HttpClient:
|
||||
def __init__(
|
||||
self,
|
||||
user_agent: str,
|
||||
*,
|
||||
rate_limiter: RateLimiter | None = None,
|
||||
basic_auth: tuple[str, str] | None = None,
|
||||
default_headers: dict[str, str] | None = None,
|
||||
timeout: float = 60.0,
|
||||
):
|
||||
self.user_agent = user_agent
|
||||
self.rate_limiter = rate_limiter
|
||||
self.basic_auth = basic_auth
|
||||
self.default_headers = default_headers or {}
|
||||
self.timeout = timeout
|
||||
|
||||
def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
|
||||
headers = {
|
||||
"User-Agent": self.user_agent,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Encoding": "identity",
|
||||
}
|
||||
headers.update(self.default_headers)
|
||||
if self.basic_auth:
|
||||
token = base64.b64encode(
|
||||
f"{self.basic_auth[0]}:{self.basic_auth[1]}".encode()
|
||||
).decode()
|
||||
headers["Authorization"] = f"Basic {token}"
|
||||
if extra:
|
||||
headers.update(extra)
|
||||
return headers
|
||||
|
||||
def open(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
method: str = "GET",
|
||||
data: Any = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
timeout: float | None = None,
|
||||
):
|
||||
body = None
|
||||
final_headers = self._headers(headers)
|
||||
if data is not None:
|
||||
if isinstance(data, (dict, list)):
|
||||
body = json.dumps(data).encode("utf-8")
|
||||
final_headers.setdefault("Content-Type", "application/json")
|
||||
elif isinstance(data, str):
|
||||
body = data.encode("utf-8")
|
||||
else:
|
||||
body = data
|
||||
if self.rate_limiter:
|
||||
self.rate_limiter.wait()
|
||||
request = urllib.request.Request(url, data=body, headers=final_headers, method=method)
|
||||
return urllib.request.urlopen(request, timeout=timeout or self.timeout)
|
||||
|
||||
def request(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
method: str = "GET",
|
||||
data: Any = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
retries: int = 3,
|
||||
) -> tuple[int, dict[str, str], bytes]:
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(retries + 1):
|
||||
try:
|
||||
with self.open(url, method=method, data=data, headers=headers) as response:
|
||||
return response.status, dict(response.headers), response.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
payload = exc.read().decode("utf-8", "replace")
|
||||
last_error = HttpError(exc.code, url, payload)
|
||||
if exc.code not in (429, 500, 502, 503, 504) or attempt == retries:
|
||||
raise last_error
|
||||
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
||||
last_error = exc
|
||||
if attempt == retries:
|
||||
raise
|
||||
time.sleep((2**attempt) * 0.5 + random.random() * 0.3)
|
||||
raise RuntimeError(f"Request failed: {last_error}")
|
||||
|
||||
def get_json(
|
||||
self,
|
||||
url: str,
|
||||
*,
|
||||
params: dict[str, Any] | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
if params:
|
||||
query = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
|
||||
url = f"{url}{'&' if '?' in url else '?'}{query}"
|
||||
status, _, payload = self.request(url, headers=headers)
|
||||
if not payload:
|
||||
return None
|
||||
return json.loads(payload.decode("utf-8"))
|
||||
|
||||
def post_json(
|
||||
self,
|
||||
url: str,
|
||||
data: Any,
|
||||
*,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
status, _, payload = self.request(url, method="POST", data=data, headers=headers)
|
||||
if not payload:
|
||||
return None
|
||||
return json.loads(payload.decode("utf-8"))
|
||||
Reference in new issue
Block a user