diff --git a/main.py b/main.py index 6fef944..df33c5e 100644 --- a/main.py +++ b/main.py @@ -6,6 +6,8 @@ from astrbot.api.event import AstrMessageEvent, filter from access_policy import AccessPolicy from media_service import MediaService, format_media_results, format_resource_results from session_context import SessionContextStore +from confirmation import ConfirmationStore +from subscription_service import SubscriptionService, format_subscriptions @star.register( @@ -26,6 +28,8 @@ class MoviePilotPlugin(star.Star): ttl=int(config.get("search_cache_ttl", 600)), ) self.media_service = MediaService(config, self.session_store) + self.subscription_service = SubscriptionService(config) + self.confirmations = ConfirmationStore() logger.info("MoviePilot 插件已加载") @filter.command_group("mp") @@ -111,7 +115,95 @@ class MoviePilotPlugin(star.Star): logger.warning(f"MoviePilot 季信息查询失败: {exc}") yield event.plain_result(f"季信息查询失败:{exc}") + @moviepilot.command("subscribe", alias={"订阅"}) + async def subscribe_media(self, event: AstrMessageEvent, media_index: int) -> None: + """创建订阅并自动触发一次搜索。""" + if not self.access_policy.is_allowed(event): + return + media = self.session_store.get_media_result(event.unified_msg_origin, media_index) + if media is None: + yield event.plain_result("媒体编号无效或已过期,请重新使用 /mp search。") + return + try: + result = await self.subscription_service.create_subscription(media) + subscribe_id = result.get("id") + if not subscribe_id: + yield event.plain_result("订阅创建失败,MoviePilot 没有返回订阅编号。") + return + message = f"已创建订阅:{media.get('title') or media.get('name') or '未命名'}(ID: {subscribe_id})" + try: + await self.subscription_service.trigger_subscription_search(int(subscribe_id)) + message += "\n已自动触发一次资源搜索。" + except Exception as exc: + logger.warning(f"订阅创建成功但触发搜索失败: {exc}") + message += f"\n订阅已保留,但自动搜索失败:{exc}" + yield event.plain_result(message) + except Exception as exc: + logger.warning(f"MoviePilot 创建订阅失败: {exc}") + yield event.plain_result(f"订阅创建失败:{exc}") + + @moviepilot.command("subscriptions", alias={"订阅列表"}) + async def list_subscriptions(self, event: AstrMessageEvent) -> None: + """查询订阅列表。""" + if not self.access_policy.is_allowed(event): + return + try: + subscriptions = await self.subscription_service.list_subscriptions() + yield event.plain_result(format_subscriptions(subscriptions)) + except Exception as exc: + logger.warning(f"MoviePilot 查询订阅失败: {exc}") + yield event.plain_result(f"查询订阅失败:{exc}") + + @moviepilot.command("download", alias={"下载"}) + async def download_resource(self, event: AstrMessageEvent, resource_index: int) -> None: + """创建立即下载确认请求。""" + if not self.access_policy.is_allowed(event): + return + origin = event.unified_msg_origin + resource = self.session_store.get_resource_result(origin, resource_index) + media = self.session_store.get_resource_media(origin) + if resource is None or media is None: + yield event.plain_result("资源编号无效或已过期,请重新使用 /mp resources。") + return + request = self.confirmations.create( + session_origin=origin, + user_id=event.get_sender_id(), + operation="download", + target={"resource": resource, "media": media}, + ) + title = resource.get("title") or resource.get("name") or "未命名资源" + yield event.plain_result( + f"准备下载:{title}\n请在 {self.confirmations.ttl} 秒内回复:/mp confirm {request.code}" + ) + + @moviepilot.command("confirm", alias={"确认"}) + async def confirm_operation(self, event: AstrMessageEvent, code: str) -> None: + """确认并执行副作用操作。""" + if not self.access_policy.is_allowed(event): + return + request = self.confirmations.consume( + code, + session_origin=event.unified_msg_origin, + user_id=event.get_sender_id(), + ) + if request is None: + yield event.plain_result("确认码无效、已过期,或不属于当前会话。") + return + try: + if request.operation == "download": + result = await self.subscription_service.download_resource( + request.target["resource"], request.target["media"] + ) + download_id = result.get("download_id") or result.get("id") or "未知" + yield event.plain_result(f"下载任务已提交,任务 ID:{download_id}") + return + yield event.plain_result("不支持的确认操作。") + except Exception as exc: + logger.warning(f"MoviePilot 确认操作失败: {exc}") + yield event.plain_result(f"操作失败:{exc}") + async def terminate(self) -> None: """释放插件资源。""" await self.media_service.close() + await self.subscription_service.close() logger.info("MoviePilot 插件已停止") diff --git a/subscription_service.py b/subscription_service.py new file mode 100644 index 0000000..b7bed41 --- /dev/null +++ b/subscription_service.py @@ -0,0 +1,165 @@ +"""MoviePilot subscription and immediate download operations.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from media_service import MediaService +from moviepilot_client import MoviePilotClient + + +class SubscriptionService: + """Coordinate MoviePilot subscription and download APIs.""" + + def __init__(self, config: Mapping[str, Any]) -> None: + self._config = config + 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 create_subscription( + self, + media: Mapping[str, Any], + *, + season: int | None = None, + ) -> dict[str, Any]: + payload = build_subscription_payload(media, season=season) + response = await self._get_client().post( + "/api/v1/subscribe/", json=payload + ) + return response.data if isinstance(response.data, dict) else {} + + async def trigger_subscription_search(self, subscribe_id: int) -> dict[str, Any]: + response = await self._get_client().get( + f"/api/v1/subscribe/search/{subscribe_id}" + ) + return response.data if isinstance(response.data, dict) else {} + + async def list_subscriptions(self) -> list[dict[str, Any]]: + response = await self._get_client().get("/api/v1/subscribe/list") + return MediaService._as_dict_list(response.data) + + async def delete_subscription( + self, media_id: str, *, season: int | None = None + ) -> dict[str, Any]: + params = {"season": season} if season is not None else None + response = await self._get_client().delete( + f"/api/v1/subscribe/media/{media_id}", params=params + ) + return response.data if isinstance(response.data, dict) else {} + + async def download_resource( + self, + resource: Mapping[str, Any], + media: Mapping[str, Any], + ) -> dict[str, Any]: + torrent = build_torrent_payload(resource) + body: dict[str, Any] = {"torrent_in": torrent} + tmdbid = _tmdb_id(media) + if tmdbid is not None: + body["tmdbid"] = tmdbid + response = await self._get_client().post( + "/api/v1/download/add", json=body + ) + return response.data if isinstance(response.data, dict) else {} + + +def _value(media: Mapping[str, Any], *keys: str) -> Any: + for key in keys: + value = media.get(key) + if value not in (None, ""): + return value + return None + + +def _tmdb_id(media: Mapping[str, Any]) -> int | None: + value = _value(media, "tmdbid", "tmdb_id") + if value is None: + media_id = _value(media, "mediaid", "media_id", "id") + if isinstance(media_id, str) and media_id.startswith("tmdb:"): + value = media_id[5:] + try: + return int(value) if value is not None else None + except (TypeError, ValueError): + return None + + +def build_subscription_payload( + media: Mapping[str, Any], *, season: int | None = None +) -> dict[str, Any]: + """Build only public-write fields accepted by MoviePilot.""" + media_id = _value(media, "mediaid", "media_id", "id") + payload: dict[str, Any] = { + "name": _value(media, "title", "name") or "", + "year": _value(media, "year", "release_date", "first_air_date"), + "type": _normalize_media_type(_value(media, "type", "type_name")), + } + tmdbid = _tmdb_id(media) + if tmdbid is not None: + payload["tmdbid"] = tmdbid + elif media_id: + payload["mediaid"] = str(media_id) + if season is not None: + payload["season"] = season + elif _value(media, "season") is not None: + payload["season"] = _value(media, "season") + return {key: value for key, value in payload.items() if value not in (None, "")} + + +def build_torrent_payload(resource: Mapping[str, Any]) -> dict[str, Any]: + """Copy only download-relevant TorrentInfo-compatible fields.""" + fields = ( + "site", + "site_name", + "title", + "description", + "imdbid", + "enclosure", + "page_url", + "size", + "seeders", + "peers", + "grabs", + "pubdate", + "freedate", + "labels", + "category", + ) + return {key: resource[key] for key in fields if key in resource} + + +def _normalize_media_type(value: Any) -> str | None: + if not value: + return None + normalized = str(value).strip().lower() + if normalized in {"movie", "电影"}: + return "movie" + if normalized in {"tv", "电视剧", "series"}: + return "tv" + return str(value) + + +def format_subscriptions(subscriptions: list[dict[str, Any]]) -> str: + if not subscriptions: + return "当前没有订阅。" + lines = ["订阅列表:"] + for item in subscriptions: + sid = item.get("id", "?") + title = item.get("name") or "未命名" + state = item.get("state") or "" + season = item.get("season") + suffix = f" / 第 {season} 季" if season is not None else "" + lines.append(f"{sid}. {title}{suffix} {state}".strip()) + return "\n".join(lines) diff --git a/tests/test_subscription_service.py b/tests/test_subscription_service.py new file mode 100644 index 0000000..b8a4b78 --- /dev/null +++ b/tests/test_subscription_service.py @@ -0,0 +1,72 @@ +import pytest + +from subscription_service import ( + SubscriptionService, + build_subscription_payload, + build_torrent_payload, +) + + +class FakeResponse: + def __init__(self, data): + self.data = data + + +class FakeClient: + def __init__(self): + self.calls = [] + + async def post(self, path, *, params=None, json=None): + self.calls.append(("POST", path, json)) + if path == "/api/v1/subscribe/": + return FakeResponse({"id": 8}) + return FakeResponse({"download_id": "download-1"}) + + async def get(self, path, *, params=None): + self.calls.append(("GET", path, params)) + return FakeResponse({"ok": True}) + + async def delete(self, path, *, params=None): + self.calls.append(("DELETE", path, params)) + return FakeResponse({"ok": True}) + + +@pytest.fixture +def service(): + service = SubscriptionService({}) + service._client = FakeClient() + return service + + +def test_subscription_payload_uses_public_media_fields() -> None: + payload = build_subscription_payload( + {"id": "tmdb:123", "title": "沙丘", "year": "2021", "type": "电影"} + ) + + assert payload == { + "name": "沙丘", + "year": "2021", + "type": "movie", + "tmdbid": 123, + } + + +def test_torrent_payload_drops_sensitive_or_unknown_fields() -> None: + payload = build_torrent_payload( + {"title": "Dune", "enclosure": "signed", "site_cookie": "secret", "extra": 1} + ) + + assert payload == {"title": "Dune", "enclosure": "signed"} + + +@pytest.mark.asyncio +async def test_subscription_and_download_requests(service) -> None: + media = {"id": "tmdb:123", "title": "沙丘", "type": "movie"} + resource = {"title": "Dune", "enclosure": "signed"} + + assert (await service.create_subscription(media))["id"] == 8 + assert (await service.trigger_subscription_search(8))["ok"] + assert (await service.download_resource(resource, media))["download_id"] == "download-1" + assert service._client.calls[0][1] == "/api/v1/subscribe/" + assert service._client.calls[1][1] == "/api/v1/subscribe/search/8" + assert service._client.calls[2][1] == "/api/v1/download/add"