from __future__ import annotations import hashlib import json import urllib.error from typing import Any from .cache import JsonCache from .net import HttpClient, HttpError, RateLimiter API_ROOT = "https://ws.audioscrobbler.com/2.0/" PLACEHOLDER_HASH = "2a96cbd8b46e442fc41c2b86b821562f" class LastFMError(RuntimeError): pass def _as_list(value: Any) -> list[dict]: if isinstance(value, dict): return [value] if isinstance(value, list): return [item for item in value if isinstance(item, dict)] return [] def _match(value: Any) -> float: try: return float(value) except (TypeError, ValueError): return 0.0 def _image(images: Any) -> str | None: for image in reversed(_as_list(images)): url = (image.get("#text") or "").strip() if url and PLACEHOLDER_HASH not in url: return url return None def _artist_name(track: dict) -> str: artist = track.get("artist") if isinstance(artist, dict): return artist.get("name") or artist.get("#text") or "" if isinstance(artist, str): return artist return track.get("artistName") or "" class LastFM: def __init__(self, api_key: str, cache_dir, rate_limiter: RateLimiter | None = None): self.api_key = api_key self.http = HttpClient( "LastRecc/0.1 (https://github.com/lastrecc)", rate_limiter=rate_limiter or RateLimiter(4.0), ) self.cache = JsonCache(cache_dir / "lastfm", ttl_seconds=14 * 24 * 3600) def _call(self, method: str, **params: Any) -> dict: clean = {key: value for key, value in params.items() if value is not None} cache_key = method + "::" + hashlib.sha256( json.dumps(clean, sort_keys=True, ensure_ascii=False).encode("utf-8") ).hexdigest() cached = self.cache.get(cache_key) if cached is not None: return cached query = {"method": method, "api_key": self.api_key, "format": "json", **clean} try: data = self.http.get_json(API_ROOT, params=query) except (HttpError, urllib.error.URLError, TimeoutError, OSError) as exc: raise LastFMError(f"Last.fm {method} failed: {exc}") from exc except ValueError as exc: raise LastFMError(f"Last.fm {method} returned invalid JSON") from exc if not isinstance(data, dict): raise LastFMError(f"Last.fm {method} returned no data") if data.get("error"): raise LastFMError(f"Last.fm {method}: {data.get('message', 'unknown error')}") self.cache.set(cache_key, data) return data # ----------------------------------------------------------------- artists def artist_similar(self, artist: str, limit: int = 20) -> list[dict]: data = self._call("artist.getSimilar", artist=artist, limit=limit, autocorrect=1) return _as_list(data.get("similarartists", {}).get("artist")) def artist_top_tracks(self, artist: str, limit: int = 5) -> list[dict]: data = self._call("artist.getTopTracks", artist=artist, limit=limit, autocorrect=1) return _as_list(data.get("toptracks", {}).get("track")) def artist_top_albums(self, artist: str, limit: int = 5) -> list[dict]: data = self._call("artist.getTopAlbums", artist=artist, limit=limit, autocorrect=1) return _as_list(data.get("topalbums", {}).get("album")) def artist_info(self, artist: str) -> dict: data = self._call("artist.getInfo", artist=artist, autocorrect=1) return data.get("artist", {}) or {} # ------------------------------------------------------------------ tracks def track_similar(self, artist: str, track: str, limit: int = 15) -> list[dict]: data = self._call( "track.getSimilar", artist=artist, track=track, limit=limit, autocorrect=1, ) return _as_list(data.get("similartracks", {}).get("track")) def track_info(self, artist: str, track: str) -> dict: data = self._call("track.getInfo", artist=artist, track=track, autocorrect=1) return data.get("track", {}) or {} # ------------------------------------------------------------------ albums def album_info(self, artist: str, album: str) -> dict: data = self._call("album.getInfo", artist=artist, album=album, autocorrect=1) return data.get("album", {}) or {} # ------------------------------------------------------------------- utils @staticmethod def image_from_track(track: dict) -> str | None: album = track.get("album") if isinstance(album, dict): return _image(album.get("image")) or _image(track.get("image")) return _image(track.get("image")) @staticmethod def image_from_album(album: dict) -> str | None: return _image(album.get("image")) @staticmethod def artist_name(track: dict) -> str: return _artist_name(track) @staticmethod def match(value: Any) -> float: return _match(value)