"""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)