astrbot_plugin_jmdowloads/services/archive.py

156 行
5 KiB
Python

2026-07-07 00:01:44 +08:00
from __future__ import annotations
import asyncio
import os
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
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 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,
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()
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,
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:
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:
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)