from __future__ import annotations import asyncio import shutil from dataclasses import dataclass from datetime import datetime from pathlib import Path import yaml from astrbot.api import logger from .images import collect_image_files, infer_album_title from .settings import PluginSettings @dataclass(frozen=True) class DownloadedComic: comic_id: str title: str work_dir: Path download_dir: Path image_files: list[Path] class DownloadError(Exception): pass class JMDownloadService: def __init__(self, settings: PluginSettings) -> None: self.settings = settings async def download(self, comic_id: str) -> DownloadedComic: job_name = datetime.now().strftime(f"{comic_id}-%Y%m%d-%H%M%S") work_dir = self.settings.work_root / job_name download_dir = work_dir / "downloads" config_path = work_dir / "jmcomic.yml" download_dir.mkdir(parents=True, exist_ok=True) self._write_jmcomic_config(config_path, download_dir) try: title = await asyncio.wait_for( asyncio.to_thread(self._download_sync, comic_id, config_path), timeout=self.settings.download_timeout_seconds, ) except TimeoutError as exc: raise DownloadError(f"download timed out after {self.settings.download_timeout_seconds}s") from exc except Exception as exc: raise DownloadError(str(exc)) from exc image_files = collect_image_files(download_dir) if not image_files: raise DownloadError("download finished but no image files were found") return DownloadedComic( comic_id=comic_id, title=title or infer_album_title(download_dir, comic_id), work_dir=work_dir, download_dir=download_dir, image_files=image_files, ) def cleanup(self, downloaded: DownloadedComic) -> None: if not self.settings.delete_work_dir_after_archive: return if downloaded.work_dir.exists(): shutil.rmtree(downloaded.work_dir) def _download_sync(self, comic_id: str, config_path: Path) -> str: try: import jmcomic except ImportError as exc: raise DownloadError("jmcomic is not installed; check plugin requirements.txt") from exc logger.info(f"JMDownload: downloading album {comic_id} with {config_path}") option = jmcomic.create_option_by_file(str(config_path)) result = jmcomic.download_album(comic_id, option=option, check_exception=True) return self._extract_album_title(result) def _extract_album_title(self, result: object) -> str: album = getattr(result, "album", None) if album is None and isinstance(result, tuple) and result: album = result[0] title = getattr(album, "title", "") if album is not None else "" return str(title).strip() def _write_jmcomic_config(self, config_path: Path, download_dir: Path) -> None: config = { "version": "1.0", "dir_rule": { "base_dir": str(download_dir), "rule": "Bd_Atitle_Pindex", }, "client": { "domain": self.settings.jm_domains, }, "download": { "cache": True, "image": { "decode": True, "suffix": ".jpg", }, "threading": { "batch_count": self.settings.jm_batch_count, }, }, } config_path.parent.mkdir(parents=True, exist_ok=True) config_path.write_text( yaml.safe_dump(config, allow_unicode=True, sort_keys=False), encoding="utf-8", )