astrbot_plugin_jmdowloads/services/archive.py
2026-07-07 00:35:15 +08:00

204 行
6.9 KiB
Python

from __future__ import annotations
import asyncio
import os
import tempfile
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 .errors import ArchiveError
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 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()
try:
if self.settings.archive_format == "cbz":
self._create_cbz(tmp_path, downloaded, series_name, book_name)
else:
self._create_pdf(tmp_path, downloaded)
except Exception:
if tmp_path.exists():
tmp_path.unlink()
raise
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:
if not downloaded.image_files:
raise ArchiveError("没有可用于生成 PDF 的图片")
with tempfile.TemporaryDirectory(
prefix=".jm_pdf_",
dir=str(target_path.parent),
) as temp_dir:
temp_dir_path = Path(temp_dir)
temp_pdfs = self._create_pdf_chunks(downloaded.image_files, temp_dir_path)
self._merge_pdf_chunks(temp_pdfs, target_path)
def _create_pdf_chunks(
self,
image_files: list[Path],
temp_dir: Path,
) -> list[Path]:
temp_pdfs: list[Path] = []
chunk_size = self.settings.pdf_chunk_size
for chunk_index, start in enumerate(range(0, len(image_files), chunk_size), start=1):
chunk_paths = image_files[start : start + chunk_size]
chunk_pdf = temp_dir / f"part-{chunk_index:04d}.pdf"
self._write_pdf_chunk(chunk_pdf, chunk_paths)
temp_pdfs.append(chunk_pdf)
return temp_pdfs
def _write_pdf_chunk(self, target_path: Path, image_files: list[Path]) -> None:
images: list[Image.Image] = []
try:
for image_path in image_files:
images.append(self._open_pdf_image(image_path))
if not images:
raise ArchiveError("当前 PDF 分块没有可用图片")
images[0].save(
target_path,
"PDF",
save_all=True,
append_images=images[1:],
)
finally:
for image in images:
image.close()
def _open_pdf_image(self, image_path: Path) -> Image.Image:
with Image.open(image_path) as image:
if image.mode != "RGB":
image = image.convert("RGB")
else:
image = image.copy()
return image
def _merge_pdf_chunks(self, temp_pdfs: list[Path], target_path: Path) -> None:
if not temp_pdfs:
raise ArchiveError("没有生成任何 PDF 分块")
try:
from PyPDF2 import PdfMerger
except ImportError as exc:
raise ArchiveError("缺少 PyPDF2 依赖,请检查插件 requirements.txt") from exc
merger = PdfMerger()
try:
for temp_pdf in temp_pdfs:
merger.append(str(temp_pdf))
merger.write(str(target_path))
finally:
merger.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)