"""MoviePilot media and resource operations.""" from __future__ import annotations from collections.abc import Mapping from typing import Any try: from .moviepilot_client import MoviePilotClient from .session_context import SessionContextStore except ImportError: from moviepilot_client import MoviePilotClient from session_context import SessionContextStore class MediaService: """Coordinate MoviePilot media APIs with per-session result caching.""" def __init__( self, config: Mapping[str, Any], session_store: SessionContextStore, ) -> None: self._config = config self._session_store = session_store self._client: MoviePilotClient | None = None def _get_client(self) -> MoviePilotClient: if self._client is None: self._client = MoviePilotClient( str(self._config.get("moviepilot_url", "")), str(self._config.get("moviepilot_api_token", "")), ) return self._client async def close(self) -> None: if self._client is not None: await self._client.close() self._client = None async def search_media( self, origin: str, title: str, *, media_type: str | None = None, page: int = 1, count: int | None = None, ) -> list[dict[str, Any]]: params: dict[str, Any] = {"title": title, "page": page} if media_type: params["type"] = media_type params["count"] = count or int(self._config.get("search_result_count", 5)) response = await self._get_client().get("/api/v1/media/search", params=params) results = self._as_dict_list(response.data) self._session_store.set_media_results(origin, results) return results async def media_detail(self, media_id: str) -> dict[str, Any]: response = await self._get_client().get(f"/api/v1/media/{media_id}") return response.data if isinstance(response.data, dict) else {} async def media_seasons( self, *, media_id: str | None = None, title: str | None = None, year: str | None = None, season: int | None = None, ) -> list[dict[str, Any]]: params: dict[str, Any] = {} if media_id: params["mediaid"] = media_id if title: params["title"] = title if year: params["year"] = year if season is not None: params["season"] = season response = await self._get_client().get("/api/v1/media/seasons", params=params) return self._as_dict_list(response.data) async def search_resources( self, origin: str, media: dict[str, Any], *, page: int = 1, count: int | None = None, ) -> list[dict[str, Any]]: media_id = self._media_id(media) if not media_id: raise ValueError("媒体结果缺少可用的媒体 ID") response = await self._get_client().get( f"/api/v1/search/media/{media_id}", params={ "page": page, "count": count or int(self._config.get("search_result_count", 5)), }, ) results = self._as_dict_list(response.data) self._session_store.set_resource_results(origin, media, results) return results @staticmethod def _media_id(media: Mapping[str, Any]) -> str: for key in ("mediaid", "media_id", "id", "mediaId", "tmdb_id", "tmdbid"): value = media.get(key) if value: return str(value) return "" @staticmethod def _as_dict_list(value: Any) -> list[dict[str, Any]]: if isinstance(value, list): return [item for item in value if isinstance(item, dict)] if isinstance(value, dict): for key in ("results", "items", "medias", "torrents"): nested = value.get(key) if isinstance(nested, list): return [item for item in nested if isinstance(item, dict)] return [] def _first_value(item: Mapping[str, Any], *keys: str) -> Any: for key in keys: value = item.get(key) if value not in (None, "", [], {}): return value return None def _format_release_month(item: Mapping[str, Any]) -> str: value = _first_value(item, "release_date", "first_air_date", "year") if value is None: return "未公布" text = str(value) if len(text) >= 7 and text[4] == "-": return text[:7] return text def media_poster_url(item: Mapping[str, Any]) -> str | None: value = _first_value(item, "poster_path", "poster", "cover_url", "cover", "image") if isinstance(value, str) and value.startswith(("http://", "https://")): return value return None def format_media_result_item(index: int, item: Mapping[str, Any]) -> str: title = _first_value(item, "title", "name", "original_title") or "未命名" tmdb_id = _first_value(item, "tmdb_id", "tmdbid", "tmdbId") if tmdb_id is None: raw_id = _first_value(item, "id") if isinstance(raw_id, str) and raw_id.lower().startswith("tmdb:"): tmdb_id = raw_id.split(":", 1)[1] episodes = _first_value( item, "number_of_episodes", "episode_count", "episodes", "total_episode", ) rating = _first_value(item, "vote_average", "rating", "vote") media_type = _first_value(item, "type_name", "type") lines = [ f"{index}. {title}", f"TMDB编号:{tmdb_id if tmdb_id is not None else '未提供'}", f"上映年月:{_format_release_month(item)}", f"集数:{episodes if episodes is not None else '未公布'}", f"评分:{rating if rating is not None else '暂无'}", ] if media_type: lines.append(f"类型:{media_type}") return "\n".join(lines) def format_media_results(results: list[dict[str, Any]]) -> str: if not results: return "没有找到匹配的影视信息。" lines = ["影视搜索结果:"] for index, item in enumerate(results, start=1): lines.append(format_media_result_item(index, item)) lines.append("可继续使用:/mp resources <编号> 或 /mp subscribe <编号>") return "\n\n".join(lines) def format_resource_results(results: list[dict[str, Any]]) -> str: if not results: return "暂未找到资源。可以使用 /mp subscribe <媒体编号> 订阅该媒体。" lines = ["资源搜索结果:"] for index, item in enumerate(results, start=1): title = item.get("title") or item.get("name") or "未命名资源" site = item.get("site_name") or item.get("site") or "未知站点" size = item.get("size") or item.get("length") or "" quality = item.get("quality") or item.get("resolution") or "" details = " / ".join(str(value) for value in (site, size, quality) if value) lines.append(f"{index}. {title}({details})") lines.append("可使用 /mp download <编号> 选择资源下载。") return "\n".join(lines)