astrbot_plugin_jmdowloads/main.py
2026-07-07 00:31:54 +08:00

187 行
7.5 KiB
Python

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

from __future__ import annotations
import asyncio
from pathlib import Path
from astrbot.api import AstrBotConfig, logger
from astrbot.api.event import AstrMessageEvent, filter
import astrbot.api.message_components as Comp
from astrbot.api.star import Context, Star, StarTools
from .services.archive import ArchiveResult, ArchiveService
from .services.download import DownloadProgress, JMDownloadService
from .services.errors import JMDownloadError
from .services.komga import KomgaClient, KomgaScanResult
from .services.settings import PluginSettings
class JMDownloadPlugin(Star):
def __init__(self, context: Context, config: AstrBotConfig | None = None) -> None:
super().__init__(context, config)
data_dir = self._get_data_dir()
self.config = config or {}
self.settings = PluginSettings.from_config(dict(self.config), data_dir)
self.settings.ensure_dirs()
self.downloader = JMDownloadService(self.settings)
self.archiver = ArchiveService(self.settings)
self.komga = KomgaClient(self.settings.komga)
self.task_semaphore = asyncio.Semaphore(self.settings.max_concurrent_tasks)
async def initialize(self) -> None:
logger.info(
"JMDownload initialized: "
f"archive_root={self.settings.archive_root}, "
f"format={self.settings.archive_format}, "
f"komga={self.settings.komga.enabled}",
)
async def terminate(self) -> None:
logger.info("JMDownload terminated")
@filter.command_group("jm", alias={"JM", "Jm", "jM"})
def jm(self):
pass
@jm.command("download", alias={"下载"})
async def download(self, event: AstrMessageEvent, comic_id: str):
"""Download a JM album, archive it, and optionally ask Komga to scan."""
if self._deny_non_admin(event):
yield event.plain_result("JMDownload is admin-only in the current config.")
event.stop_event()
return
comic_id = comic_id.strip()
if not comic_id.isdigit():
yield event.plain_result("Usage: /jm download <numeric_id>")
event.stop_event()
return
await event.send(event.plain_result(f"开始下载 JM {comic_id},任务已进入队列。"))
file_send_message = ""
try:
async with self.task_semaphore:
await event.send(event.plain_result(f"开始执行 JM {comic_id} 下载任务。"))
downloaded = await self.downloader.download(
comic_id,
progress_callback=lambda progress: self._send_progress(event, progress),
)
archive_result = await self.archiver.archive(downloaded)
self.downloader.cleanup(downloaded)
scan_result = await self.komga.scan_library()
if self.settings.send_archive_file:
file_send_message = await self._send_archive_file(event, archive_result)
except JMDownloadError as exc:
logger.warning(f"JMDownload expected failure for {comic_id}: {exc}")
yield event.plain_result(f"JMDownload 失败:{exc.user_message}")
event.stop_event()
return
except Exception as exc:
logger.exception(f"JMDownload failed for {comic_id}")
yield event.plain_result("JMDownload 发生未预期错误,请查看 AstrBot 日志。")
event.stop_event()
return
yield event.plain_result(
self._format_success(archive_result, scan_result, file_send_message),
)
event.stop_event()
@jm.command("status")
async def status(self, event: AstrMessageEvent):
"""Show current JMDownload archive and Komga settings."""
lines = [
"JMDownload 状态",
f"归档目录:{self.settings.archive_root}",
f"归档格式:{self.settings.archive_format}",
f"PDF 分块大小:{self.settings.pdf_chunk_size}",
f"并发任务数:{self.settings.max_concurrent_tasks}",
f"下载重试次数:{self.settings.download_retry_count}",
f"进度提示间隔:{self.settings.progress_interval_seconds} 秒",
f"发送归档文件:{self.settings.send_archive_file}",
f"Komga 自动扫描:{self.settings.komga.enabled}",
f"Komga 配置完整:{self.settings.komga.can_scan}",
f"Komga 地址:{self.settings.komga.base_url or '未配置'}",
f"Komga Library ID:{self.settings.komga.library_id or '未配置'}",
]
yield event.plain_result("\n".join(lines))
event.stop_event()
@jm.command("scan")
async def scan(self, event: AstrMessageEvent):
"""Trigger a Komga scan for the configured library."""
if self._deny_non_admin(event):
yield event.plain_result("JMDownload is admin-only in the current config.")
event.stop_event()
return
await event.send(event.plain_result("正在触发 Komga 扫描..."))
result = await self.komga.scan_library()
yield event.plain_result(result.message)
event.stop_event()
def _deny_non_admin(self, event: AstrMessageEvent) -> bool:
return bool(self.settings.admin_only and not event.is_admin())
def _format_success(
self,
archive_result: ArchiveResult,
scan_result: KomgaScanResult,
file_send_message: str = "",
) -> str:
existed = "复用已有归档" if archive_result.existed else "已创建归档"
lines = [
f"JMDownload 完成:{existed}",
f"系列:{archive_result.series_name}",
f"格式:{archive_result.archive_format}",
f"页数:{archive_result.page_count}",
f"文件:{archive_result.path}",
f"Komga: {scan_result.message}",
]
if file_send_message:
lines.append(file_send_message)
return "\n".join(lines)
async def _send_archive_file(
self,
event: AstrMessageEvent,
archive_result: ArchiveResult,
) -> str:
if not archive_result.path.exists():
return "文件发送:归档文件不存在,已跳过发送。"
try:
await event.send(
event.chain_result(
[
Comp.File(
name=archive_result.path.name,
file=str(archive_result.path.resolve()),
),
],
),
)
return "文件发送:已尝试发送归档文件。"
except Exception as exc:
logger.warning(f"JMDownload: file send failed: {exc}")
return f"文件发送:平台发送失败,归档仍保存在本地。原因:{exc}"
async def _send_progress(
self,
event: AstrMessageEvent,
progress: DownloadProgress,
) -> None:
await event.send(
event.plain_result(
"下载进度:"
f"JM {progress.comic_id} "
f"第 {progress.attempt}/{progress.max_attempts} 次尝试,"
f"已发现 {progress.image_count} 张图片"
),
)
def _get_data_dir(self) -> Path:
try:
return StarTools.get_data_dir("astrbot_plugin_jmdownload")
except Exception:
fallback = Path("data/plugin_data/astrbot_plugin_jmdownload")
fallback.mkdir(parents=True, exist_ok=True)
return fallback.resolve()