from __future__ import annotations import json import sys import threading import time import urllib.parse from typing import Any from .cache import is_fresh, load_json, save_json from .config import Settings, basic_auth from .net import HttpClient, HttpError, RateLimiter class NavidromeError(RuntimeError): pass class Navidrome: """Navidrome native API + Subsonic API client.""" def __init__(self, settings: Settings): self.settings = settings self.base = settings.navidrome_url self.http = HttpClient( "LastRecc/0.1 (https://github.com/lastrecc)", rate_limiter=RateLimiter(settings.navidrome_rate), basic_auth=basic_auth(settings), default_headers={"X-ND-Client-Unique-Id": "lastrecc"}, ) self._token: str | None = None self._salt: str | None = None self._subsonic_token: str | None = None self._login_lock = threading.Lock() self._songs: dict[str, dict] = {} self._songs_path = settings.cache_dir / "navidrome_songs.json" self._songs_loaded = False # ------------------------------------------------------------------ auth def login(self, force: bool = False) -> None: with self._login_lock: if self._token and not force: return try: data = self.http.post_json( f"{self.base}/auth/login", { "username": self.settings.navidrome_user, "password": self.settings.navidrome_password, }, ) except HttpError as exc: raise NavidromeError(f"Navidrome login failed: {exc}") from exc if not data or "token" not in data: raise NavidromeError("Navidrome login returned no token") self._token = data["token"] self._salt = data.get("subsonicSalt") self._subsonic_token = data.get("subsonicToken") def _native_headers(self) -> dict[str, str]: self.login() return {"X-ND-Authorization": f"Bearer {self._token}"} def _native_request(self, url: str) -> tuple[int, dict[str, str], bytes]: for attempt in range(2): try: return self.http.request(url, headers=self._native_headers()) except HttpError as exc: if exc.status == 401 and attempt == 0: self.login(force=True) continue raise raise NavidromeError("Navidrome request failed after re-authentication") # --------------------------------------------------------------- scrobbles def get_scrobbles(self, force: bool = False, ttl: int = 600) -> list[dict]: path = self.settings.cache_dir / "scrobbles.json" if not force and is_fresh(path, ttl): cached = load_json(path) if cached and isinstance(cached.get("items"), list): return cached["items"] items: list[dict] = [] start = 0 total = None while True: url = ( f"{self.base}/api/scrobble" f"?_end=5000&_order=DESC&_sort=submission_time&_start={start}" ) _, headers, payload = self._native_request(url) chunk = json.loads(payload.decode("utf-8")) if payload else [] if not isinstance(chunk, list): raise NavidromeError(f"Unexpected scrobble response: {chunk!r}") items.extend(chunk) total = int(headers.get("X-Total-Count", len(items))) if not chunk or len(items) >= total: break start += len(chunk) if start > 200_000: break save_json(path, {"fetched_at": time.time(), "items": items}) return items # ------------------------------------------------------------------- songs def _load_songs(self) -> None: if self._songs_loaded: return cached = load_json(self._songs_path, {}) if isinstance(cached, dict): self._songs = {str(k): v for k, v in cached.items() if isinstance(v, dict)} self._songs_loaded = True def get_songs(self, ids: set[str] | list[str]) -> dict[str, dict]: """Fetch song metadata for IDs, batching and caching aggressively.""" self._load_songs() missing = [song_id for song_id in ids if song_id not in self._songs] if not missing: return {song_id: self._songs[song_id] for song_id in ids} for offset in range(0, len(missing), 80): chunk = missing[offset : offset + 80] query = urllib.parse.urlencode([("id", song_id) for song_id in chunk]) try: _, _, payload = self._native_request(f"{self.base}/api/song?{query}") songs = json.loads(payload.decode("utf-8")) if payload else [] except (HttpError, NavidromeError) as exc: print(f" ! song metadata batch failed: {exc}", file=sys.stderr) continue if not isinstance(songs, list): continue for song in songs: if song.get("id"): self._songs[song["id"]] = song if (offset // 80) % 5 == 0: save_json(self._songs_path, self._songs) print( f" ยท metadata {min(offset + 80, len(missing))}/{len(missing)}", file=sys.stderr, end="\r", ) save_json(self._songs_path, self._songs) print(" " * 60, file=sys.stderr, end="\r") return {song_id: self._songs[song_id] for song_id in ids if song_id in self._songs} # ---------------------------------------------------------------- subsonic def _subsonic_params(self) -> dict[str, str]: self.login() if not self._salt or not self._subsonic_token: raise NavidromeError("Navidrome did not return Subsonic credentials") return { "u": self.settings.navidrome_user, "t": self._subsonic_token, "s": self._salt, "v": "1.16.1", "c": "LastRecc", "f": "json", } def subsonic(self, method: str, **params: Any) -> dict: query = self._subsonic_params() query.update({key: value for key, value in params.items() if value is not None}) url = f"{self.base}/rest/{method}.view?{urllib.parse.urlencode(query)}" data = self.http.get_json(url) response = (data or {}).get("subsonic-response", {}) if response.get("status") != "ok": error = response.get("error", {}) raise NavidromeError(f"Subsonic {method} failed: {error or response}") return response def search_songs(self, query: str, limit: int = 5) -> list[dict]: try: data = self.subsonic( "search3", query=query, songCount=limit, albumCount=0, artistCount=0, ) except (HttpError, NavidromeError): return [] result = data.get("searchResult3", {}) songs = result.get("song", []) if isinstance(songs, dict): songs = [songs] return [song for song in songs if isinstance(song, dict)] def cover_url(self, cover_id: str, size: int = 300) -> str: query = self._subsonic_params() query.update({"id": cover_id, "size": str(size)}) return f"{self.base}/rest/getCoverArt.view?{urllib.parse.urlencode(query)}" def stream_url(self, song_id: str) -> str: query = self._subsonic_params() query.update({"id": song_id}) return f"{self.base}/rest/stream.view?{urllib.parse.urlencode(query)}" def page_url(self, album_id: str | None = None, song_id: str | None = None) -> str: if album_id: return f"{self.base}/app/#/album/{urllib.parse.quote(album_id)}/show" if song_id: return f"{self.base}/app/#/song/{urllib.parse.quote(song_id)}/show" return f"{self.base}/app/"