from __future__ import annotations import asyncio import os import zipfile from dataclasses import dataclass from datetime import datetime from pathlib import Path from xml.sax.saxutils import escape from PIL import Image from .download import DownloadedComic from .images import safe_filename from .settings import PluginSettings @dataclass(frozen=True) class ArchiveResult: path: Path series_dir: Path series_name: str book_name: str archive_format: str existed: bool page_count: int class ArchiveError(Exception): pass class ArchiveService: def __init__(self, settings: PluginSettings) -> None: self.settings = settings async def archive(self, downloaded: DownloadedComic) -> ArchiveResult: return await asyncio.to_thread(self._archive_sync, downloaded) def _archive_sync(self, downloaded: DownloadedComic) -> ArchiveResult: series_name = safe_filename(downloaded.title, fallback=f"JM {downloaded.comic_id}") book_name = safe_filename(f"{series_name} [{downloaded.comic_id}]") series_dir = self.settings.archive_root / series_name series_dir.mkdir(parents=True, exist_ok=True) suffix = ".cbz" if self.settings.archive_format == "cbz" else ".pdf" target_path = series_dir / f"{book_name}{suffix}" if target_path.exists() and not self.settings.overwrite_existing: return ArchiveResult( path=target_path, series_dir=series_dir, series_name=series_name, book_name=book_name, archive_format=self.settings.archive_format, existed=True, page_count=len(downloaded.image_files), ) tmp_path = target_path.with_suffix(f"{target_path.suffix}.tmp") if tmp_path.exists(): tmp_path.unlink() if self.settings.archive_format == "cbz": self._create_cbz(tmp_path, downloaded, series_name, book_name) else: self._create_pdf(tmp_path, downloaded) os.replace(tmp_path, target_path) return ArchiveResult( path=target_path, series_dir=series_dir, series_name=series_name, book_name=book_name, archive_format=self.settings.archive_format, existed=False, page_count=len(downloaded.image_files), ) def _create_cbz( self, target_path: Path, downloaded: DownloadedComic, series_name: str, book_name: str, ) -> None: with zipfile.ZipFile(target_path, "w", compression=zipfile.ZIP_DEFLATED) as archive: self._writestr( archive, "ComicInfo.xml", self._comic_info_xml(downloaded, series_name, book_name).encode("utf-8"), ) for index, image_path in enumerate(downloaded.image_files, start=1): page_name = f"{index:04d}{image_path.suffix.lower()}" archive.write(image_path, page_name) def _create_pdf(self, target_path: Path, downloaded: DownloadedComic) -> None: images: list[Image.Image] = [] try: for image_path in downloaded.image_files: image = Image.open(image_path) if image.mode != "RGB": image = image.convert("RGB") images.append(image) if not images: raise ArchiveError("no images available for PDF creation") images[0].save( target_path, "PDF", save_all=True, append_images=images[1:], ) finally: for image in images: image.close() def _comic_info_xml( self, downloaded: DownloadedComic, series_name: str, book_name: str, ) -> str: now = datetime.now() return "\n".join( [ '', "", f" {escape(book_name)}", f" {escape(series_name)}", f" {escape(downloaded.comic_id)}", f" {len(downloaded.image_files)}", f" {now.year}", f" {now.month}", f" {now.day}", " Digital", " YesAndRightToLeft", " zh", f" {escape(downloaded.source_url)}", f" {escape('JM album ' + downloaded.comic_id)}", "", "", ], ) def _writestr( self, archive: zipfile.ZipFile, archive_name: str, content: bytes, ) -> None: info = zipfile.ZipInfo(archive_name) info.compress_type = zipfile.ZIP_DEFLATED info.external_attr = 0o644 << 16 archive.writestr(info, content)