astrbot_plugin_jmdowloads/main.py

159 行
6.3 KiB
Python

2026-07-07 00:01:44 +08:00
from __future__ import annotations
2026-07-07 00:13:26 +08:00
import asyncio
2026-07-07 00:01:44 +08:00
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
2026-07-07 00:13:26 +08:00
from .services.download import DownloadProgress, JMDownloadService
2026-07-07 00:01:44 +08:00
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)
2026-07-07 00:13:26 +08:00
self.task_semaphore = asyncio.Semaphore(self.settings.max_concurrent_tasks)
2026-07-07 00:01:44 +08:00
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
2026-07-07 00:13:26 +08:00
await event.send(event.plain_result(f"开始下载 JM {comic_id},任务已进入队列。"))
2026-07-07 00:01:44 +08:00
try:
2026-07-07 00:13:26 +08:00
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()
2026-07-07 00:01:44 +08:00
except Exception as exc:
logger.exception(f"JMDownload failed for {comic_id}")
2026-07-07 00:13:26 +08:00
yield event.plain_result(f"JMDownload 失败:{exc}")
2026-07-07 00:01:44 +08:00
event.stop_event()
return
if self.settings.send_archive_file:
yield event.chain_result(
[
Comp.Plain(self._format_success(archive_result, scan_result)),
Comp.File(name=archive_result.path.name, file=str(archive_result.path)),
],
)
else:
yield event.plain_result(self._format_success(archive_result, scan_result))
event.stop_event()
@jm.command("status")
async def status(self, event: AstrMessageEvent):
"""Show current JMDownload archive and Komga settings."""
lines = [
2026-07-07 00:13:26 +08:00
"JMDownload 状态",
f"归档目录:{self.settings.archive_root}",
f"归档格式:{self.settings.archive_format}",
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}",
2026-07-07 00:19:34 +08:00
f"Komga 地址:{self.settings.komga.base_url or '未配置'}",
f"Komga Library ID:{self.settings.komga.library_id or '未配置'}",
2026-07-07 00:01:44 +08:00
]
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
2026-07-07 00:19:34 +08:00
await event.send(event.plain_result("正在触发 Komga 扫描..."))
2026-07-07 00:01:44 +08:00
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,
) -> str:
2026-07-07 00:13:26 +08:00
existed = "复用已有归档" if archive_result.existed else "已创建归档"
2026-07-07 00:01:44 +08:00
return "\n".join(
[
2026-07-07 00:13:26 +08:00
f"JMDownload 完成:{existed}",
f"系列:{archive_result.series_name}",
2026-07-07 00:16:40 +08:00
f"格式:{archive_result.archive_format}",
2026-07-07 00:13:26 +08:00
f"页数:{archive_result.page_count}",
f"文件:{archive_result.path}",
2026-07-07 00:01:44 +08:00
f"Komga: {scan_result.message}",
],
)
2026-07-07 00:13:26 +08:00
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} 张图片"
),
)
2026-07-07 00:01:44 +08:00
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()