astrbot_plugin_jmdowloads/services/archive.py
2026-07-07 00:16:40 +08:00

155 行
5 KiB
Python

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(
[
'<?xml version="1.0" encoding="utf-8"?>',
"<ComicInfo>",
f" <Title>{escape(book_name)}</Title>",
f" <Series>{escape(series_name)}</Series>",
f" <Number>{escape(downloaded.comic_id)}</Number>",
f" <PageCount>{len(downloaded.image_files)}</PageCount>",
f" <Year>{now.year}</Year>",
f" <Month>{now.month}</Month>",
f" <Day>{now.day}</Day>",
" <Format>Digital</Format>",
" <Manga>YesAndRightToLeft</Manga>",
" <LanguageISO>zh</LanguageISO>",
f" <Web>{escape(downloaded.source_url)}</Web>",
f" <Summary>{escape('JM album ' + downloaded.comic_id)}</Summary>",
"</ComicInfo>",
"",
],
)
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)