diff --git a/download_service.py b/download_service.py new file mode 100644 index 0000000..0d935cf --- /dev/null +++ b/download_service.py @@ -0,0 +1,61 @@ +"""MoviePilot download task 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 DownloadService: + """Coordinate download task 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 list_tasks(self, name: str | None = None) -> list[dict[str, Any]]: + params = {"name": name} if name else None + response = await self._get_client().get("/api/v1/download/", params=params) + return MediaService._as_dict_list(response.data) + + async def start(self, task_id: str) -> dict[str, Any]: + response = await self._get_client().get(f"/api/v1/download/start/{task_id}") + return response.data if isinstance(response.data, dict) else {} + + async def stop(self, task_id: str) -> dict[str, Any]: + response = await self._get_client().get(f"/api/v1/download/stop/{task_id}") + return response.data if isinstance(response.data, dict) else {} + + async def delete(self, task_id: str) -> dict[str, Any]: + response = await self._get_client().delete(f"/api/v1/download/{task_id}") + return response.data if isinstance(response.data, dict) else {} + + +def format_download_tasks(tasks: list[dict[str, Any]]) -> str: + if not tasks: + return "当前没有下载任务。" + lines = ["下载任务:"] + for item in tasks: + task_id = item.get("download_id") or item.get("hash") or item.get("id") or "?" + title = item.get("name") or item.get("title") or "未命名任务" + state = item.get("state") or item.get("status") or "" + progress = item.get("progress") or item.get("percent") or "" + suffix = " / ".join(str(value) for value in (state, progress) if value) + lines.append(f"{task_id}: {title}" + (f"({suffix})" if suffix else "")) + return "\n".join(lines) diff --git a/main.py b/main.py index df33c5e..fdb4a66 100644 --- a/main.py +++ b/main.py @@ -8,6 +8,7 @@ from media_service import MediaService, format_media_results, format_resource_re from session_context import SessionContextStore from confirmation import ConfirmationStore from subscription_service import SubscriptionService, format_subscriptions +from download_service import DownloadService, format_download_tasks @star.register( @@ -29,6 +30,7 @@ class MoviePilotPlugin(star.Star): ) self.media_service = MediaService(config, self.session_store) self.subscription_service = SubscriptionService(config) + self.download_service = DownloadService(config) self.confirmations = ConfirmationStore() logger.info("MoviePilot 插件已加载") @@ -155,10 +157,45 @@ class MoviePilotPlugin(star.Star): yield event.plain_result(f"查询订阅失败:{exc}") @moviepilot.command("download", alias={"下载"}) - async def download_resource(self, event: AstrMessageEvent, resource_index: int) -> None: - """创建立即下载确认请求。""" + async def download_resource(self, event: AstrMessageEvent, target: str) -> None: + """创建立即下载确认请求或控制已有下载任务。""" if not self.access_policy.is_allowed(event): return + parts = target.split(maxsplit=1) + if parts and parts[0] in {"start", "开始", "stop", "暂停", "delete", "删除"}: + if len(parts) != 2 or not parts[1].strip(): + yield event.plain_result("用法:/mp download start|stop|delete <任务ID>") + return + action, task_id = parts[0], parts[1].strip() + if action in {"delete", "删除"}: + request = self.confirmations.create( + session_origin=event.unified_msg_origin, + user_id=event.get_sender_id(), + operation="delete_download", + target={"task_id": task_id}, + ) + yield event.plain_result( + f"准备删除下载任务 {task_id}。请回复:/mp confirm {request.code}" + ) + return + try: + result = ( + await self.download_service.start(task_id) + if action in {"start", "开始"} + else await self.download_service.stop(task_id) + ) + state = "开始" if action in {"start", "开始"} else "暂停" + yield event.plain_result(f"已发送{state}任务请求:{task_id}\n{result or '操作成功'}") + except Exception as exc: + logger.warning(f"MoviePilot 下载任务控制失败: {exc}") + yield event.plain_result(f"下载任务操作失败:{exc}") + return + + try: + resource_index = int(target) + except ValueError: + yield event.plain_result("用法:/mp download <资源编号>,或 /mp download start|stop|delete <任务ID>") + return origin = event.unified_msg_origin resource = self.session_store.get_resource_result(origin, resource_index) media = self.session_store.get_resource_media(origin) @@ -197,13 +234,46 @@ class MoviePilotPlugin(star.Star): download_id = result.get("download_id") or result.get("id") or "未知" yield event.plain_result(f"下载任务已提交,任务 ID:{download_id}") return + if request.operation == "delete_download": + task_id = str(request.target["task_id"]) + await self.download_service.delete(task_id) + yield event.plain_result(f"已删除下载任务:{task_id}") + return yield event.plain_result("不支持的确认操作。") except Exception as exc: logger.warning(f"MoviePilot 确认操作失败: {exc}") yield event.plain_result(f"操作失败:{exc}") + @moviepilot.command("downloads", alias={"下载列表"}) + async def list_downloads(self, event: AstrMessageEvent) -> None: + """查询当前下载任务。""" + if not self.access_policy.is_allowed(event): + return + try: + tasks = await self.download_service.list_tasks() + yield event.plain_result(format_download_tasks(tasks)) + except Exception as exc: + logger.warning(f"MoviePilot 查询下载任务失败: {exc}") + yield event.plain_result(f"查询下载任务失败:{exc}") + + @moviepilot.command("cancel", alias={"取消"}) + async def cancel_confirmation(self, event: AstrMessageEvent) -> None: + """取消当前会话的待确认操作。""" + if not self.access_policy.is_allowed(event): + return + pending = [ + item + for item in self.confirmations.snapshot() + if item["session_origin"] == event.unified_msg_origin + and item["user_id"] == event.get_sender_id() + ] + for item in pending: + self.confirmations.cancel(item["code"]) + yield event.plain_result("已取消待确认操作。" if pending else "当前没有待确认操作。") + async def terminate(self) -> None: """释放插件资源。""" await self.media_service.close() await self.subscription_service.close() + await self.download_service.close() logger.info("MoviePilot 插件已停止") diff --git a/tests/test_download_service.py b/tests/test_download_service.py new file mode 100644 index 0000000..4e6eeca --- /dev/null +++ b/tests/test_download_service.py @@ -0,0 +1,55 @@ +import pytest + +from download_service import DownloadService, format_download_tasks + + +class FakeResponse: + def __init__(self, data): + self.data = data + + +class FakeClient: + def __init__(self): + self.calls = [] + + async def get(self, path, *, params=None): + self.calls.append(("GET", path, params)) + if path != "/api/v1/download/": + return FakeResponse({"ok": True}) + return FakeResponse([{"download_id": "abc", "name": "沙丘", "state": "下载中"}]) + + async def delete(self, path, *, params=None): + self.calls.append(("DELETE", path, params)) + return FakeResponse({"ok": True}) + + +@pytest.fixture +def service(): + service = DownloadService({}) + service._client = FakeClient() + return service + + +@pytest.mark.asyncio +async def test_download_task_operations(service) -> None: + assert (await service.list_tasks())[0]["download_id"] == "abc" + assert (await service.start("abc"))["ok"] + assert (await service.stop("abc"))["ok"] + assert (await service.delete("abc"))["ok"] + assert service._client.calls == [ + ("GET", "/api/v1/download/", None), + ("GET", "/api/v1/download/start/abc", None), + ("GET", "/api/v1/download/stop/abc", None), + ("DELETE", "/api/v1/download/abc", None), + ] + + +def test_format_download_tasks() -> None: + text = format_download_tasks( + [{"download_id": "abc", "name": "沙丘", "state": "下载中"}] + ) + + assert "abc" in text + assert "沙丘" in text + assert "下载中" in text + assert "当前没有下载任务" in format_download_tasks([])