diff --git a/app/application/configuration.py b/app/application/configuration.py index 93846e728..fbc36b582 100644 --- a/app/application/configuration.py +++ b/app/application/configuration.py @@ -245,6 +245,7 @@ class ChainRuntimeConfig: search_threadpool_size: int = 1 transfer_threads: int = 1 transfer_failure_notification_aggregation: bool = True + transfer_success_notification_aggregation: bool = True transfer_task_timeout: int = 120 scrape_follow_tmdb: bool = True metadata_cache_ttl: int = 3600 diff --git a/app/application/settings/resources/system_settings_catalog.json b/app/application/settings/resources/system_settings_catalog.json index 160e24015..a09e02579 100644 --- a/app/application/settings/resources/system_settings_catalog.json +++ b/app/application/settings/resources/system_settings_catalog.json @@ -1447,6 +1447,12 @@ "source_file": "app/runtime/config.py", "source_line": 643 }, + "TRANSFER_SUCCESS_NOTIFICATION_AGGREGATION": { + "description": "是否按批次聚合电影、电视剧和音乐的整理成功通知", + "group": "ai_agent", + "source_file": "app/runtime/config.py", + "source_line": 882 + }, "TRANSFER_TASK_TIMEOUT": { "description": "外部接管的运行中整理任务无状态心跳超时(分钟),0 表示禁用", "group": "transfer", diff --git a/app/application/transfer/notifications.py b/app/application/transfer/notifications.py index db9e1d9ea..33edefd3f 100644 --- a/app/application/transfer/notifications.py +++ b/app/application/transfer/notifications.py @@ -1,15 +1,20 @@ -"""整理失败通知的分组键和短暂聚合。""" +"""整理结果通知的分组、批次等待和短暂聚合。""" from __future__ import annotations import asyncio import threading +from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Callable +from typing import TYPE_CHECKING, Callable, Optional from app.application.transfer.feedback import TransferFailureNotification +from app.domain.context import MediaInfo, MusicInfo +from app.domain.meta.metabase import MetaBase from app.runtime.log import logger from app.schemas.media import resolve_media_identity +from app.schemas.tmdb import TmdbEpisode +from app.schemas.transfer import TransferInfo if TYPE_CHECKING: from app.application.transfer.models import TransferTask @@ -31,20 +36,42 @@ def build_transfer_failure_group_key(task: TransferTask) -> str: return f"path:{parent_path or source_path}:user:{username}" -class TransferFailureNotificationAggregator: - """在短暂静默窗口内按媒体合并整理失败通知。""" +@dataclass(frozen=True, slots=True) +class TransferSuccessNotification: + """保存逐任务成功结果副本,避免后续作业统计修改已缓冲通知。""" + + meta: MetaBase + mediainfo: MediaInfo | MusicInfo + transferinfo: TransferInfo + episodes_info: Optional[list[TmdbEpisode]] + username: Optional[str] + + +def build_transfer_success_group_key(task: TransferTask, result: TransferInfo) -> str: + """按下载来源、媒体目录、季和用户隔离成功通知,避免跨专辑或用户混发。""" + directory = result.target_diritem + destination = (directory.storage, directory.path) if directory else (task.target_storage, str(task.target_path)) + source = (task.downloader, task.download_hash) if task.download_hash else (task.fileitem.storage, str(Path(task.fileitem.path or "").parent)) + season = getattr(task.meta, "begin_season", None) + return repr((source, destination, season, task.username)) + + +class TransferNotificationAggregator[Notification]: + """在线程安全缓冲中等待明确批次结束,或按静默窗口合并通知。""" NOTIFICATION_DEBOUNCE_SECONDS = 30 def __init__(self) -> None: """初始化分组缓冲、回调、定时器与关闭状态。""" - self._buffers: dict[str, list[TransferFailureNotification]] = {} + self._buffers: dict[str, list[Notification]] = {} self._callbacks: dict[ str, - Callable[[list[TransferFailureNotification]], None], + Callable[[list[Notification]], None], ] = {} self._timers: dict[str, asyncio.TimerHandle] = {} self._generations: dict[str, int] = {} + self._next_generation = 0 + self._waiting_batches: dict[str, set[str]] = {} self._lock = threading.Lock() self._closed = False @@ -52,19 +79,29 @@ class TransferFailureNotificationAggregator: self, *, group_key: str, - notification: TransferFailureNotification, - callback: Callable[[list[TransferFailureNotification]], None], - loop: asyncio.AbstractEventLoop, + notification: Notification, + callback: Callable[[list[Notification]], None], + loop: Optional[asyncio.AbstractEventLoop] = None, + defer_until: Optional[str] = None, ) -> None: - """从整理线程安全地把失败快照加入事件循环中的聚合缓冲。""" + """先登记快照;明确批次由完成信号刷新,其余通知使用事件循环静默窗口。""" # 先在调用线程登记快照,关闭流程才能覆盖已接收但尚未进入事件循环的通知。 with self._lock: if self._closed: - raise RuntimeError("整理失败通知聚合器正在关闭,不能再接收通知") + raise RuntimeError("整理通知聚合器正在关闭,不能再接收通知") self._buffers.setdefault(group_key, []).append(notification) self._callbacks[group_key] = callback - generation = self._generations.get(group_key, 0) + 1 + # 分组刷新后也不复用代号,避免旧回调命中新创建的同名分组。 + self._next_generation += 1 + generation = self._next_generation self._generations[group_key] = generation + if defer_until: + self._waiting_batches.setdefault(group_key, set()).add(defer_until) + if defer_until: + return + if loop is None: + self.flush(group_key, generation, callback) + return try: loop.call_soon_threadsafe( self._schedule_on_loop, @@ -75,7 +112,7 @@ class TransferFailureNotificationAggregator: ) except Exception as err: logger.error( - f"创建整理失败通知聚合定时器失败,将立即发送 " + f"创建整理通知聚合定时器失败,将立即发送 " f"(group={group_key}): {err}" ) self.flush(group_key, generation, callback) @@ -84,7 +121,7 @@ class TransferFailureNotificationAggregator: self, group_key: str, generation: int, - callback: Callable[[list[TransferFailureNotification]], None], + callback: Callable[[list[Notification]], None], loop: asyncio.AbstractEventLoop, ) -> None: """在所属事件循环中为已登记缓冲重置静默窗口。""" @@ -94,6 +131,7 @@ class TransferFailureNotificationAggregator: self._closed or group_key not in self._buffers or self._generations.get(group_key) != generation + or self._waiting_batches.get(group_key) ): return timer = self._timers.pop(group_key, None) @@ -111,7 +149,7 @@ class TransferFailureNotificationAggregator: schedule_error = err if schedule_error is not None: logger.error( - f"创建整理失败通知聚合定时器失败,将立即发送 " + f"创建整理通知聚合定时器失败,将立即发送 " f"(group={group_key}): {schedule_error}" ) self.flush(group_key, generation, callback) @@ -120,34 +158,46 @@ class TransferFailureNotificationAggregator: self, group_key: str, generation: int, - callback: Callable[[list[TransferFailureNotification]], None], + callback: Callable[[list[Notification]], None], ) -> None: """发送一个分组内的聚合结果并释放缓冲。""" with self._lock: # 新通知已登记但 timer 重置回调尚未执行时,旧代不得提前发送新批次。 - if self._generations.get(group_key) != generation: + if self._generations.get(group_key) != generation or self._waiting_batches.get(group_key): return notifications = self._buffers.pop(group_key, []) self._callbacks.pop(group_key, None) timer = self._timers.pop(group_key, None) self._generations.pop(group_key, None) + self._waiting_batches.pop(group_key, None) if timer: timer.cancel() if not notifications: return self._deliver(group_key, notifications, callback) + def release_batch(self, batch_id: str) -> None: + """批次全部终结后刷新相关分组;单文件批次同样即时发送且不等待静默窗。""" + with self._lock: + ready = [] + for group_key, batches in self._waiting_batches.items(): + batches.discard(batch_id) + if not batches: + ready.append((group_key, self._generations[group_key], self._callbacks[group_key])) + for group_key, generation, callback in ready: + self.flush(group_key, generation, callback) + @staticmethod def _deliver( group_key: str, - notifications: list[TransferFailureNotification], - callback: Callable[[list[TransferFailureNotification]], None], + notifications: list[Notification], + callback: Callable[[list[Notification]], None], ) -> None: """调用聚合通知回调,并统一观察发送异常。""" try: callback(notifications) except Exception as err: - logger.error(f"发送整理失败聚合通知失败 (group={group_key}): {err}") + logger.error(f"发送整理聚合通知失败 (group={group_key}): {err}") def close(self) -> None: """停止接收新通知,取消定时器并同步发送全部已缓冲通知。""" @@ -168,13 +218,18 @@ class TransferFailureNotificationAggregator: self._generations.clear() self._buffers.clear() self._callbacks.clear() + self._waiting_batches.clear() for timer in timers: timer.cancel() for group_key, notification_count in orphaned: logger.error( - f"整理失败通知聚合缓冲缺少发送回调,无法刷新 " + f"整理通知聚合缓冲缺少发送回调,无法刷新 " f"(group={group_key}, count={notification_count})" ) for group_key, notifications, callback in pending: self._deliver(group_key, notifications, callback) + + +class TransferFailureNotificationAggregator(TransferNotificationAggregator[TransferFailureNotification]): + """保留失败通知已有入口及三十秒静默聚合行为。""" diff --git a/app/chain/transfer/contract.py b/app/chain/transfer/contract.py index 425d25379..6f22d48aa 100644 --- a/app/chain/transfer/contract.py +++ b/app/chain/transfer/contract.py @@ -27,6 +27,7 @@ if TYPE_CHECKING: download_history_repository: Any eventmanager: Any failure_notification_aggregator: Any + success_notification_aggregator: Any jobview: Any runtime_config: Any transfer_admission_repository: Any @@ -127,6 +128,9 @@ if TYPE_CHECKING: remove_torrents: Callable[..., Any] run_module: Callable[..., Any] send_transfer_message: Callable[..., Any] + notify_successful_transfer: Callable[..., Any] + queue_successful_transfer_notification: Callable[..., Any] + _send_transfer_success_notifications: Callable[..., Any] torrent_files: Callable[..., Any] transfer_completed: Callable[..., Any] diff --git a/app/chain/transfer/history.py b/app/chain/transfer/history.py index 20fd35f11..e73b2fa09 100644 --- a/app/chain/transfer/history.py +++ b/app/chain/transfer/history.py @@ -1,15 +1,24 @@ """手动和远程整理历史入口及结果消息。""" import re +from copy import deepcopy from pathlib import Path from typing import Any, List, Optional, Tuple, Union, cast from app.application.audio import use_music_cue +from app.application.messaging.message import TemplateContextBuilder +from app.application.transfer.models import TransferTask +from app.application.transfer.notifications import ( + TransferSuccessNotification, + build_transfer_success_group_key, +) from app.chain.media import MediaChain from app.chain.transfer.contract import _TransferOwnerBase +from app.domain import episode as episode_rules from app.domain.context import MediaInfo, MusicAlbumInfo, MusicInfo from app.domain.meta.metabase import MetaBase from app.runtime.log import logger +from app.runtime.loop import main_loop_registry from app.schemas.message import Message from app.schemas.tmdb import TmdbEpisode from app.schemas.transfer import EpisodeFormat, TransferInfo @@ -315,6 +324,8 @@ class TransferHistoryOwner(_TransferOwnerBase): season_episode: Optional[str] = None, episodes_info: Optional[List[TmdbEpisode]] = None, username: Optional[str] = None, + buttons: Optional[list[list[dict[str, Any]]]] = None, + batch: bool = False, ): """ 发送入库成功的消息 @@ -324,15 +335,33 @@ class TransferHistoryOwner(_TransferOwnerBase): :param season_episode: 已入库季集文本 :param episodes_info: 当前季的全部集信息 :param username: 用户名 + :param buttons: 批次通知使用的历史入口 + :param batch: 多文件批次使用简洁汇总,单文件沿用用户通知模板 """ - self.post_message( - Message( + message = Message( mtype=MessageType.Organize, ctype=ContentType.OrganizeSuccess, image=mediainfo.get_message_image(), username=username, link=self.runtime_config.history_url, - ), + buttons=buttons, + ) + if batch: + context = TemplateContextBuilder().build( + meta=meta, mediainfo=cast(MediaInfo, mediainfo), transferinfo=transferinfo, + aggregate_music_album=True, season_episode=season_episode, + ) + message.title = context.get("title_year") or mediainfo.title + if season_episode: + message.title = f"{message.title} {season_episode}" + message.text = f"📂 已入库 {transferinfo.file_count} 个文件" + total_tracks = getattr(mediainfo, "total_tracks", None) + if mediainfo.type == MediaType.MUSIC and total_tracks: + message.text += f" / 共 {total_tracks} 首曲目" + if transferinfo.target_diritem: + message.text += f"\n目录:{transferinfo.target_diritem.path}" + self.post_message( + message, meta=meta, mediainfo=mediainfo, transferinfo=transferinfo, @@ -341,6 +370,68 @@ class TransferHistoryOwner(_TransferOwnerBase): username=username, ) + def notify_successful_transfer(self, task: TransferTask, transferinfo: TransferInfo) -> None: + """全局开启时聚合成功结果,目录关闭通知和前台手动整理仍保持静默。""" + if not transferinfo.target_item or not transferinfo.need_notify or (task.manual and not task.background): + return + assert task.meta is not None and task.mediainfo is not None + if self.runtime_config.transfer_success_notification_aggregation: + self.queue_successful_transfer_notification(task, transferinfo) + + def queue_successful_transfer_notification(self, task: TransferTask, transferinfo: TransferInfo) -> None: + """仅缓冲成功展示快照,历史、完成事件和种子状态仍逐任务结算。""" + assert task.meta is not None and task.mediainfo is not None + notification = TransferSuccessNotification( + meta=deepcopy(task.meta), + mediainfo=deepcopy(task.mediainfo), + transferinfo=transferinfo.model_copy(deep=True), + episodes_info=deepcopy(task.episodes_info), + username=task.username, + ) + try: + self.success_notification_aggregator.schedule( + group_key=build_transfer_success_group_key(task, transferinfo), + notification=notification, + callback=self._send_transfer_success_notifications, + loop=None if task.transfer_batch_id else main_loop_registry.require(), + defer_until=task.transfer_batch_id, + ) + except Exception as err: + logger.error(f"加入整理成功通知聚合缓冲失败,将立即发送:{err}") + self._send_transfer_success_notifications([notification]) + + def _send_transfer_success_notifications(self, notifications: list[TransferSuccessNotification]) -> None: + """合并真实目标文件及大小,并以专辑、电影或季为模板主体发送批次通知。""" + if not notifications: + return + first = notifications[0] + files: dict[str, int] = {} + for notice in notifications: + result = notice.transferinfo + paths = result.file_list_new or ([result.target_item.path] if result.target_item else []) + size, remainder = divmod(result.total_size or 0, len(paths) or 1) + for index, path in enumerate(paths): + files[path] = size + (1 if index < remainder else 0) + merged = first.transferinfo.model_copy(update={ + "file_list_new": list(files), "file_count": len(files), "total_size": sum(files.values()), + }) + media = first.mediainfo + if isinstance(media, MusicInfo) and media.album: + media = deepcopy(media) + media.music_type = MUSIC_ENTITY_ALBUM + episodes = sorted({ + episode for notice in notifications for episode in notice.meta.episode_list + }) + season_episode = first.meta.season if media.type == MediaType.TV else None + if season_episode and episodes: + season_episode = f"{season_episode} {episode_rules.format_ranges(episodes)}" + self.send_transfer_message( + meta=first.meta, mediainfo=media, transferinfo=merged, + season_episode=season_episode, episodes_info=first.episodes_info, username=first.username, + buttons=[[{"text": "查看整理记录", "url": self.runtime_config.history_url}]] if len(files) > 1 else None, + batch=len(files) > 1, + ) + @staticmethod def _is_blocked_by_exclude_words( file_path: str, diff --git a/app/chain/transfer/queue.py b/app/chain/transfer/queue.py index 8d1c7e2c2..8dae3f075 100644 --- a/app/chain/transfer/queue.py +++ b/app/chain/transfer/queue.py @@ -23,6 +23,10 @@ from app.application.transfer.execution import ( TransferExecutionSnapshot, TransferExecutionState, ) +from app.application.transfer.notifications import ( + TransferNotificationAggregator, + TransferSuccessNotification, +) from app.application.transfer.workflow import ( JobManager, TransferAdmission, @@ -83,6 +87,7 @@ class TransferQueueOwner(_TransferOwnerBase): # Agent重试管理器 # 整理失败通知聚合器 self.failure_notification_aggregator = TransferFailureNotificationAggregator() + self.success_notification_aggregator = TransferNotificationAggregator[TransferSuccessNotification]() # durable admission 仓储先于内存入队保存任务,进程退出后仍可恢复。 self._transfer_admissions = self.transfer_admission_repository self._transfer_executions = self.transfer_execution_repository @@ -324,6 +329,7 @@ class TransferQueueOwner(_TransferOwnerBase): if not workers_closed: return False self.failure_notification_aggregator.close() + self.success_notification_aggregator.close() return True def on_config_changed(self) -> None: diff --git a/app/chain/transfer/scrape.py b/app/chain/transfer/scrape.py index a2ac207c0..679cdc951 100644 --- a/app/chain/transfer/scrape.py +++ b/app/chain/transfer/scrape.py @@ -192,6 +192,9 @@ class ScrapeBatchMixin(_TransferOwnerBase): targets = list(batch.get("targets", {}).values()) self._scrape_batches.pop(batch_id, None) + aggregator = getattr(self, "success_notification_aggregator", None) + if aggregator is not None: + aggregator.release_batch(batch_id) for target in targets: fileitem = target.get("fileitem") if not fileitem: diff --git a/app/chain/transfer/settlement.py b/app/chain/transfer/settlement.py index 1c06ffab5..7967f01ae 100644 --- a/app/chain/transfer/settlement.py +++ b/app/chain/transfer/settlement.py @@ -366,7 +366,10 @@ class TransferSettlementOwner(_TransferOwnerBase): or task.fileitem.size ) # 发送通知,实时手动整理时不发 - if transferinfo.need_notify and (task.background or not task.manual): + if ( + transferinfo.need_notify and (task.background or not task.manual) + and not self.runtime_config.transfer_success_notification_aggregation + ): se_str = None if task.mediainfo.type == MediaType.TV: season_episodes = self.jobview.season_episodes( @@ -559,6 +562,7 @@ class TransferSettlementOwner(_TransferOwnerBase): # 登记批次级刮削目标 self._record_scrape_target(task, transferinfo) + self.notify_successful_transfer(task, transferinfo) # 全部整理完成且有成功的任务时,发送消息和事件 if self.jobview.is_finished(task): diff --git a/app/runtime/config.py b/app/runtime/config.py index c4d259fc7..ad34f68cd 100644 --- a/app/runtime/config.py +++ b/app/runtime/config.py @@ -878,6 +878,8 @@ class ConfigModel(BaseModel): AI_AGENT_RETRY_TRANSFER: bool = False # 是否按媒体聚合整理失败通知,关闭时保持逐条发送 TRANSFER_FAILURE_NOTIFICATION_AGGREGATION: bool = True + # 是否按批次聚合电影、电视剧和音乐的整理成功通知 + TRANSFER_SUCCESS_NOTIFICATION_AGGREGATION: bool = True # 音频输入提供商:openai/openai_chat_audio/mimo/minimax AUDIO_INPUT_PROVIDER: str = "openai" diff --git a/app/startup/composition/configuration.py b/app/startup/composition/configuration.py index 0b74fafc1..2a56a607f 100644 --- a/app/startup/composition/configuration.py +++ b/app/startup/composition/configuration.py @@ -265,6 +265,9 @@ def build_chain_runtime_config(settings: Settings) -> ChainRuntimeConfig: transfer_failure_notification_aggregation=( settings.TRANSFER_FAILURE_NOTIFICATION_AGGREGATION ), + transfer_success_notification_aggregation=( + settings.TRANSFER_SUCCESS_NOTIFICATION_AGGREGATION + ), transfer_task_timeout=settings.TRANSFER_TASK_TIMEOUT, scrape_follow_tmdb=settings.SCRAP_FOLLOW_TMDB, metadata_cache_ttl=settings.CONF.meta, diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index 7412b545f..068586852 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -763,7 +763,7 @@ flowchart LR | 指标 | 当前值 | |---|---:| | Python 模块 | 1119 | -| 内部导入边 | 9,524 | +| 内部导入边 | 9,538 | | 非平凡 SCC | 1(精确 containment 的 TMDB 移植包环) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 49(债务已清零,49 条精确 containment) | @@ -773,7 +773,7 @@ flowchart LR | Model/Oper 自动事务与自建 Session | 0 | | 组合根外 `SystemConfigOper()` | 0 | -整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;音乐标签准入与批次共识由 `app.chain.transfer.music` 负责,预览证据由 `app.application.transfer.projection` 只读投影;宿主依赖边现为 9,524;订阅独立日志复用运行时上下文、系统日志端口与资源鉴权,新增 19 条合法依赖边(含父包展开),未新增模块或 SCC;插件实例校验复用 `app.domain.plugin` 的物理身份规则,兼容下划线 ID,新增 2 条 Schema 到 Domain 的合法依赖边(含父包展开);种子下载限流窗口由 `app.domain.torrent` 定义,失败冷却 owner 复用同一语义,新增 1 条合法 Chain 到 Domain 的导入边;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条模块导入边;资源过滤动作 `app.workflow.actions.filter_torrents` 与动作包共用的领域还原函数同样把 Schema 资源还原为领域对象后再交给过滤链,新增 6 条模块导入边。音乐来源链与识别缓存复用领域身份核验,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。缓存组合根只在启动时选用 Redis 缓存才导入 Redis 适配器,依赖 langchain_core 的对话记忆模型归属 `app.agent.memory`,文件缓存且未启用智能体的实例不再加载 redis 与 langchain_core。Telegram 渠道改用模块内 `app.modules.telegram.botapi` 精简 Bot API 客户端,经 `RequestUtils` 出站,宿主不再导入 pyTelegramBotAPI,启用 Telegram 的实例也不会因该 SDK 加载 redis;该依赖暂时保留给插件使用。Web Push 协议(aes128gcm 加密、VAPID 签名与经 `RequestUtils` 投递)由网络适配器 `app.adapters.network.webpush` 直接基于 http-ece 与 py-vapid 实现,消息端点与 `WebPushModule` 共用,宿主不再导入 pywebpush 及其连带的 aiohttp;该依赖同样暂时保留给插件使用。飞书渠道改用模块内 `app.modules.feishu.openapi` OpenAPI 客户端(经 `RequestUtils` 出站)与网络适配器 `app.adapters.network.feishu` 事件长连接(websocket-client 同步收发 pbbp2 帧),宿主不再导入 lark-oapi 及其上万个生成模块,长连接也不再依赖 SDK 的模块级事件循环;插件经 `app.sdk.feishu` 复用同一长连接,lark-oapi 暂时保留给尚未迁移的插件使用。API 文档路由由 `app.adapters.web.docs` 按 `API_DOCS_ENABLE` 逐请求开放,默认关闭,未开放时不生成文档。当前 `app.startup.lifecycle` 为 587、`app.factory` 为 600、`app.main` 为 602。专辑订阅入库对账新增 `app.chain.subscribe.music` 一个职责 owner;按注入的下载/整理历史 Port 读取事实,复用音频标签/CUE 读取和领域覆盖规则,依赖图增加 18 条合法边,不引入跨层数据库或 Adapter 直连。订阅业务活动新增 `app.application.subscription.activity` 及对应 DB Model、Oper、Adapter 四个模块,三入口与功能前提交对照均只增加这四个模块;性能基线仅同步结构计数,保留原有历史耗时采样和预算。音乐调用观察 `app.application.music.observation` 新增一个轻量模块,记录来源结果及请求预算;AcoustID及路径识别复用此上下文传递有界指纹候选,保留旧单ID模块合同。站点图片域名快照新增 `app.application.security.image`,各启动入口增加一个模块;性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。 +成功通知聚合复用既有 owner 和领域/模板模型,新增 14 条合法内部依赖边(含父包展开),未新增模块或 SCC。整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;音乐标签准入与批次共识由 `app.chain.transfer.music` 负责,预览证据由 `app.application.transfer.projection` 只读投影;宿主依赖边现为 9,538;订阅独立日志复用运行时上下文、系统日志端口与资源鉴权,新增 19 条合法依赖边(含父包展开),未新增模块或 SCC;插件实例校验复用 `app.domain.plugin` 的物理身份规则,兼容下划线 ID,新增 2 条 Schema 到 Domain 的合法依赖边(含父包展开);种子下载限流窗口由 `app.domain.torrent` 定义,失败冷却 owner 复用同一语义,新增 1 条合法 Chain 到 Domain 的导入边;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条模块导入边;资源过滤动作 `app.workflow.actions.filter_torrents` 与动作包共用的领域还原函数同样把 Schema 资源还原为领域对象后再交给过滤链,新增 6 条模块导入边。音乐来源链与识别缓存复用领域身份核验,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。缓存组合根只在启动时选用 Redis 缓存才导入 Redis 适配器,依赖 langchain_core 的对话记忆模型归属 `app.agent.memory`,文件缓存且未启用智能体的实例不再加载 redis 与 langchain_core。Telegram 渠道改用模块内 `app.modules.telegram.botapi` 精简 Bot API 客户端,经 `RequestUtils` 出站,宿主不再导入 pyTelegramBotAPI,启用 Telegram 的实例也不会因该 SDK 加载 redis;该依赖暂时保留给插件使用。Web Push 协议(aes128gcm 加密、VAPID 签名与经 `RequestUtils` 投递)由网络适配器 `app.adapters.network.webpush` 直接基于 http-ece 与 py-vapid 实现,消息端点与 `WebPushModule` 共用,宿主不再导入 pywebpush 及其连带的 aiohttp;该依赖同样暂时保留给插件使用。飞书渠道改用模块内 `app.modules.feishu.openapi` OpenAPI 客户端(经 `RequestUtils` 出站)与网络适配器 `app.adapters.network.feishu` 事件长连接(websocket-client 同步收发 pbbp2 帧),宿主不再导入 lark-oapi 及其上万个生成模块,长连接也不再依赖 SDK 的模块级事件循环;插件经 `app.sdk.feishu` 复用同一长连接,lark-oapi 暂时保留给尚未迁移的插件使用。API 文档路由由 `app.adapters.web.docs` 按 `API_DOCS_ENABLE` 逐请求开放,默认关闭,未开放时不生成文档。当前 `app.startup.lifecycle` 为 587、`app.factory` 为 600、`app.main` 为 602。专辑订阅入库对账新增 `app.chain.subscribe.music` 一个职责 owner;按注入的下载/整理历史 Port 读取事实,复用音频标签/CUE 读取和领域覆盖规则,依赖图增加 18 条合法边,不引入跨层数据库或 Adapter 直连。订阅业务活动新增 `app.application.subscription.activity` 及对应 DB Model、Oper、Adapter 四个模块,三入口与功能前提交对照均只增加这四个模块;性能基线仅同步结构计数,保留原有历史耗时采样和预算。音乐调用观察 `app.application.music.observation` 新增一个轻量模块,记录来源结果及请求预算;AcoustID及路径识别复用此上下文传递有界指纹候选,保留旧单ID模块合同。站点图片域名快照新增 `app.application.security.image`,各启动入口增加一个模块;性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。 架构专项验证分为两个 CI 投影:`Check event semantic policy` 先运行依赖、Adapter、出口和 Event 语义门禁,`Check host architecture snapshot` 再执行快照测试及一次 diff --git a/docs/mcp-api.md b/docs/mcp-api.md index bbce157c6..905479980 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -438,6 +438,8 @@ FastAPI 的 HTTP 异常和参数校验异常统一使用 `message`,不再返 影视自动识别在未指定来源时只使用 TMDB,未命中时不会继续查询其它影视源。音乐路径识别严格按 AcoustID 音频指纹、文件标签、文件名三级依次执行;指纹或标签直接提供 MusicBrainz Recording ID 时,会直接查询 MusicBrainz 详情,未绑定身份的音乐标题及目录识别按 `SEARCH_SOURCE` 中内置音乐来源的配置顺序回退(MusicBrainz、TheAudioDB、豆瓣音乐),未选择音乐来源时兼容默认 MusicBrainz。显式 `media_source` / 主身份或 MusicBrainz 发行标签固定所属来源;来源之间不转换或拼接 ID。`MediaInfo` 响应仍可能包含 `tmdb_id`、`douban_id`、`bangumi_id`、`anilist_id` 等跨源映射辅助字段,但这些字段不是通用请求入口。明确归属 `/tmdb`、`/douban`、`/bangumi`、`/anilist` 的接口,以及固定使用 TMDB 的剧集组和排期接口,仍可按其单数据源契约接收原生 ID。 +整理目录的 `notify` 保持布尔类型;成功通知聚合统一由全局开关控制。开启 `TRANSFER_SUCCESS_NOTIFICATION_AGGREGATION`,明确批次完成后一次发送,外部无批次任务使用三十秒静默窗口。详见 [整理成功通知粒度](transfer-notifications.md)。 + | 方法 | 路径 | 说明 | | :--- | :--- | :--- | | GET | `/api/v1/media/search` | 按标题搜索媒体、合集、影视人物或音乐;人物结果可同时包含 MusicBrainz 艺术家,参数:`title`、`type`、`page`、`count`,可重复传入可选 `media_source`;未指定 `music_type` 时音乐搜索只返回单曲和专辑,显式 `music_type` 仍可用于专用实体选择;内置模块只处理自身支持的来源,插件模块可以处理其注册的扩展来源,旧客户端的逗号格式仅在输入边界兼容 | diff --git a/docs/refactor/optimization-checklist.md b/docs/refactor/optimization-checklist.md index 1ff638263..1ab8b011d 100644 --- a/docs/refactor/optimization-checklist.md +++ b/docs/refactor/optimization-checklist.md @@ -100,7 +100,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁 | 指标 | 当前值 | 解释 | |---|---:|---| -| 宿主 Python 模块 / 内部依赖边 | 1119 / 9,524 | `dependency-baseline.json` 当前快照;专辑订阅入库对账新增 1 个 Chain owner 和 18 条合法依赖边(含父包展开),仍经注入 Port 读取历史并通过既有 mutation 写入;订阅业务活动新增 4 个模块和 50 条合法内部依赖边(含父包展开),Application 仅定义事实与持久化 Port,DB Adapter/Oper 实现存取,组合根注入,未增加 Application/Chain 到具体 Adapter 或数据库的直连;插件实例校验复用 `app.domain.plugin` 的物理身份规则,兼容下划线 ID,新增 2 条合法依赖边(含父包展开);种子失败冷却复用 `app.domain.torrent` 的限流语义,新增 1 条合法导入边;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条合法模块导入边,资源过滤动作复用同一还原再新增 6 条;LLM 独占连接关闭复用宿主线程池;歌词字形转换复用 `app.foundation.text`;订阅创建使用 `app.domain.context.MediaInfo` 和运行时配置端口,将非 TMDB 影视身份投影为 TMDB 身份 | +| 宿主 Python 模块 / 内部依赖边 | 1119 / 9,538 | `dependency-baseline.json` 当前快照;成功通知聚合复用既有 owner 和领域/模板模型,新增 14 条合法内部依赖边(含父包展开),未新增模块或 SCC。专辑订阅入库对账新增 1 个 Chain owner 和 18 条合法依赖边(含父包展开),仍经注入 Port 读取历史并通过既有 mutation 写入;订阅业务活动新增 4 个模块和 50 条合法内部依赖边(含父包展开),Application 仅定义事实与持久化 Port,DB Adapter/Oper 实现存取,组合根注入,未增加 Application/Chain 到具体 Adapter 或数据库的直连;插件实例校验复用 `app.domain.plugin` 的物理身份规则,兼容下划线 ID,新增 2 条合法依赖边(含父包展开);种子失败冷却复用 `app.domain.torrent` 的限流语义,新增 1 条合法导入边;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条合法模块导入边,资源过滤动作复用同一还原再新增 6 条;LLM 独占连接关闭复用宿主线程池;歌词字形转换复用 `app.foundation.text`;订阅创建使用 `app.domain.context.MediaInfo` 和运行时配置端口,将非 TMDB 影视身份投影为 TMDB 身份 | | 非平凡 SCC | 1 | 仅保留精确 containment 的 29 模块 TMDB 移植包环 | | 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 | | Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 | diff --git a/docs/rules/05-architecture.md b/docs/rules/05-architecture.md index ee2ce3043..c4e22d74a 100644 --- a/docs/rules/05-architecture.md +++ b/docs/rules/05-architecture.md @@ -73,7 +73,7 @@ to make the directory tree look symmetrical. | `app/application/invocation.py` | Frozen Agent write-call identity, claim and receipt contracts; the injected repository provides atomic claim, fenced settlement and unresolved-state reads, while `db/adapters/invocation.py` owns short transactions and cold-start recovery is invoked by startup | | `app/application/network.py` | System network-test target catalog, immutable public/private projections, URL and redirect admission, response validation and the injected transport Port; startup owns concrete HTTP Adapter assembly | | `app/application/outbox.py` | Durable intent, transaction-only stager, short-transaction dispatch store, claim fencing and structured post-commit result contracts | -| `app/application/transfer/` | Durable transfer use cases: `workflow.py` owns queue service orchestration; `models.py` owns admission/planning/task contracts; `jobs.py` owns in-process task views; `notifications.py` owns failure aggregation; `projection.py` owns domain projections; `execution.py` owns stable operation identity, step/checkpoint state, retry/manual-review commands and terminal-settlement DTOs; `recovery.py` owns failed/corrupt task cleanup and history detachment through the execution repository; `history.py` projects history write fields and file fingerprints; `feedback.py` owns failure stages, notification snapshots and message text, while Chain owns notification delivery and cleanup side effects | +| `app/application/transfer/` | Durable transfer use cases: `workflow.py` owns queue service orchestration; `models.py` owns admission/planning/task contracts; `jobs.py` owns in-process task views; `notifications.py` owns success/failure notification snapshots, batch waiting and quiet-window aggregation; `projection.py` owns domain projections; `execution.py` owns stable operation identity, step/checkpoint state, retry/manual-review commands and terminal-settlement DTOs; `recovery.py` owns failed/corrupt task cleanup and history detachment through the execution repository; `history.py` projects history write fields and file fingerprints; `feedback.py` owns failure stages, notification snapshots and message text, while Chain owns notification delivery and cleanup side effects | | `app/chain/transfer/music.py` | 音乐整理的纯标签准入、目录共识、发行分组与曲目上下文编排;`filter.py` 保留通用文件筛选和既有 mixin 调用契约。可信标签在本地完成分类与命名,分类的外部事实补充可由本次用例明确禁用,仍遵守用户策略与人工覆盖 | | `app/application/plugin/` | Plugin market catalog, installation command, installed-plugin identity contract and startup migration, runtime port, folder operations and dynamic-route use cases; filenames remain single words (`catalog.py`, `identity.py`, `migration.py`, `install.py`, `runtime.py`, `folders.py`, `routes.py`) | | `app/application/server/` | MoviePilot Server reporting and sharing use cases; local data readers and transport callbacks are injected by startup | diff --git a/docs/transfer-notifications.md b/docs/transfer-notifications.md new file mode 100644 index 000000000..ed4081fab --- /dev/null +++ b/docs/transfer-notifications.md @@ -0,0 +1,17 @@ +# 整理成功通知粒度 + +系统设置 → 高级设置 → 实验室中的“按批次聚合整理成功通知”默认开启, +对应 `TRANSFER_SUCCESS_NOTIFICATION_AGGREGATION=true`。一张分轨专辑的任务全部结束后, +按下载器/种子、目标媒体目录、季和用户合并成一条成功通知。没有下载 hash 时按源目录分组。 +音乐标题显示专辑,正文显示实际入库文件数、已知的专辑总曲目数及目标目录, +多文件通知提供“查看整理记录”入口;单文件明确批次立即发送并沿用用户通知模板。 + +电影、电视剧和音乐使用同一个全局开关。关闭时保持原有按媒体作业发送的行为。 +目录设置继续使用原来的“发送通知”开关(`notify: true/false`),不增加通知粒度设置。 +批次聚合只影响展示消息,逐文件整理历史、完成/失败事件、刮削和种子状态回写保持原流程。 +失败通知仍由独立的失败聚合开关控制。 + +没有明确批次的外部任务采用三十秒静默窗口;连续到达会重置窗口。 +明确批次等待登记关闭且所有任务终结,较慢的曲目不会打断汇总,失败任务不会计入成功文件数。 +前台手动整理仍不发送成功通知。关闭进程时在整理 worker 收敛后刷新剩余缓冲。 +通知缓冲是内存展示状态,异常退出不保证重发此前已完成任务的成功通知;逐文件历史仍可查询。 diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 909121247..3ce6a734f 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -941,8 +941,8 @@ "runtime_only": true } }, - "edge_count": 9524, - "edge_sha256": "e530dbe3368c07f5e287667142b41efb92c5318d6e33a9438cd00479b7f38f57", + "edge_count": 9538, + "edge_sha256": "b7b224c7a66e3a2d169cffdad65ef7b54dc425af11b1ccb12b6bc1ceebf9108b", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -4359,10 +4359,16 @@ "app.application.transfer.notifications -> app.application", "app.application.transfer.notifications -> app.application.transfer", "app.application.transfer.notifications -> app.application.transfer.feedback", + "app.application.transfer.notifications -> app.domain", + "app.application.transfer.notifications -> app.domain.context", + "app.application.transfer.notifications -> app.domain.meta", + "app.application.transfer.notifications -> app.domain.meta.metabase", "app.application.transfer.notifications -> app.runtime", "app.application.transfer.notifications -> app.runtime.log", "app.application.transfer.notifications -> app.schemas", "app.application.transfer.notifications -> app.schemas.media", + "app.application.transfer.notifications -> app.schemas.tmdb", + "app.application.transfer.notifications -> app.schemas.transfer", "app.application.transfer.projection -> app.domain", "app.application.transfer.projection -> app.domain.context", "app.application.transfer.projection -> app.domain.meta", @@ -5817,17 +5823,24 @@ "app.chain.transfer.format -> app.schemas.types", "app.chain.transfer.history -> app.application", "app.chain.transfer.history -> app.application.audio", + "app.chain.transfer.history -> app.application.messaging", + "app.chain.transfer.history -> app.application.messaging.message", + "app.chain.transfer.history -> app.application.transfer", + "app.chain.transfer.history -> app.application.transfer.models", + "app.chain.transfer.history -> app.application.transfer.notifications", "app.chain.transfer.history -> app.chain", "app.chain.transfer.history -> app.chain.media", "app.chain.transfer.history -> app.chain.transfer", "app.chain.transfer.history -> app.chain.transfer.contract", "app.chain.transfer.history -> app.domain", "app.chain.transfer.history -> app.domain.context", + "app.chain.transfer.history -> app.domain.episode", "app.chain.transfer.history -> app.domain.meta", "app.chain.transfer.history -> app.domain.meta.metabase", "app.chain.transfer.history -> app.runtime", "app.chain.transfer.history -> app.runtime.errors", "app.chain.transfer.history -> app.runtime.log", + "app.chain.transfer.history -> app.runtime.loop", "app.chain.transfer.history -> app.schemas", "app.chain.transfer.history -> app.schemas.message", "app.chain.transfer.history -> app.schemas.tmdb", @@ -5891,6 +5904,7 @@ "app.chain.transfer.queue -> app.application.history", "app.chain.transfer.queue -> app.application.transfer", "app.chain.transfer.queue -> app.application.transfer.execution", + "app.chain.transfer.queue -> app.application.transfer.notifications", "app.chain.transfer.queue -> app.application.transfer.workflow", "app.chain.transfer.queue -> app.chain", "app.chain.transfer.queue -> app.chain.media", diff --git a/tests/test_music_transfer.py b/tests/test_music_transfer.py index 73c2712b6..9e6c2ddb4 100644 --- a/tests/test_music_transfer.py +++ b/tests/test_music_transfer.py @@ -1,4 +1,5 @@ from copy import deepcopy +from dataclasses import replace from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -650,8 +651,9 @@ def test_job_manager_separates_music_entity_namespaces_for_same_provider_id(): def test_success_file_aggregation_is_isolated_between_music_jobs_in_same_directory(monkeypatch): - """同目录内交错完成的整专与单曲作业不能互相取走通知文件清单。""" + """全局关闭聚合时,同目录交错完成的整专与单曲作业仍保留旧文件清单。""" chain = object.__new__(TransferChain) + chain.runtime_config = replace(chain.runtime_config, transfer_success_notification_aggregation=False) chain.jobview = JobManager() chain._success_target_files = {} chain._scrape_batches = {} diff --git a/tests/test_transfer_success_notification_aggregation.py b/tests/test_transfer_success_notification_aggregation.py new file mode 100644 index 000000000..cd1c4b38a --- /dev/null +++ b/tests/test_transfer_success_notification_aggregation.py @@ -0,0 +1,298 @@ +"""成功通知按明确批次或静默窗口聚合,且不改变逐文件结算副作用。""" + +from dataclasses import replace +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from app.application.configuration import ChainRuntimeConfig +from app.application.transfer.execution import TransferExecutionCheckpoint, TransferSettlementResult +from app.application.transfer.jobs import JobManager +from app.application.transfer.models import TransferTask +from app.application.transfer.notifications import ( + TransferNotificationAggregator, + TransferSuccessNotification, + build_transfer_success_group_key, +) +from app.chain.transfer.facade import TransferChain +from app.domain.context import MediaInfo, MusicInfo +from app.domain.meta.metamusic import MetaMusic +from app.domain.metainfo import MetaInfo +from app.runtime.config import ConfigModel +from app.runtime.loop import main_loop_registry +from app.schemas.file import FileItem +from app.schemas.transfer import TransferInfo +from app.schemas.types import ContentType, EventType, MediaType, MessageType + + +class _Loop: + """记录静默窗口而不创建真实后台任务。""" + + def __init__(self): + """初始化可手动触发的定时回调。""" + self.timers = [] + + def call_soon_threadsafe(self, callback, *args): + """同步登记事件循环回调。""" + callback(*args) + + def call_later(self, _delay, callback, *args): + """保存定时器并提供可取消的句柄。""" + timer = SimpleNamespace(callback=callback, args=args, cancel=Mock()) + self.timers.append(timer) + return timer + + def flush(self): + """按登记顺序触发定时器,包含已取消回调以验证代际保护。""" + for timer in self.timers: + timer.callback(*timer.args) + + +def _task(number=1, *, batch="batch", username="tester", download_hash="hash"): + """构造同一专辑内具有不同录音身份的分轨整理任务。""" + return TransferTask( + fileitem=FileItem(storage="local", path=f"/downloads/Album/{number}.flac", name=f"{number}.flac", extension="flac", type="file", size=100), + meta=MetaMusic(title=f"Track {number}", album="Album", track_number=number), + mediainfo=MusicInfo(title=f"Track {number}", album="Album", artists=["Artist"], year=2013, + media_source="musicbrainz", media_id=f"recording-{number}", total_tracks=74), + target_path=Path("/library/Album"), transfer_batch_id=batch, + download_hash=download_hash, username=username, background=True, + ) + + +def _result(number=1): + """提供包含真实目标路径的成功结果。""" + path = f"/library/Album/{number}.flac" + return TransferInfo( + target_item=FileItem(storage="local", path=path, type="file"), + target_diritem=FileItem(storage="local", path="/library/Album", type="dir"), + file_list_new=[path], file_count=1, total_size=100, need_notify=True, + ) + + +@pytest.fixture +def chain(): + """构造没有线程、数据库和真实消息通道的通知宿主。""" + owner = object.__new__(TransferChain) + owner.runtime_config = ChainRuntimeConfig(media_extensions=(".flac", ".mkv"), history_url="https://example.test/history") + owner.success_notification_aggregator = TransferNotificationAggregator[TransferSuccessNotification]() + owner.post_message = Mock() + owner._scrape_batches = {} + owner._audio_exts = [".flac"] + owner._media_exts = [".mkv"] + owner._subtitle_exts = [".srt"] + owner.eventmanager = Mock() + yield owner + owner.success_notification_aggregator.close() + + +def test_success_notification_aggregation_defaults_on(): + """成功侧默认值与失败侧一致。""" + assert ConfigModel.model_fields["TRANSFER_SUCCESS_NOTIFICATION_AGGREGATION"].default is True + + +@pytest.mark.parametrize("change", ["username", "download_hash", "downloader", "destination", "storage"]) +def test_success_group_isolates_source_destination_and_user(change): + """不同用户、种子、下载器、目标或存储不能混入同一通知。""" + first, second = _task(), _task(2) + result = _result() + modified = _result(2) + if change == "destination": + modified.target_diritem.path = "/library/Other Album" + elif change == "storage": + modified.target_diritem.storage = "smb" + else: + setattr(second, change, "other") + assert build_transfer_success_group_key(first, result) != build_transfer_success_group_key(second, modified) + + +def test_all_74_slow_tracks_wait_for_batch_and_send_once(chain): + """曲目间隔超过静默窗也不拆批,统计真实文件并以专辑名发送。""" + tasks = [_task(number) for number in range(1, 75)] + for task in tasks: + chain._register_scrape_batch_task(task) + chain._close_scrape_batch("batch") + for number, task in enumerate(tasks, start=1): + result = _result(number) + chain.queue_successful_transfer_notification(task, result) + # 模拟旧通知计数在同一结果对象上被改写。 + result.file_count = 999 + chain._finish_scrape_batch_task(task) + assert chain.post_message.call_count == (1 if number == 74 else 0) + message = chain.post_message.call_args.args[0] + assert message.title == "Album (2013)" + assert "已入库 74 个文件 / 共 74 首曲目" in message.text + assert message.buttons == [[{"text": "查看整理记录", "url": "https://example.test/history"}]] + assert message.ctype == ContentType.OrganizeSuccess + assert message.mtype == MessageType.Organize + assert chain.post_message.call_args.kwargs["transferinfo"].total_size == 7400 + assert not chain.eventmanager.send_event.called + + +def test_single_file_batch_is_immediate_and_keeps_template(chain): + """一个文件的明确批次结束即发,保留用户模板和无批量按钮行为。""" + task = _task() + chain._register_scrape_batch_task(task) + chain._close_scrape_batch("batch") + chain.queue_successful_transfer_notification(task, _result()) + chain._finish_scrape_batch_task(task) + message = chain.post_message.call_args.args[0] + assert message.title is None and message.text is None + assert message.buttons is None + assert chain.post_message.call_count == 1 + + +def test_closed_batch_is_required_even_if_work_finishes_while_enumerating(chain): + """目录枚举期间先完成的曲目要等登记结束,防止过早发送。""" + task = _task() + chain._register_scrape_batch_task(task) + chain.queue_successful_transfer_notification(task, _result()) + chain._finish_scrape_batch_task(task) + chain.post_message.assert_not_called() + chain._close_scrape_batch("batch") + chain.post_message.assert_called_once() + + +def test_unbatched_events_use_quiet_window_and_deduplicate_paths(chain, monkeypatch): + """没有明确批次的外部任务使用静默窗,相同目标不会重复累计。""" + loop = _Loop() + monkeypatch.setattr(main_loop_registry, "require", lambda: loop) + for number in [1, 2, 1]: + chain.queue_successful_transfer_notification(_task(number, batch=None), _result(number)) + chain.post_message.assert_not_called() + loop.flush() + chain.post_message.assert_called_once() + assert chain.post_message.call_args.kwargs["transferinfo"].file_count == 2 + assert chain.post_message.call_args.kwargs["transferinfo"].total_size == 200 + + +def test_overlapping_batches_wait_for_both_and_shutdown_flushes_once(chain): + """同组重叠批次不会互相提前刷新;关闭发送剩余快照且重复关闭幂等。""" + for number, batch in [(1, "a"), (2, "b")]: + chain.queue_successful_transfer_notification(_task(number, batch=batch), _result(number)) + chain.success_notification_aggregator.release_batch("a") + chain.post_message.assert_not_called() + chain.success_notification_aggregator.close() + chain.success_notification_aggregator.close() + chain.success_notification_aggregator.release_batch("b") + chain.post_message.assert_called_once() + assert "已入库 2 个文件" in chain.post_message.call_args.args[0].text + + +@pytest.mark.parametrize("notify,manual,background", [(False, False, True), (True, True, False)]) +def test_disabled_or_foreground_manual_notifications_remain_silent(chain, notify, manual, background): + """关闭通知及前台手动整理不进入缓冲。""" + task = _task() + task.manual, task.background = manual, background + result = _result() + result.need_notify = notify + chain.notify_successful_transfer(task, result) + chain.success_notification_aggregator.close() + chain.post_message.assert_not_called() + + +@pytest.mark.parametrize("media_type", [MediaType.MOVIE, MediaType.TV, MediaType.MUSIC]) +def test_global_disabled_keeps_legacy_notifications(chain, media_type): + """全局关闭时成功任务不进入新的缓冲,由原有作业通知负责发送。""" + chain.runtime_config = replace(chain.runtime_config, transfer_success_notification_aggregation=False) + task = _task() + if media_type != MediaType.MUSIC: + task.meta = MetaInfo("Movie 2026" if media_type == MediaType.MOVIE else "Show S01E01") + task.mediainfo = MediaInfo(title="Movie" if media_type == MediaType.MOVIE else "Show", year="2026", type=media_type) + chain.notify_successful_transfer(task, _result()) + chain.success_notification_aggregator.close() + chain.post_message.assert_not_called() + + +def test_movie_batch_uses_same_success_aggregation(chain): + """电影同样在批次结束后汇总成功文件,并保持入库消息类型。""" + for number in [1, 2]: + task = _task(number) + task.meta = MetaInfo("Movie 2026") + task.mediainfo = MediaInfo(title="Movie", year="2026", type=MediaType.MOVIE) + chain.notify_successful_transfer(task, _result(number)) + chain.post_message.assert_not_called() + chain.success_notification_aggregator.release_batch("batch") + message = chain.post_message.call_args.args[0] + assert message.title == "Movie (2026)" + assert "已入库 2 个文件" in message.text + assert message.ctype == ContentType.OrganizeSuccess + assert chain.post_message.call_count == 1 + + +def test_television_batch_retains_season_episode_range(chain): + """影视汇总保留季集范围,不把不同季混合。""" + for number in [1, 2]: + task = _task(number) + task.meta = MetaInfo(f"Show S01E{number:02d}") + task.mediainfo = MediaInfo(title="Show", year="2026", type=MediaType.TV) + chain.queue_successful_transfer_notification(task, _result(number)) + chain.success_notification_aggregator.release_batch("batch") + message = chain.post_message.call_args.args[0] + assert message.title == "Show (2026) S01 E01-E02" + + +def test_mixed_outcomes_preserve_each_history_event_and_only_count_success(chain, monkeypatch): + """批次成败混合时逐任务持久化和事件不变,成功汇总只计已入库文件。""" + chain.jobview = JobManager() + chain._success_target_files = {} + chain.transfer_history_repository = Mock() + chain.queue_failed_transfer_notification = Mock() + chain._TransferChain__mark_torrent_completed_if_done = Mock() + chain._record_scrape_target = Mock() + chain._send_metadata_scrape_event = Mock() + chain.durable_event_writer = Mock() + chain.durable_event_writer.transfer_result.return_value = TransferSettlementResult( + history_id=1, settlement_revision=1, pending_deleted=True, + ) + monkeypatch.setattr("app.chain.transfer.settlement.record_transfer_failure", Mock()) + monkeypatch.setattr("app.chain.transfer.settlement.clear_transfer_failures", Mock()) + tasks = [_task(number) for number in [1, 2, 3]] + for task in tasks: + chain.jobview.add_task(task) + chain._register_scrape_batch_task(task) + chain._close_scrape_batch("batch") + for number, task in enumerate(tasks, start=1): + result = _result(number) + if number == 3: + result.success = False + result.message = "测试失败" + task.bind_admission_task_id(f"task-{number}") + task.bind_execution_lease(owner_id="worker", lease_token=f"lease-{number}") + task.bind_execution_checkpoint(TransferExecutionCheckpoint.create( + payload={"outcome": "succeeded" if result.success else "failed", "transferinfo": result.model_dump(mode="json")}, + operation_ids=(f"operation-{number}",), + )) + chain._TransferChain__default_callback(task, result) + chain._finish_scrape_batch_task(task) + assert chain.durable_event_writer.transfer_result.call_count == 3 + assert chain.queue_failed_transfer_notification.call_count == 1 + assert chain._record_scrape_target.call_count == 2 + assert chain._TransferChain__mark_torrent_completed_if_done.call_count == 3 + assert "已入库 2 个文件" in chain.post_message.call_args.args[0].text + assert chain.post_message.call_count == 1 + calls = chain.durable_event_writer.transfer_result.call_args_list + assert [call.kwargs["topic"] for call in calls] == ["transfer.completed", "transfer.completed", "transfer.audio.failed"] + for call in calls: + call.kwargs["publish"]({"test": True}) + assert [call.args[0] for call in chain.eventmanager.send_event.call_args_list] == [ + EventType.TransferComplete, EventType.TransferComplete, EventType.AudioTransferFailed, + ] + + +def test_old_callback_cannot_flush_recreated_group(): + """已刷新的组重新创建后,旧代回调不得发送新组快照。""" + loop = _Loop() + aggregator = TransferNotificationAggregator[str]() + callback = Mock() + aggregator.schedule(group_key="group", notification="old", callback=callback, loop=loop) + old_timer = loop.timers[0] + old_timer.callback(*old_timer.args) + aggregator.schedule(group_key="group", notification="new", callback=callback, loop=loop) + old_timer.callback(*old_timer.args) + assert callback.call_args_list == [((['old'],), {})] + loop.timers[1].callback(*loop.timers[1].args) + assert callback.call_count == 2 + callback.assert_called_with(["new"]) diff --git a/tests/test_transfer_worker_lifecycle.py b/tests/test_transfer_worker_lifecycle.py index 9d4f921f6..0c354fb82 100644 --- a/tests/test_transfer_worker_lifecycle.py +++ b/tests/test_transfer_worker_lifecycle.py @@ -445,28 +445,32 @@ def test_close_workers_lock_wait_uses_the_same_timeout_budget() -> None: def test_close_keeps_failure_notification_when_workers_do_not_converge() -> None: - """活跃整理线程超时后,失败通知 owner 必须继续供线程使用。""" + """活跃整理线程超时后,成功和失败通知 owner 必须继续供线程使用。""" chain = _build_chain() chain.close_workers = MagicMock(return_value=False) chain.failure_notification_aggregator = MagicMock() + chain.success_notification_aggregator = MagicMock() completed = asyncio.run(chain.close(timeout_seconds=0.01)) assert completed is False chain.close_workers.assert_called_once_with(0.01) chain.failure_notification_aggregator.close.assert_not_called() + chain.success_notification_aggregator.close.assert_not_called() def test_close_releases_failure_notification_after_workers_converge() -> None: - """worker 和回放退出后,整理链应刷新并关闭失败通知 owner。""" + """worker 和回放退出后,整理链应刷新并关闭成功和失败通知 owner。""" chain = _build_chain() chain.close_workers = MagicMock(return_value=True) chain.failure_notification_aggregator = MagicMock() + chain.success_notification_aggregator = MagicMock() completed = asyncio.run(chain.close(timeout_seconds=0.01)) assert completed is True chain.failure_notification_aggregator.close.assert_called_once_with() + chain.success_notification_aggregator.close.assert_called_once_with() def test_stop_transfer_runtime_does_not_construct_chain(monkeypatch) -> None: