"""Plex HTTP API client: library inventory and the all-accounts history prior.""" from __future__ import annotations from datetime import datetime from typing import Any import httpx from plexreaper.models import Inventory, Library, Title _MOVIE, _SHOW, _EPISODE = 1, 2, 4 def _ts(value: Any) -> datetime | None: try: return datetime.fromtimestamp(int(value)) if value else None except (TypeError, ValueError, OSError): return None def _parts_size(item: dict) -> int: return sum( int(part.get("size") or 0) for media in item.get("Media") or [] for part in media.get("Part") or [] ) def _external_ids(item: dict) -> dict[str, str]: ids: dict[str, str] = {} for g in item.get("Guid") or []: scheme, _, value = str(g.get("id", "")).partition("://") if scheme and value: ids[scheme] = value return ids def _tags(item: dict, key: str) -> list[str]: return [t["tag"] for t in item.get(key) or [] if t.get("tag")] class PlexClient: """Async JSON client. Read-only by construction: only GET is implemented.""" def __init__(self, url: str, token: str, *, timeout: float = 120.0, page_size: int = 5000) -> None: self.page_size = page_size self._client = httpx.AsyncClient( base_url=url.rstrip("/"), headers={"Accept": "application/json", "X-Plex-Token": token}, timeout=timeout, ) async def aclose(self) -> None: await self._client.aclose() async def __aenter__(self) -> PlexClient: return self async def __aexit__(self, *exc: object) -> None: await self.aclose() # ---- transport ---------------------------------------------------------- async def _get(self, path: str, params: dict | None = None, headers: dict | None = None) -> dict: r = await self._client.get(path, params=params, headers=headers) r.raise_for_status() return r.json().get("MediaContainer", {}) async def _paged(self, path: str, params: dict | None = None) -> list[dict]: items: list[dict] = [] start = 0 while True: headers = {"X-Plex-Container-Start": str(start), "X-Plex-Container-Size": str(self.page_size)} container = await self._get(path, params, headers) page = container.get("Metadata") or [] items.extend(page) total = int(container.get("totalSize") or container.get("size") or len(items)) start += len(page) if not page or start >= total: return items # ---- queries ------------------------------------------------------------ async def identity(self) -> dict: return await self._get("/identity") async def libraries(self) -> list[Library]: container = await self._get("/library/sections") return [ Library(id=int(d["key"]), name=d["title"], type=d.get("type", "other")) for d in container.get("Directory") or [] ] async def inventory(self, library_ids: list[int] | None = None) -> Inventory: """Every movie and show in the chosen libraries, with sizes summed from episodes for shows.""" libraries = await self.libraries() titles: list[Title] = [] episode_to_show: dict[str, str] = {} wanted = set(library_ids or []) for lib in libraries: if lib.type not in ("movie", "show") or (wanted and lib.id not in wanted): continue if lib.type == "movie": titles.extend(self._movies(lib, await self._section(lib.id, _MOVIE))) else: shows = await self._section(lib.id, _SHOW) episodes = await self._section(lib.id, _EPISODE) titles.extend(self._shows(lib, shows, episodes, episode_to_show)) return Inventory(titles=titles, episode_to_show=episode_to_show, scanned_at=datetime.now()) async def _section(self, section_id: int, type_code: int) -> list[dict]: return await self._paged( f"/library/sections/{section_id}/all", {"type": type_code, "includeGuids": 1, "includeCollections": 1}, ) @staticmethod def _base(item: dict, lib: Library, kind: str) -> dict: return { "guid": item.get("guid") or f"plex://{kind}/ratingkey-{item.get('ratingKey')}", "rating_key": int(item.get("ratingKey") or 0), "kind": kind, "title": item.get("title") or "Unknown", "year": item.get("year"), "library_id": lib.id, "library_name": lib.name, "added_at": _ts(item.get("addedAt")) or datetime.now(), "rating": item.get("rating"), "audience_rating": item.get("audienceRating"), "genres": _tags(item, "Genre"), "collections": _tags(item, "Collection"), "external_ids": _external_ids(item), } def _movies(self, lib: Library, items: list[dict]) -> list[Title]: return [ Title(**self._base(it, lib, "movie"), size_bytes=_parts_size(it), duration_ms=int(it.get("duration") or 0)) for it in items ] def _shows(self, lib: Library, shows: list[dict], episodes: list[dict], episode_to_show: dict[str, str]) -> list[Title]: by_key = {str(s.get("ratingKey")): s for s in shows} size: dict[str, int] = {} duration: dict[str, int] = {} count: dict[str, int] = {} seasons: dict[str, set[int]] = {} for ep in episodes: key = str(ep.get("grandparentRatingKey") or "") show = by_key.get(key) if show is None: continue size[key] = size.get(key, 0) + _parts_size(ep) duration[key] = duration.get(key, 0) + int(ep.get("duration") or 0) count[key] = count.get(key, 0) + 1 if ep.get("parentIndex") is not None: seasons.setdefault(key, set()).add(int(ep["parentIndex"])) if ep.get("guid") and show.get("guid"): episode_to_show[ep["guid"]] = show["guid"] out: list[Title] = [] for key, show in by_key.items(): out.append( Title( **self._base(show, lib, "show"), size_bytes=size.get(key, 0), duration_ms=duration.get(key, 0), season_count=len(seasons.get(key, ())) or int(show.get("childCount") or 0), episode_count=count.get(key, 0) or int(show.get("leafCount") or 0), ) ) return out async def history(self) -> dict[int, tuple[int, datetime | None]]: """All-accounts watch history keyed by movie / show rating key: (views, last viewed).""" entries = await self._paged("/status/sessions/history/all") out: dict[int, tuple[int, datetime | None]] = {} for e in entries: kind = e.get("type") if kind == "movie": key = e.get("ratingKey") elif kind == "episode": key = e.get("grandparentRatingKey") or str(e.get("grandparentKey", "")).rsplit("/", 1)[-1] else: continue try: rk = int(key) except (TypeError, ValueError): continue views, last = out.get(rk, (0, None)) seen = _ts(e.get("viewedAt")) out[rk] = (views + 1, max(filter(None, (last, seen)), default=None)) return out