astrbot_plugin_jmdowloads/services/archive.py

205 行
6.9 KiB
Python

2026-07-07 00:01:44 +08:00
from __future__ import annotations
import asyncio
import os
2026-07-07 00:28:06 +08:00
import tempfile
2026-07-07 00:01:44 +08:00
import zipfile
from dataclasses import dataclass
2026-07-07 00:16:40 +08:00
from datetime import datetime
2026-07-07 00:01:44 +08:00
from pathlib import Path
from xml.sax.saxutils import escape
from PIL import Image
from .download import DownloadedComic
2026-07-07 00:31:54 +08:00
from .errors import ArchiveError
2026-07-07 00:01:44 +08:00
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
2026-07-07 00:16:40 +08:00
archive_format: str
2026-07-07 00:01:44 +08:00
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,
2026-07-07 00:16:40 +08:00
archive_format=self.settings.archive_format,
2026-07-07 00:01:44 +08:00
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()
2026-07-07 00:35:15 +08:00
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
2026-07-07 00:01:44 +08:00
os.replace(tmp_path, target_path)
return ArchiveResult(
path=target_path,
series_dir=series_dir,
series_name=series_name,
book_name=book_name,
2026-07-07 00:16:40 +08:00
archive_format=self.settings.archive_format,
2026-07-07 00:01:44 +08:00
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:
2026-07-07 00:16:40 +08:00
self._writestr(
archive,
2026-07-07 00:01:44 +08:00
"ComicInfo.xml",
2026-07-07 00:16:40 +08:00
self._comic_info_xml(downloaded, series_name, book_name).encode("utf-8"),
2026-07-07 00:01:44 +08:00
)
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:
2026-07-07 00:28:06 +08:00
if not downloaded.image_files:
2026-07-07 00:31:54 +08:00
raise ArchiveError("没有可用于生成 PDF 的图片")
2026-07-07 00:28:06 +08:00
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:
2026-07-07 00:01:44 +08:00
images: list[Image.Image] = []
try:
2026-07-07 00:28:06 +08:00
for image_path in image_files:
images.append(self._open_pdf_image(image_path))
2026-07-07 00:01:44 +08:00
if not images:
2026-07-07 00:31:54 +08:00
raise ArchiveError("当前 PDF 分块没有可用图片")
2026-07-07 00:01:44 +08:00
images[0].save(
target_path,
"PDF",
save_all=True,
append_images=images[1:],
)
finally:
for image in images:
image.close()
2026-07-07 00:28:06 +08:00
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:
2026-07-07 00:31:54 +08:00
raise ArchiveError("没有生成任何 PDF 分块")
2026-07-07 00:28:06 +08:00
try:
from PyPDF2 import PdfMerger
except ImportError as exc:
2026-07-07 00:31:54 +08:00
raise ArchiveError("缺少 PyPDF2 依赖,请检查插件 requirements.txt") from exc
2026-07-07 00:28:06 +08:00
merger = PdfMerger()
try:
for temp_pdf in temp_pdfs:
merger.append(str(temp_pdf))
merger.write(str(target_path))
finally:
merger.close()
2026-07-07 00:01:44 +08:00
def _comic_info_xml(
self,
downloaded: DownloadedComic,
series_name: str,
book_name: str,
) -> str:
2026-07-07 00:16:40 +08:00
now = datetime.now()
2026-07-07 00:01:44 +08:00
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>",
2026-07-07 00:16:40 +08:00
f" <Year>{now.year}</Year>",
f" <Month>{now.month}</Month>",
f" <Day>{now.day}</Day>",
" <Format>Digital</Format>",
2026-07-07 00:01:44 +08:00
" <Manga>YesAndRightToLeft</Manga>",
2026-07-07 00:16:40 +08:00
" <LanguageISO>zh</LanguageISO>",
f" <Web>{escape(downloaded.source_url)}</Web>",
f" <Summary>{escape('JM album ' + downloaded.comic_id)}</Summary>",
2026-07-07 00:01:44 +08:00
"</ComicInfo>",
"",
],
)
2026-07-07 00:16:40 +08:00
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)