"""Radarr / Sonarr v3 client. The only module that performs network writes, and only through these methods.""" from __future__ import annotations from typing import Any import httpx from plexreaper.config import ArrConfig from plexreaper.models import Title class ArrClient: def __init__(self, cfg: ArrConfig, *, timeout: float = 60.0) -> None: if not cfg.api_key: raise RuntimeError(f"{cfg.env_prefix}_API_KEY is not set for arr instance {cfg.name!r}") self.cfg = cfg self.kind = "movie" if cfg.type == "radarr" else "series" self._client = httpx.AsyncClient( base_url=cfg.url.rstrip("/") + "/api/v3", headers={"X-Api-Key": cfg.api_key, "Accept": "application/json"}, timeout=timeout, ) async def aclose(self) -> None: await self._client.aclose() async def __aenter__(self) -> ArrClient: return self async def __aexit__(self, *exc: object) -> None: await self.aclose() @property def name(self) -> str: return self.cfg.name # ---- reads -------------------------------------------------------------------- async def _get(self, path: str, params: dict | None = None) -> Any: r = await self._client.get(path, params=params) r.raise_for_status() return r.json() async def status(self) -> dict: return await self._get("/system/status") async def profiles(self) -> dict[int, str]: return {int(p["id"]): p["name"] for p in await self._get("/qualityprofile")} async def all_items(self) -> list[dict]: return await self._get(f"/{self.kind}") async def item(self, item_id: int) -> dict: return await self._get(f"/{self.kind}/{item_id}") async def files(self, item: dict) -> list[dict]: """On-disk files for one movie / series as [{id, path, size}].""" if self.cfg.type == "radarr": mf = item.get("movieFile") if not mf and item.get("hasFile"): mf = (await self.item(int(item["id"]))).get("movieFile") return [{"id": int(mf["id"]), "path": mf.get("path"), "size": int(mf.get("size") or 0), "resolution": _resolution(mf)}] if mf else [] episodes = await self._get("/episodefile", {"seriesId": int(item["id"])}) return [ { "id": int(e["id"]), "path": e.get("path"), "size": int(e.get("size") or 0), "season": e.get("seasonNumber"), "resolution": _resolution(e), } for e in episodes ] async def profiles_raw(self) -> list[dict]: return await self._get("/qualityprofile") # ---- writes ------------------------------------------------------------------- async def update(self, item: dict) -> dict: r = await self._client.put(f"/{self.kind}/{int(item['id'])}", json=item) r.raise_for_status() return r.json() if r.content else item async def unmonitor(self, item: dict) -> dict: fresh = await self.item(int(item["id"])) fresh["monitored"] = False for season in fresh.get("seasons") or []: season["monitored"] = False return await self.update(fresh) async def set_profile(self, item: dict, profile_id: int) -> dict: fresh = await self.item(int(item["id"])) fresh["qualityProfileId"] = profile_id fresh["monitored"] = True return await self.update(fresh) async def bulk_set_profile(self, item_ids: list[int], profile_id: int) -> None: """One call through the *arr bulk editor: quality profile only, files untouched.""" key = "movieIds" if self.cfg.type == "radarr" else "seriesIds" r = await self._client.put(f"/{self.kind}/editor", json={key: item_ids, "qualityProfileId": profile_id}) r.raise_for_status() async def delete_file(self, file_id: int) -> None: endpoint = "moviefile" if self.cfg.type == "radarr" else "episodefile" r = await self._client.delete(f"/{endpoint}/{file_id}") r.raise_for_status() async def search(self, item_id: int) -> None: body = {"name": "MoviesSearch", "movieIds": [item_id]} if self.cfg.type == "radarr" else {"name": "SeriesSearch", "seriesId": item_id} r = await self._client.post("/command", json=body) r.raise_for_status() def _resolution(file: dict) -> int: try: return int(((file.get("quality") or {}).get("quality") or {}).get("resolution") or 0) except (TypeError, ValueError): return 0 def profile_max_resolution(profile: dict) -> int: """Highest vertical resolution the profile allows (0 when unknown).""" best = 0 for it in profile.get("items") or []: if not it.get("allowed"): continue quals = [it["quality"]] if it.get("quality") else [q["quality"] for q in it.get("items") or [] if q.get("allowed")] for q in quals: best = max(best, int(q.get("resolution") or 0)) return best def summarize(cfg: ArrConfig, item: dict, profiles: dict[int, str]) -> dict: """The few fields the evidence panel shows.""" stats = item.get("statistics") or {} size = int(item.get("sizeOnDisk") or stats.get("sizeOnDisk") or 0) out = { "arr": cfg.name, "id": int(item["id"]), "monitored": bool(item.get("monitored")), "profile": profiles.get(int(item.get("qualityProfileId") or 0), "?"), "size_bytes": size, "path": item.get("path"), } if cfg.type == "sonarr": out["status"] = item.get("status") out["episodes"] = f"{stats.get('episodeFileCount', 0)}/{stats.get('totalEpisodeCount', 0)} files" else: out["has_file"] = bool(item.get("hasFile")) return out class ArrIndex: """All items of one instance, resolvable from a Plex title by external id, then by title and year.""" def __init__(self, cfg: ArrConfig, items: list[dict], profiles: dict[int, str], profiles_raw: list[dict] | None = None) -> None: self.cfg = cfg self.profiles = profiles self.items = items self.max_resolution: dict[int, int] = {int(p["id"]): profile_max_resolution(p) for p in profiles_raw or []} self.by_tmdb: dict[int, dict] = {} self.by_tvdb: dict[int, dict] = {} self.by_imdb: dict[str, dict] = {} self.by_title: dict[tuple[str, int | None], dict] = {} for it in items: if it.get("tmdbId"): self.by_tmdb[int(it["tmdbId"])] = it if it.get("tvdbId"): self.by_tvdb[int(it["tvdbId"])] = it if it.get("imdbId"): self.by_imdb[str(it["imdbId"])] = it self.by_title[(str(it.get("title", "")).lower(), it.get("year"))] = it def resolve(self, title: Title) -> dict | None: ids = title.external_ids for key, index in (("tmdb", self.by_tmdb), ("tvdb", self.by_tvdb)): if ids.get(key, "").isdigit() and int(ids[key]) in index: return index[int(ids[key])] if ids.get("imdb") in self.by_imdb: return self.by_imdb[ids["imdb"]] return self.by_title.get((title.title.lower(), title.year)) def profile_id(self, name: str) -> int | None: return next((pid for pid, pname in self.profiles.items() if pname.lower() == name.lower()), None) async def load_index(client: ArrClient) -> ArrIndex: raw = await client.profiles_raw() return ArrIndex(client.cfg, await client.all_items(), {int(p["id"]): p["name"] for p in raw}, raw)