astrbot_plugin_moviepilot/download_service.py

68 行
2.8 KiB
Python

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

"""MoviePilot download task operations."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
try:
from .media_service import MediaService
from .moviepilot_client import MoviePilotClient
except ImportError:
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", "")),
timeout=float(self._config.get("moviepilot_timeout", 20)),
retries=int(self._config.get("moviepilot_retries", 2)),
retry_backoff=float(self._config.get("moviepilot_retry_backoff", 0.5)),
)
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)