From b6b57a30db8e0f94e1bce24ce802f9381ddfdc3c Mon Sep 17 00:00:00 2001 From: jxxghp Date: Fri, 13 Nov 2026 16:17:22 +0800 Subject: [PATCH] feat(music): add manual alignment and destination controls (#7401) --- .../policy/resources/api_mcp_schema.json | 24 +++++++ app/api/endpoints/transfer.py | 19 ++++-- app/chain/media/album.py | 16 +++-- app/chain/transfer/filter.py | 18 ++++-- app/chain/transfer/history.py | 45 +++++++++++++- app/chain/transfer/music.py | 5 +- app/chain/transfer/workflow.py | 12 +++- app/domain/music.py | 20 +++--- app/modules/filemanager/module.py | 10 +++ app/modules/filemanager/transhandler.py | 30 +++++++-- app/schemas/transfer.py | 26 ++++++++ docs/mcp-api.md | 12 ++++ skills/moviepilot-api/api/transfer.md | 16 ++++- tests/test_filemanager_planning.py | 50 ++++++++++++++- tests/test_music_release_selection.py | 62 +++++++++++++++++-- tests/test_music_source_protection.py | 8 ++- tests/test_music_track_alignment.py | 41 +++++++++++- version.py | 2 +- 18 files changed, 373 insertions(+), 43 deletions(-) diff --git a/app/agent/policy/resources/api_mcp_schema.json b/app/agent/policy/resources/api_mcp_schema.json index ee1008c83..e603793eb 100644 --- a/app/agent/policy/resources/api_mcp_schema.json +++ b/app/agent/policy/resources/api_mcp_schema.json @@ -2694,6 +2694,30 @@ "description": "本次手动整理的 MusicBrainz 文字字形优先级;空值继承系统设置", "title": "Music Release Scripts" }, + "music_target_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "本次音乐最终目录。填写后只应用文件名模板,类型、分类及专辑目录层级由此路径确定", + "title": "Music Target Path" + }, + "music_track_match": { + "default": "strict", + "description": "本次手选专辑曲目对齐方式,支持严格校验、忽略时长或按源路径自然顺序套用。顺序模式要求曲目数一致", + "enum": [ + "strict", + "ignore_duration", + "sequential" + ], + "title": "Music Track Match", + "type": "string" + }, "music_type": { "anyOf": [ { diff --git a/app/api/endpoints/transfer.py b/app/api/endpoints/transfer.py index 8e600c42f..43f480d5a 100644 --- a/app/api/endpoints/transfer.py +++ b/app/api/endpoints/transfer.py @@ -974,6 +974,20 @@ def _route_manual_transfer( ) +def _manual_music_transfer_options(item: ManualTransferItem) -> dict[str, Any]: + """ + 仅传递显式启用的音乐选项,兼容未使用新能力的旧整理调用。 + """ + options: dict[str, Any] = {} + if item.musicbrainz_release_id is not None: + options["musicbrainz_release_id"] = item.musicbrainz_release_id + if item.music_track_match != "strict": + options["music_track_match"] = item.music_track_match + if item.music_target_path: + options["music_target_path"] = Path(item.music_target_path) + return options + + def _execute_manual_transfer( transer_item: ManualTransferItem, background: Optional[bool], @@ -1079,10 +1093,7 @@ def _execute_manual_transfer( selected_music_fileitems, transer_item.music_type, ) - release_kwargs: dict[str, Any] = ( - {"musicbrainz_release_id": transer_item.musicbrainz_release_id} - if transer_item.musicbrainz_release_id is not None else {} - ) + release_kwargs = _manual_music_transfer_options(transer_item) # 前端显式传入文件列表时,按选中的文件逐个处理,避免将目录整体展开。 if explicit_selected_files: diff --git a/app/chain/media/album.py b/app/chain/media/album.py index 25fd1be21..c1d4f4784 100644 --- a/app/chain/media/album.py +++ b/app/chain/media/album.py @@ -7,7 +7,7 @@ import json import os from copy import deepcopy from pathlib import Path -from typing import Any, Optional, Union, cast +from typing import Any, Literal, Optional, Union, cast from app.application.audio import AudioMetadataHelper, music_cue_enabled from app.application.configuration import get_chain_runtime_config_snapshot @@ -34,6 +34,7 @@ from app.domain.music import ( music_text_key, ) from app.foundation.text import convert as zhconv_convert +from app.foundation.text import natural_sort_key from app.runtime.execution import run_in_threadpool from app.schemas.types import MUSIC_ENTITY_ALBUM, MUSIC_ENTITY_RECORDING, MediaSource, MusicEntityType @@ -377,11 +378,17 @@ class MediaAlbumOwner(_MediaOwnerBase): cls, files: list[Path], album: MusicAlbumInfo, + *, + track_match: Literal["strict", "ignore_duration", "sequential"] = "strict", ) -> dict[str, MusicInfo]: """ - 读取本地标签,并把手动选择发行版的曲目对齐到文件。 + 读取本地标签,按本次手动策略将所选发行版曲目对齐到文件。 """ - return cls._album_track_map(files, AudioMetadataHelper.read_many(files), album, allow_title_override=True) + if track_match == "sequential": + # 路径自然排序固定目录扫描与多选请求的顺序,保证预览和实际提交一致。 + files = sorted(files, key=lambda path: natural_sort_key(path.as_posix())) + return cls._album_track_map(files, AudioMetadataHelper.read_many(files), album, + allow_title_override=True, track_match=track_match) @classmethod def _album_track_map( @@ -391,6 +398,7 @@ class MediaAlbumOwner(_MediaOwnerBase): album: MusicAlbumInfo, *, allow_title_override: bool = False, + track_match: Literal["strict", "ignore_duration", "sequential"] = "strict", ) -> dict[str, MusicInfo]: """ 逻辑曲目全部对位后才输出对应物理文件,整轨始终保持 Album 身份。 @@ -398,7 +406,7 @@ class MediaAlbumOwner(_MediaOwnerBase): if len(files) != len(metas) or not music_album_has_consistent_tracks(album): return {} logical, owners = expand_music_tracks(metas) - aligned = align_music_tracks(logical, album.tracks, allow_title_override=allow_title_override) + aligned = align_music_tracks(logical, album.tracks, allow_title_override=allow_title_override, track_match=track_match) result: dict[str, MusicInfo] = {} for index, path in enumerate(files): positions = [position for position, owner in enumerate(owners) if owner == index] diff --git a/app/chain/transfer/filter.py b/app/chain/transfer/filter.py index 2ea569832..30832ffdb 100644 --- a/app/chain/transfer/filter.py +++ b/app/chain/transfer/filter.py @@ -4,7 +4,7 @@ import threading from copy import deepcopy from pathlib import Path -from typing import Any, Dict, Optional, Protocol, Union, cast +from typing import Any, Dict, Literal, Optional, Protocol, Union, cast from app.application.configuration import ( get_chain_runtime_config_snapshot, @@ -490,9 +490,11 @@ class FileFilterMixin(_TransferOwnerBase): self, file_items: list[tuple[FileItem, bool]], album: Optional[MusicAlbumInfo], + *, + track_match: Literal["strict", "ignore_duration", "sequential"] = "strict", ) -> tuple[dict[str, MusicInfo], Optional[str]]: """ - 对齐手选发行版的全部曲目,并拒绝混有重复版本的目录。 + 按本次策略对齐手选发行版;严格与忽略时长模式均要求唯一对位。 """ if not album: return {}, None @@ -503,12 +505,18 @@ class FileFilterMixin(_TransferOwnerBase): ] if not audio_paths: return {}, None - aligned_tracks = MediaChain._align_selected_music_album(audio_paths, album) + aligned_tracks = MediaChain._align_selected_music_album( + audio_paths, album, **({"track_match": track_match} if track_match != "strict" else {}), + ) if len(aligned_tracks) != len(audio_paths): + reason = ( + "顺序套用要求所选音频(含 CUE 逻辑曲目)与发行版曲目数一致" + if track_match == "sequential" else + "存在重复版本、曲目信息冲突或无法唯一对位的曲目;请按单个发行版本选择文件并核对曲目" + ) return {}, ( f"所选专辑只能对齐 {len(aligned_tracks)} / {len(audio_paths)} " - "个音频文件,存在重复版本、曲目信息冲突或无法唯一对位的曲目;" - "请按单个发行版本选择文件并核对曲目" + f"个音频文件,{reason}" ) selected_tracks: dict[str, MusicInfo] = {} for resolved_path, track in aligned_tracks.items(): diff --git a/app/chain/transfer/history.py b/app/chain/transfer/history.py index 9a7eb548e..b69ee8a48 100644 --- a/app/chain/transfer/history.py +++ b/app/chain/transfer/history.py @@ -5,7 +5,7 @@ import re from copy import deepcopy from pathlib import Path -from typing import Any, List, Optional, Tuple, Union, cast +from typing import Any, List, Literal, Optional, Tuple, Union, cast from app.application.audio import use_music_cue from app.application.transfer.models import TransferTask @@ -34,6 +34,29 @@ from app.schemas.types import ( ) +def _manual_music_options_error( + files: list[FileItem], *, mtype: Optional[MediaType], music_type: Optional[str], media_id: Optional[str], + preview: Optional[bool], track_match: str, target_path: Optional[Path], +) -> Optional[str]: + """ + 校验旧链调用方的音乐选项,避免绕过 HTTP Schema 后静默使用无效选择。 + """ + if track_match == "strict" and target_path is None: + return None + if mtype not in (None, MediaType.MUSIC): + return "音乐手动整理选项不能用于影视整理" + if target_path is not None and (not target_path.is_absolute() or ".." in target_path.parts): + return "音乐最终目录必须为不含上级跳转的绝对路径" + if track_match not in {"strict", "ignore_duration", "sequential"}: + return "不支持的音乐曲目对齐方式" + if track_match != "strict": + if music_type != MUSIC_ENTITY_ALBUM or (not preview and not media_id): + return "请先选择音乐专辑,再调整曲目对齐方式" + if any(item.storage != "local" for item in files): + return "调整曲目对齐方式需要读取本地音频,请先将所选音乐下载到本地" + return None + + def _recognize_manual_media( *, media_source: MediaSource, @@ -83,7 +106,8 @@ class TransferHistoryOwner(_TransferOwnerBase): 隔离本次 CUE 策略,批次与普通请求均保持既有整理入口兼容。 """ with use_music_cue(music_cue_enable): - if selected_fileitems is not None or report_results or skip_success: + if (selected_fileitems is not None or report_results or skip_success + or "music_track_match" in transfer_kwargs or "music_target_path" in transfer_kwargs): return cast( Tuple[bool, Union[str, dict[str, Any]]], self._execute_transfer( @@ -222,6 +246,8 @@ class TransferHistoryOwner(_TransferOwnerBase): skip_success: bool = False, musicbrainz_release_id: Optional[str] = None, music_cue_enable: Optional[bool] = None, + music_track_match: Literal["strict", "ignore_duration", "sequential"] = "strict", + music_target_path: Optional[Path] = None, ) -> Tuple[bool, Union[str, dict[str, Any]]]: """ 手动整理,支持复杂条件,带进度显示 @@ -256,8 +282,18 @@ class TransferHistoryOwner(_TransferOwnerBase): :param skip_success: 预览和执行均跳过成功记录,优先于强制整理和重整 :param musicbrainz_release_id: 指定属于 media_id 发行组的具体 MusicBrainz 发行版 :param music_cue_enable: 本次是否识别 CUE,空值继承系统设置,不修改全局开关 + :param music_track_match: 本次手选专辑的曲目对齐方式,默认严格校验 + :param music_target_path: 本次音乐最终目录,仅应用文件名模板 """ logger.info(f"手动整理:{fileitem.path} ...") + options_error = _manual_music_options_error( + selected_fileitems or [fileitem], mtype=mtype, music_type=music_type, media_id=media_id, + preview=preview, track_match=music_track_match, target_path=music_target_path, + ) + if options_error: + return False, options_error + if music_track_match != "strict" or music_target_path is not None: + mtype = MediaType.MUSIC explicit_identity = media_source is not None or media_id is not None if explicit_identity and (not media_source or not media_id): return False, "手动整理需要同时提供 media_source 和 media_id" @@ -293,6 +329,11 @@ class TransferHistoryOwner(_TransferOwnerBase): music_release_regions=music_release_regions, music_release_scripts=music_release_scripts, ) + if music_track_match != "strict": + transfer_kwargs["music_track_match"] = music_track_match + if music_target_path is not None: + transfer_kwargs["music_target_path"] = music_target_path + transfer_kwargs["target_path"] = target_path or music_target_path if media_source and media_id: # 有输入媒体ID时预先识别,音乐与影视统一走 recognize_media 按类型分发 mediainfo = _recognize_manual_media( diff --git a/app/chain/transfer/music.py b/app/chain/transfer/music.py index 3b2d0618e..4a3805f11 100644 --- a/app/chain/transfer/music.py +++ b/app/chain/transfer/music.py @@ -84,13 +84,16 @@ class MusicReleaseGroup: def music_planning_input( owner: _TransferOwnerBase, task: TransferTask, context: MusicBatchContext, cleanup: Optional[FileItem], regions: Optional[list[str]], scripts: Optional[list[str]], + *, music_target_path: Optional[Path] = None, ) -> TransferPlanningInput: """ - 冻结需要重新识别的原发行范围,重启恢复不能扩大到未选择的其他专辑。 + 冻结原发行范围与本次最终目录,重启恢复沿用准入时的选择。 """ planning = cast(TransferPlanningInput, owner._TransferChain__build_planning_input(task, cleanup_dest_fileitem=cleanup)) if not isinstance(task.meta, MetaMusic): return planning + if music_target_path is not None: + planning = replace(planning, options={**planning.options, "music_target_path": music_target_path.as_posix()}) if task.preview: task.bind_music_preview_context(_music_preview_context(owner, task, context)) recognition = task.mediainfo.raw_data.get("recognition", {}) if isinstance(task.mediainfo, MusicInfo) else {} diff --git a/app/chain/transfer/workflow.py b/app/chain/transfer/workflow.py index 37030d0f3..fddbcdb5d 100644 --- a/app/chain/transfer/workflow.py +++ b/app/chain/transfer/workflow.py @@ -517,6 +517,8 @@ class TransferWorkflowOwner(_TransferOwnerBase): selected_fileitems: Optional[list[FileItem]] = None, report_results: bool = False, skip_success: bool = False, + music_track_match: Literal["strict", "ignore_duration", "sequential"] = "strict", + music_target_path: Optional[Path] = None, ) -> Tuple[bool, Union[str, dict[str, Any]]]: """ 执行一个复杂目录的整理操作 @@ -553,6 +555,8 @@ class TransferWorkflowOwner(_TransferOwnerBase): :param selected_fileitems: 前端显式选中的文件,按同一批次规划 :param report_results: 返回实际阶段回执,后台接收不表示入库完成 :param skip_success: 在预览、历史清理及任务准入前跳过成功记录 + :param music_track_match: 手选专辑的曲目对齐方式,默认严格校验 + :param music_target_path: 本次音乐最终目录,冻结后用于预览及恢复执行 返回:成功标识,错误信息 """ selected_music_album: Optional[MusicAlbumInfo] @@ -641,7 +645,8 @@ class TransferWorkflowOwner(_TransferOwnerBase): file_items, inherited_meta_map = candidate_planner._plan_file_items(file_items) selected_music_track_map, selected_music_error = self._selected_music_track_map( - file_items, selected_music_album + file_items, selected_music_album, + **({"track_match": music_track_match} if music_track_match != "strict" else {}), ) if selected_music_error: return False, selected_music_error @@ -692,6 +697,7 @@ class TransferWorkflowOwner(_TransferOwnerBase): music_release_scripts=music_release_scripts, selected_music_track_map=selected_music_track_map, submission=submission, + music_target_path=music_target_path, ) except OperationInterrupted: return submission.result(False, [f"{fileitem.name} 已取消"], preview=False, preview_items=[]) @@ -791,6 +797,7 @@ class TransferWorkflowOwner(_TransferOwnerBase): music_release_scripts: Optional[list[str]], selected_music_track_map: dict[str, MusicInfo], submission: _TransferSubmissionCollector, + music_target_path: Optional[Path] = None, ) -> Tuple[List[TransferTask], bool, List[str], int, set[Tuple[str, str]]]: """ 从冻结候选构建任务,并集中执行历史去重与 持久化 绑定。 @@ -983,7 +990,8 @@ class TransferWorkflowOwner(_TransferOwnerBase): cleanup_intent = cleanup_dest_fileitem if not preview and not cleanup_intent_assigned else None transfer_task.bind_planning_input( self._build_music_planning_input(transfer_task, music_batch_context, cleanup_intent, - music_release_regions, music_release_scripts) + music_release_regions, music_release_scripts, + music_target_path=music_target_path) ) if ( recovery_admission diff --git a/app/domain/music.py b/app/domain/music.py index b5e12f191..588b2ab9b 100644 --- a/app/domain/music.py +++ b/app/domain/music.py @@ -589,9 +589,11 @@ def _music_track_identity_match(meta: MetaMusic, track: MusicInfo, allow_title_o return identity_match -def _music_track_pair_score(meta: MetaMusic, track: MusicInfo, allow_title_override: bool) -> float: +def _music_track_pair_score( + meta: MetaMusic, track: MusicInfo, allow_title_override: bool, ignore_duration: bool, +) -> float: """ - 评估一条文件与发行曲目的证据;明确身份或时长冲突不能被其它分数抵消。 + 评估文件与发行曲目的证据,仅在手动明确忽略时长时跳过时长证据。 """ if not allow_title_override and music_credit_conflicts(track, meta): return 0.0 @@ -606,7 +608,7 @@ def _music_track_pair_score(meta: MetaMusic, track: MusicInfo, allow_title_overr and not music_artist_evidence_matches(track, meta, artists)): return 0.0 duration_close = False - if meta.duration and track.duration: + if not ignore_duration and meta.duration and track.duration: delta = abs(meta.duration - track.duration) longest = max(meta.duration, track.duration) if delta > max(10, longest * 0.08): @@ -623,7 +625,7 @@ def _music_track_pair_score(meta: MetaMusic, track: MusicInfo, allow_title_overr ) if not identity_match and not title_match and not weak_title and not (allow_title_override and position_match): return 0.0 - if not identity_match and not title_match and meta.duration and track.duration and not duration_close: + if not ignore_duration and not identity_match and not title_match and meta.duration and track.duration and not duration_close: return 0.0 if not (identity_match or title_match or position_match or (weak_title and duration_close)): return 0.0 @@ -644,17 +646,21 @@ def _unique_track_choice(scores: dict[int, float]) -> Optional[int]: def align_music_tracks( metas: list[MetaMusic], tracks: list[MusicInfo], *, allow_title_override: bool = False, + track_match: Literal["strict", "ignore_duration", "sequential"] = "strict", ) -> dict[int, int]: """ 以双向唯一证据对位曲目,返回本地索引到远端索引;无证据项保持未匹配。 - 手选发行可依据唯一位置纠正旧曲名及旧身份,但仍拒绝显著时长冲突。 - 双向检查使重复版本不能抢占一个位置,输入排序不会改变歌曲身份。 + 手选发行可依据唯一位置纠正旧曲名及旧身份,默认拒绝显著时长冲突。 + ignore_duration 跳过时长证据;sequential 按输入顺序对应且要求数量一致。 + 严格与忽略时长模式通过双向检查消除重复版本歧义,输入排序不会改变歌曲身份。 """ + if track_match == "sequential": + return dict(enumerate(range(len(tracks)))) if len(metas) == len(tracks) else {} scores = { index: { remote: score for remote, track in enumerate(tracks) - if (score := _music_track_pair_score(meta, track, allow_title_override)) > 0 + if (score := _music_track_pair_score(meta, track, allow_title_override, track_match == "ignore_duration")) > 0 } for index, meta in enumerate(metas) } diff --git a/app/modules/filemanager/module.py b/app/modules/filemanager/module.py index 792f8ef58..fdc732e68 100644 --- a/app/modules/filemanager/module.py +++ b/app/modules/filemanager/module.py @@ -578,6 +578,14 @@ class FileManagerModule(_ModuleBase): :raises ValueError: 源路径、目标路径、整理方式或存储配置无效 """ handler = TransHandler() + music_target = ( + planning_input.options.get("music_target_path") + if planning_input is not None and mediainfo.type == MediaType.MUSIC else None + ) + music_target_path = Path(music_target) if isinstance(music_target, str) and music_target else None + target_path = music_target_path or target_path + library_type_folder = False if music_target_path else library_type_folder + library_category_folder = False if music_target_path else library_category_folder if ( fileitem.storage == "local" and (not fileitem.path or not Path(fileitem.path).exists()) @@ -622,6 +630,8 @@ class FileManagerModule(_ModuleBase): logger.error( f"{mediainfo.type.value if mediainfo.type else '未知类型'} {mediainfo.title_year} 未找到有效的媒体库目录,无法整理文件,源路径:{fileitem.path}") raise TransferPlanningRejectedError("未找到有效的媒体库目录") + target_path = music_target_path or target_path + need_rename = bool(music_target_path) or need_rename if not transfer_type: directory_name = target_directory.name if target_directory else "目标目录" logger.error(f"{directory_name} 未设置整理方式") diff --git a/app/modules/filemanager/transhandler.py b/app/modules/filemanager/transhandler.py index 8f544ba07..7df2942fd 100644 --- a/app/modules/filemanager/transhandler.py +++ b/app/modules/filemanager/transhandler.py @@ -553,13 +553,9 @@ class TransHandler: ) if self.__is_subtitle_file(fileitem): final_target = self.__rename_subtitles(fileitem, final_target) - target_directory_path = DirectoryHelper.get_media_root_path( - rename_format, - rename_path=final_target, - media_type=mediainfo.type, + final_target, target_directory_path = self.__resolve_file_target_paths( + planning_input, mediainfo, target_path, final_target, rename_format, ) - if not target_directory_path: - raise ValueError("重命名格式无效") if self.__is_media_image_file(fileitem): # 封面保持原名并放到媒体根,不套用曲序/曲名模板或进入 Disc 子目录。 final_target = target_directory_path / Path(str(fileitem.path)).name @@ -599,6 +595,28 @@ class TransHandler: preview=preview, ) + @staticmethod + def __resolve_file_target_paths( + planning_input: TransferPlanningInput, + mediainfo: MediaInfo | MusicInfo, + target_path: Path, + rendered_path: Path, + rename_format: str, + ) -> tuple[Path, Path]: + """ + 解析模板文件与媒体根目录,手动音乐最终目录仅保留已渲染的文件名。 + + 先渲染完整模板可保留跨目录层级的 Jinja 条件语义。 + """ + if mediainfo.type == MediaType.MUSIC and planning_input.options.get("music_target_path"): + return target_path / rendered_path.name, target_path + media_root = DirectoryHelper.get_media_root_path( + rename_format, rename_path=rendered_path, media_type=mediainfo.type, + ) + if not media_root: + raise ValueError("重命名格式无效") + return rendered_path, media_root + @staticmethod def __intercept_transfer( *, diff --git a/app/schemas/transfer.py b/app/schemas/transfer.py index bcc80aa5f..8de7d4e89 100644 --- a/app/schemas/transfer.py +++ b/app/schemas/transfer.py @@ -372,6 +372,14 @@ class ManualTransferItem(OptionalMediaIdentityMixin, BaseModel): description="本次手动整理的 MusicBrainz 文字字形优先级;空值继承系统设置", ) music_cue_enable: Optional[bool] = Field(default=None, strict=True, description="本次手动整理是否识别 CUE;空值继承系统设置") + music_track_match: Literal["strict", "ignore_duration", "sequential"] = Field( + default="strict", + description="本次手选专辑曲目对齐方式,支持严格校验、忽略时长或按源路径自然顺序套用。顺序模式要求曲目数一致", + ) + music_target_path: Optional[str] = Field( + default=None, + description="本次音乐最终目录。填写后只应用文件名模板,类型、分类及专辑目录层级由此路径确定", + ) type_name: Optional[str] = Field(default=None, description="类型") season: Optional[int] = Field(default=None, description="季号") transfer_type: Optional[str] = Field(default=None, description="整理方式") @@ -392,6 +400,24 @@ class ManualTransferItem(OptionalMediaIdentityMixin, BaseModel): reorganize: Optional[bool] = Field(default=False, description="重新整理,清理命中的成功历史及其旧目标") skip_success: bool = Field(default=False, description="跳过成功历史,优先于重新整理;预览与执行使用相同过滤范围") + @model_validator(mode="after") + def validate_music_manual_options(self) -> "ManualTransferItem": + """ + 限定音乐专用选项并规范最终目录,拒绝相对路径和上级目录跳转。 + """ + if self.music_track_match == "strict" and not self.music_target_path: + return self + if (self.type_name or "").strip().lower() not in {"", "自动", "auto", "none", "音乐", "music"}: + raise ValueError("音乐手动整理选项不能用于影视整理") + if self.music_track_match != "strict" and self.music_type != "album": + raise ValueError("调整曲目对齐方式需要选择音乐专辑") + if self.music_target_path is not None: + path = Path(self.music_target_path.strip()) + if not path.is_absolute() or ".." in path.parts: + raise ValueError("音乐最终目录必须为不含上级跳转的绝对路径") + self.music_target_path = path.as_posix() + return self + @model_validator(mode="after") def validate_music_release_selection(self) -> "ManualTransferItem": """ diff --git a/docs/mcp-api.md b/docs/mcp-api.md index 69f6b44d3..4bd657599 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -609,6 +609,18 @@ Emby、Jellyfin、Plex、Navidrome 的目录、条目、搜索、季集和活动 音乐专辑刮削默认保留已有曲名、艺人和曲序,响应 `message` 与日志会说明。需要尝试更新时,可在系统刮削设置中将“音乐标签”设为“覆盖”:只有与专辑曲目双向唯一对位、且录音身份和时长没有冲突的文件才会采用来源提供的曲目字段;未可靠匹配的文件继续保留本地字段。手动刮削可按唯一曲序纠正曲名,自动刮削使用更严格的证据;启用 CUE 读取时,整轨 CUE 不会被当作单曲覆盖。结果中的匹配数量不等同于实际发生变化的标签数量。远端音轨在对位和写入阶段分别下载;启用 CUE 读取时,目录未列出当前音轨或索引下载失败会保留曲目字段。普通远端存储列表不保证返回全部子项,使用此类存储前应核对 CUE 或通过本地挂载操作。 +### 音乐手动整理选项 + +`transfer.manual` 的 `music_track_match` 默认 `strict`。手动选择专辑后可设为 +`ignore_duration`,跳过时长证据并继续要求曲目唯一对位;`sequential` 将源文件按完整路径 +自然排序(2 在 10 前),依次套用发行版曲目。顺序模式要求逻辑曲目数一致,CUE 按逻辑曲目计数。 +这些选项需要本地音频,预览和执行应使用相同参数与源文件范围。 + +`music_target_path` 接受音乐最终目录的绝对路径。填写后保留文件名模板,把类型、分类、 +专辑与音质目录层级统一落在该目录;留空沿用现有目录规则。歌词同步重命名,封面与整轨 CUE +保持配套文件命名规则。最终目录与已选曲目身份会冻结到任务输入,任务恢复沿用原选择。 +音乐没有线上条目时,可留空媒体 ID,使用完整的本地标签整理。 + ### 分页与截断 - 按选定操作的合同使用分页字段。例如 `subscription.list` 使用 `page` / `count`,`subscription.execution.list` 使用 `limit`,原生服务列表常用 `offset` / `limit`。 diff --git a/skills/moviepilot-api/api/transfer.md b/skills/moviepilot-api/api/transfer.md index 842cb73af..abf8232d9 100644 --- a/skills/moviepilot-api/api/transfer.md +++ b/skills/moviepilot-api/api/transfer.md @@ -26,6 +26,16 @@ other albums with the same display name. Unsupported packages appear as failed i a default. Preview and execute with identical IDs and source items; this path requires local audio for track alignment. Do not place a Release ID in `media_id`. +For a manually chosen album, `music_track_match` defaults to `strict`. +`ignore_duration` removes duration evidence while retaining unique track matching. +`sequential` pairs naturally sorted full source paths (2 before 10) with release tracks +and requires equal logical track counts, including CUE tracks. These modes require local audio. +Preview and execute using the same source scope and options, and inspect sequential mappings. +`music_target_path` is an optional absolute final music directory. It applies only the +filename template and places tracks and companions in that directory. The task freezes +this choice for recovery. With no online album, omit the media ID to use complete local tags. + + ## Durable AI recognition correction With both `AI_AGENT_ENABLE` and `AI_AGENT_RETRY_TRANSFER` enabled, a newly committed @@ -57,7 +67,7 @@ Purpose: 执行手动文件转移与整理流程。 Identity scope: `admin`; required role: `system_admin`. - `path_params`: none - `query`: `background` (boolean|null; default `False`): 是否异步执行整理,并在完成前返回。 -- `body`: `episode_detail` (string|null): 指定集数; `episode_format` (string|null): 自定义格式; `episode_group` (string|null): 剧集组; `episode_offset` (string|null): 集数偏移; `episode_part` (string|null): 指定PART; `fileitem` (FileItem-Input): storage.list 返回的一个完整源存储项目。; `fileitems` (array|null): 文件项列表(前端多选时传入); `from_history` (boolean|null; default `False`): 复用历史识别信息; `library_category_folder` (boolean|null): 媒体库类别子目录; `library_type_folder` (boolean|null): 媒体库类型子目录; `logid` (integer|null): 日志ID; `logids` (array|null): 日志ID列表(前端多选历史记录时传入); `media_id` (string|null): 数据源原生ID; `media_source` (MediaSource|null): 媒体数据源; `min_filesize` (integer|null; default `0`): 最小文件大小; `music_cue_enable` (boolean|null): 本次手动整理是否识别 CUE;空值继承系统设置; `music_release_regions` (array|null): 本次手动整理的 MusicBrainz 发行地区优先级;空值继承系统设置; `music_release_scripts` (array|null): 本次手动整理的 MusicBrainz 文字字形优先级;空值继承系统设置; `music_type` (string(recording,album)|null): 音乐实体类型; `musicbrainz_release_id` (string|null): 显式选择具体发行版;media_id 仍为 Release Group,不能互换; `preview` (boolean|null; default `False`): 仅预览,不执行整理; `reorganize` (boolean|null; default `False`): 重新整理,清理命中的成功历史及其旧目标; `scrape` (boolean|null; default `False`): 刮削; `season` (integer|null): 季号; `skip_success` (boolean; default `False`): 跳过成功历史,优先于重新整理;预览与执行使用相同过滤范围; `target_path` (string|null): 目标路径; `target_storage` (string|null): 目标存储; `transfer_type` (string|null): 整理方式; `type_name` (string|null): 类型 +- `body`: `episode_detail` (string|null): 指定集数; `episode_format` (string|null): 自定义格式; `episode_group` (string|null): 剧集组; `episode_offset` (string|null): 集数偏移; `episode_part` (string|null): 指定PART; `fileitem` (FileItem-Input): storage.list 返回的一个完整源存储项目。; `fileitems` (array|null): 文件项列表(前端多选时传入); `from_history` (boolean|null; default `False`): 复用历史识别信息; `library_category_folder` (boolean|null): 媒体库类别子目录; `library_type_folder` (boolean|null): 媒体库类型子目录; `logid` (integer|null): 日志ID; `logids` (array|null): 日志ID列表(前端多选历史记录时传入); `media_id` (string|null): 数据源原生ID; `media_source` (MediaSource|null): 媒体数据源; `min_filesize` (integer|null; default `0`): 最小文件大小; `music_cue_enable` (boolean|null): 本次手动整理是否识别 CUE;空值继承系统设置; `music_release_regions` (array|null): 本次手动整理的 MusicBrainz 发行地区优先级;空值继承系统设置; `music_release_scripts` (array|null): 本次手动整理的 MusicBrainz 文字字形优先级;空值继承系统设置; `music_target_path` (string|null; default `None`): 本次音乐最终目录。填写后只应用文件名模板,类型、分类及专辑目录层级由此路径确定; `music_track_match` (string(strict,ignore_duration,sequential); default `strict`): 本次手选专辑曲目对齐方式,支持严格校验、忽略时长或按源路径自然顺序套用。顺序模式要求曲目数一致; `music_type` (string(recording,album)|null): 音乐实体类型; `musicbrainz_release_id` (string|null): 显式选择具体发行版;media_id 仍为 Release Group,不能互换; `preview` (boolean|null; default `False`): 仅预览,不执行整理; `reorganize` (boolean|null; default `False`): 重新整理,清理命中的成功历史及其旧目标; `scrape` (boolean|null; default `False`): 刮削; `season` (integer|null): 季号; `skip_success` (boolean; default `False`): 跳过成功历史,优先于重新整理;预览与执行使用相同过滤范围; `target_path` (string|null): 目标路径; `target_storage` (string|null): 目标存储; `transfer_type` (string|null): 整理方式; `type_name` (string|null): 类型 ### `transfer.history` `GET /api/v1/history/transfer`; policy effect: `safe_read`. @@ -127,7 +137,7 @@ Purpose: 检查给定存储项目是否已有成功整理历史。 Identity scope: `admin`; required role: `system_admin`. - `path_params`: none - `query`: none -- `body`: `episode_detail` (string|null): 指定集数; `episode_format` (string|null): 自定义格式; `episode_group` (string|null): 剧集组; `episode_offset` (string|null): 集数偏移; `episode_part` (string|null): 指定PART; `fileitem` (FileItem-Input): storage.list 返回的一个完整源存储项目。; `fileitems` (array|null): 文件项列表(前端多选时传入); `from_history` (boolean|null; default `False`): 复用历史识别信息; `library_category_folder` (boolean|null): 媒体库类别子目录; `library_type_folder` (boolean|null): 媒体库类型子目录; `logid` (integer|null): 日志ID; `logids` (array|null): 日志ID列表(前端多选历史记录时传入); `media_id` (string|null): 数据源原生ID; `media_source` (MediaSource|null): 媒体数据源; `min_filesize` (integer|null; default `0`): 最小文件大小; `music_cue_enable` (boolean|null): 本次手动整理是否识别 CUE;空值继承系统设置; `music_release_regions` (array|null): 本次手动整理的 MusicBrainz 发行地区优先级;空值继承系统设置; `music_release_scripts` (array|null): 本次手动整理的 MusicBrainz 文字字形优先级;空值继承系统设置; `music_type` (string(recording,album)|null): 音乐实体类型; `musicbrainz_release_id` (string|null): 显式选择具体发行版;media_id 仍为 Release Group,不能互换; `preview` (boolean|null; default `False`): 仅预览,不执行整理; `reorganize` (boolean|null; default `False`): 重新整理,清理命中的成功历史及其旧目标; `scrape` (boolean|null; default `False`): 刮削; `season` (integer|null): 季号; `skip_success` (boolean; default `False`): 跳过成功历史,优先于重新整理;预览与执行使用相同过滤范围; `target_path` (string|null): 目标路径; `target_storage` (string|null): 目标存储; `transfer_type` (string|null): 整理方式; `type_name` (string|null): 类型 +- `body`: `episode_detail` (string|null): 指定集数; `episode_format` (string|null): 自定义格式; `episode_group` (string|null): 剧集组; `episode_offset` (string|null): 集数偏移; `episode_part` (string|null): 指定PART; `fileitem` (FileItem-Input): storage.list 返回的一个完整源存储项目。; `fileitems` (array|null): 文件项列表(前端多选时传入); `from_history` (boolean|null; default `False`): 复用历史识别信息; `library_category_folder` (boolean|null): 媒体库类别子目录; `library_type_folder` (boolean|null): 媒体库类型子目录; `logid` (integer|null): 日志ID; `logids` (array|null): 日志ID列表(前端多选历史记录时传入); `media_id` (string|null): 数据源原生ID; `media_source` (MediaSource|null): 媒体数据源; `min_filesize` (integer|null; default `0`): 最小文件大小; `music_cue_enable` (boolean|null): 本次手动整理是否识别 CUE;空值继承系统设置; `music_release_regions` (array|null): 本次手动整理的 MusicBrainz 发行地区优先级;空值继承系统设置; `music_release_scripts` (array|null): 本次手动整理的 MusicBrainz 文字字形优先级;空值继承系统设置; `music_target_path` (string|null; default `None`): 本次音乐最终目录。填写后只应用文件名模板,类型、分类及专辑目录层级由此路径确定; `music_track_match` (string(strict,ignore_duration,sequential); default `strict`): 本次手选专辑曲目对齐方式,支持严格校验、忽略时长或按源路径自然顺序套用。顺序模式要求曲目数一致; `music_type` (string(recording,album)|null): 音乐实体类型; `musicbrainz_release_id` (string|null): 显式选择具体发行版;media_id 仍为 Release Group,不能互换; `preview` (boolean|null; default `False`): 仅预览,不执行整理; `reorganize` (boolean|null; default `False`): 重新整理,清理命中的成功历史及其旧目标; `scrape` (boolean|null; default `False`): 刮削; `season` (integer|null): 季号; `skip_success` (boolean; default `False`): 跳过成功历史,优先于重新整理;预览与执行使用相同过滤范围; `target_path` (string|null): 目标路径; `target_storage` (string|null): 目标存储; `transfer_type` (string|null): 整理方式; `type_name` (string|null): 类型 ### `transfer.manual_review` `GET /api/v1/transfer/tasks/{task_id}/manual-review`; policy effect: `safe_read`. @@ -185,7 +195,7 @@ Purpose: 根据给定源存储项目解析已配置的整理目标。 Identity scope: `admin`; required role: `system_admin`. - `path_params`: none - `query`: none -- `body`: `episode_detail` (string|null): 指定集数; `episode_format` (string|null): 自定义格式; `episode_group` (string|null): 剧集组; `episode_offset` (string|null): 集数偏移; `episode_part` (string|null): 指定PART; `fileitem` (FileItem-Input): storage.list 返回的一个完整源存储项目。; `fileitems` (array|null): 文件项列表(前端多选时传入); `from_history` (boolean|null; default `False`): 复用历史识别信息; `library_category_folder` (boolean|null): 媒体库类别子目录; `library_type_folder` (boolean|null): 媒体库类型子目录; `logid` (integer|null): 日志ID; `logids` (array|null): 日志ID列表(前端多选历史记录时传入); `media_id` (string|null): 数据源原生ID; `media_source` (MediaSource|null): 媒体数据源; `min_filesize` (integer|null; default `0`): 最小文件大小; `music_cue_enable` (boolean|null): 本次手动整理是否识别 CUE;空值继承系统设置; `music_release_regions` (array|null): 本次手动整理的 MusicBrainz 发行地区优先级;空值继承系统设置; `music_release_scripts` (array|null): 本次手动整理的 MusicBrainz 文字字形优先级;空值继承系统设置; `music_type` (string(recording,album)|null): 音乐实体类型; `musicbrainz_release_id` (string|null): 显式选择具体发行版;media_id 仍为 Release Group,不能互换; `preview` (boolean|null; default `False`): 仅预览,不执行整理; `reorganize` (boolean|null; default `False`): 重新整理,清理命中的成功历史及其旧目标; `scrape` (boolean|null; default `False`): 刮削; `season` (integer|null): 季号; `skip_success` (boolean; default `False`): 跳过成功历史,优先于重新整理;预览与执行使用相同过滤范围; `target_path` (string|null): 目标路径; `target_storage` (string|null): 目标存储; `transfer_type` (string|null): 整理方式; `type_name` (string|null): 类型 +- `body`: `episode_detail` (string|null): 指定集数; `episode_format` (string|null): 自定义格式; `episode_group` (string|null): 剧集组; `episode_offset` (string|null): 集数偏移; `episode_part` (string|null): 指定PART; `fileitem` (FileItem-Input): storage.list 返回的一个完整源存储项目。; `fileitems` (array|null): 文件项列表(前端多选时传入); `from_history` (boolean|null; default `False`): 复用历史识别信息; `library_category_folder` (boolean|null): 媒体库类别子目录; `library_type_folder` (boolean|null): 媒体库类型子目录; `logid` (integer|null): 日志ID; `logids` (array|null): 日志ID列表(前端多选历史记录时传入); `media_id` (string|null): 数据源原生ID; `media_source` (MediaSource|null): 媒体数据源; `min_filesize` (integer|null; default `0`): 最小文件大小; `music_cue_enable` (boolean|null): 本次手动整理是否识别 CUE;空值继承系统设置; `music_release_regions` (array|null): 本次手动整理的 MusicBrainz 发行地区优先级;空值继承系统设置; `music_release_scripts` (array|null): 本次手动整理的 MusicBrainz 文字字形优先级;空值继承系统设置; `music_target_path` (string|null; default `None`): 本次音乐最终目录。填写后只应用文件名模板,类型、分类及专辑目录层级由此路径确定; `music_track_match` (string(strict,ignore_duration,sequential); default `strict`): 本次手选专辑曲目对齐方式,支持严格校验、忽略时长或按源路径自然顺序套用。顺序模式要求曲目数一致; `music_type` (string(recording,album)|null): 音乐实体类型; `musicbrainz_release_id` (string|null): 显式选择具体发行版;media_id 仍为 Release Group,不能互换; `preview` (boolean|null; default `False`): 仅预览,不执行整理; `reorganize` (boolean|null; default `False`): 重新整理,清理命中的成功历史及其旧目标; `scrape` (boolean|null; default `False`): 刮削; `season` (integer|null): 季号; `skip_success` (boolean; default `False`): 跳过成功历史,优先于重新整理;预览与执行使用相同过滤范围; `target_path` (string|null): 目标路径; `target_storage` (string|null): 目标存储; `transfer_type` (string|null): 整理方式; `type_name` (string|null): 类型 ## Body Models diff --git a/tests/test_filemanager_planning.py b/tests/test_filemanager_planning.py index 17cc9c5d3..ebab9561f 100644 --- a/tests/test_filemanager_planning.py +++ b/tests/test_filemanager_planning.py @@ -13,8 +13,9 @@ from app.application.transfer.workflow import ( TransferPlanItem, TransferPlanningInput, ) -from app.domain.context import MediaInfo +from app.domain.context import MediaInfo, MusicInfo from app.domain.meta.metabase import MetaBase +from app.domain.meta.metamusic import MetaMusic from app.modules.filemanager import transhandler as transhandler_module from app.modules.filemanager.module import FileManagerModule from app.modules.filemanager.transhandler import TransHandler @@ -380,6 +381,53 @@ def test_module_preserves_admission_input_while_freezing_resolved_directory(): assert checkpoint.resolved_mediainfo["title"] == "Test Show" +@pytest.mark.parametrize("configured", [False, True]) +@pytest.mark.parametrize("renaming", [False, True]) +@pytest.mark.parametrize("extension", ["flac", "lrc", "jpg"]) +def test_manual_music_final_directory_preserves_filename_and_frozen_input(monkeypatch, configured, renaming, extension): + """ + 手动最终目录覆盖分类及模板目录,音频歌词仍重命名,封面保持原名且规划不写文件。 + """ + fileitem = _build_fileitem().model_copy(update={ + "path": f"/downloads/song.{extension}", "name": f"song.{extension}", "extension": extension, + }) + meta = MetaMusic(title="Selected Song", album="Album", artists=["Artist"], track_number=1, + sample_rate=48000, duration=30) + info = MusicInfo.from_meta(meta) + planning = _build_input(fileitem, options={"music_target_path": "/chosen/OST/Album"}) + fingerprint = planning.fingerprint + original_get_setting = transhandler_module.get_runtime_setting + + def setting(name): + """ + 以跨目录条件模板验证先完整渲染再提取文件名,其他配置仍走隔离默认值。 + """ + if name == "RENAME_FORMAT": + return lambda _type: "{% if sample_rate %}{{sample_rate}}/{{album}}/{% endif %}{{track}} - {{title}}{{fileExt}}" + return original_get_setting(name) + + monkeypatch.setattr(transhandler_module, "get_runtime_setting", setting) + directory = TransferDirectoryConf( + library_path="/configured-library", library_storage="alist", transfer_type="copy", renaming=renaming, + library_type_folder=True, library_category_folder=True, scraping=True, overwrite_mode="never", + ) if configured else None + checkpoint = FileManagerModule().plan_transfer( + fileitem=fileitem, meta=meta, mediainfo=info, target_directory=directory, target_path=Path("/default-root"), + target_storage="alist", transfer_type="copy", library_type_folder=True, library_category_folder=True, + source_oper=ReadOnlyTreeStorage({}), planning_input=planning, + ) + target = Path(checkpoint.final_target_path) + assert target.parent == Path("/chosen/OST/Album") + assert target.name == ("song.jpg" if extension == "jpg" else f"01 - Selected Song.{extension}") + assert checkpoint.root_target_path == "/chosen/OST/Album" + assert checkpoint.planning_input.fingerprint == fingerprint + assert checkpoint.resolved_meta["sample_rate"] == 48000 + assert checkpoint.resolved_meta["duration"] == 30 + restored = TransferPlanCheckpoint.from_payload(checkpoint.to_payload()) + assert restored.final_target_path == checkpoint.final_target_path + assert restored.planning_input.options["music_target_path"] == "/chosen/OST/Album" + + def _build_cleanup_checkpoint(monkeypatch, calls: list[str]): """ 构造带冻结旧目标清理意图的单文件检查点。 diff --git a/tests/test_music_release_selection.py b/tests/test_music_release_selection.py index 8fde322b3..87c01bfc5 100644 --- a/tests/test_music_release_selection.py +++ b/tests/test_music_release_selection.py @@ -5,6 +5,7 @@ import asyncio from copy import deepcopy from hashlib import sha256 +from pathlib import Path from types import SimpleNamespace from unittest.mock import AsyncMock, Mock @@ -174,7 +175,8 @@ async def test_album_http_preserves_edition_and_rejects_wrong_source(monkeypatch @pytest.mark.parametrize("selected_files", [False, True]) -def test_manual_edition_preview_execution_and_replay_keep_same_tracks(tmp_path, monkeypatch, selected_files): +@pytest.mark.parametrize("track_match", ["strict", "ignore_duration", "sequential"]) +def test_manual_edition_preview_execution_and_replay_keep_same_tracks(tmp_path, monkeypatch, selected_files, track_match): """ 真实FLAC经API到曲目规划,预览与执行同版;冻结任务重放不另选标准版或改源文件。 """ @@ -184,6 +186,12 @@ def test_manual_edition_preview_execution_and_replay_keep_same_tracks(tmp_path, chain = _prepare_chain(monkeypatch, items) monkeypatch.setattr("app.chain.transfer.workflow.StorageChain.get_item", lambda _self, item: item) group, release = _payloads() + if track_match != "strict": + for index, track in enumerate(release["media"][0]["tracks"]): + track["length"] = 180000 + index * 60000 + if track_match == "sequential": + track["title"] = f"Chosen Song {index + 1}" + items.reverse() module, _calls = _module(monkeypatch, group, release) metadata = MediaChain() source = MusicBrainzChain() @@ -206,12 +214,17 @@ def test_manual_edition_preview_execution_and_replay_keep_same_tracks(tmp_path, for preview in (True, False): request = ManualTransferItem(fileitem=_directory_item(paths[0].parent), fileitems=items if selected_files else None, media_source="musicbrainz", media_id=GROUP, music_type="album", type_name="音乐", - musicbrainz_release_id=DELUXE.upper(), preview=preview) + musicbrainz_release_id=DELUXE.upper(), preview=preview, + music_track_match=track_match, music_target_path=str(tmp_path / "chosen-library")) response = manual_transfer(request, background=False, history_query=SimpleNamespace(), _="test") assert response.success, response.message assert len(planned) == 4 - assert [entry[1]["title"] for entry in planned] == ["First Song", "Second Song"] * 2 + titles = [entry[1]["title"] for entry in planned] + expected = ["Chosen Song 1", "Chosen Song 2"] if track_match == "sequential" else ["First Song", "Second Song"] + assert sorted(titles[:2]) == sorted(titles[2:]) == expected assert all(entry[1]["musicbrainz_release_id"] == DELUXE for entry in planned) + assert all(entry[1]["duration"] == 3 for entry in planned) + assert all(entry[2].options["music_target_path"] == str(tmp_path / "chosen-library") for entry in planned) restored = [] replay_owner = make_transfer_chain() monkeypatch.setattr(replay_owner, "_TransferChain__bind_claimed_admission", lambda *_args: None) @@ -219,11 +232,28 @@ def test_manual_edition_preview_execution_and_replay_keep_same_tracks(tmp_path, for item, (_preview, info, planning) in zip(items, planned[2:]): admission = SimpleNamespace(planning_input=planning, task_id="replay-selected") assert replay_owner._TransferChain__queue_accepted_replay(item, admission) + assert restored[-1].planning_input.options["music_target_path"] == str(tmp_path / "chosen-library") assert restored[-1].mediainfo.musicbrainz_release_id == info["musicbrainz_release_id"] assert restored[-1].mediainfo.media_id == info["media_id"] assert [sha256(path.read_bytes()).hexdigest() for path in paths] == original +@pytest.mark.parametrize("changes", [ + {"music_track_match": "invalid"}, + {"music_track_match": "sequential", "music_type": "recording"}, + {"music_track_match": "ignore_duration", "type_name": "电影"}, + {"music_target_path": "relative/album"}, + {"music_target_path": "/library/../album"}, +]) +def test_manual_music_options_reject_invalid_namespace_or_directory(changes): + """ + 新选项默认关闭,错误模式、影视类型或不安全目录在请求边界被拒绝。 + """ + assert ManualTransferItem().music_track_match == "strict" + with pytest.raises(ValidationError): + ManualTransferItem(**({"music_type": "album"} | changes)) + + def test_invalid_manual_release_cannot_enqueue_or_fall_back(monkeypatch): """ 旧调用绕过HTTP时同样拒绝不完整发行身份,查不到发行也不进入文件整理。 @@ -241,6 +271,26 @@ def test_invalid_manual_release_cannot_enqueue_or_fall_back(monkeypatch): execute.assert_not_called() +@pytest.mark.parametrize("options", [ + {"music_target_path": Path("/library"), "mtype": MediaType.MOVIE}, + {"music_target_path": Path("relative")}, + {"music_target_path": Path("/library/../album")}, + {"music_track_match": "invalid"}, + {"music_track_match": "sequential", "music_type": "recording"}, + {"music_track_match": "sequential", "music_type": "album"}, +]) +def test_invalid_manual_music_options_do_not_start_transfer(monkeypatch, options): + """ + 直接调用旧链入口同样拒绝跨类型、相对目录、非法模式和未选专辑的顺序套用。 + """ + owner = make_transfer_chain() + execute = Mock() + monkeypatch.setattr(owner, "_execute_transfer", execute) + state, message = owner.manual_transfer(make_fileitem("/music/song.flac"), **options) + assert not state and message + execute.assert_not_called() + + def test_explicit_release_remote_storage_fails_before_lookup(monkeypatch): """ 远端无法读取曲目证据时明确拒绝指定发行,防止退回逐文件默认识别。 @@ -255,7 +305,8 @@ def test_explicit_release_remote_storage_fails_before_lookup(monkeypatch): lookup.assert_not_called() -def test_explicit_release_cue_keeps_album_identity_and_companion(tmp_path, monkeypatch): +@pytest.mark.parametrize("track_match", ["strict", "ignore_duration", "sequential"]) +def test_explicit_release_cue_keeps_album_identity_and_companion(tmp_path, monkeypatch, track_match): """ 整轨按CUE逻辑曲目核验所选版,音频和索引仍作为同一专辑,不伪造单曲身份。 """ @@ -270,6 +321,8 @@ def test_explicit_release_cue_keeps_album_identity_and_companion(tmp_path, monke group, release = _payloads() tracks = release["media"][0]["tracks"] tracks[0]["length"], tracks[1]["length"] = 1000, 2000 + if track_match != "strict": + tracks[0]["length"], tracks[1]["length"] = 180000, 240000 module, _calls = _module(monkeypatch, group, release) metadata = MediaChain() source = MusicBrainzChain() @@ -289,6 +342,7 @@ def test_explicit_release_cue_keeps_album_identity_and_companion(tmp_path, monke monkeypatch.setattr(chain, "_TransferChain__handle_transfer", capture) state, result = TransferChain.manual_transfer(chain, _directory_item(audio.parent), media_source=MediaSource.MusicBrainz, media_id=GROUP, music_type="album", musicbrainz_release_id=DELUXE, + music_track_match=track_match, preview=True, background=False) assert state, result assert len(planned) == 2 diff --git a/tests/test_music_source_protection.py b/tests/test_music_source_protection.py index 1084a3b69..07494fc44 100644 --- a/tests/test_music_source_protection.py +++ b/tests/test_music_source_protection.py @@ -287,7 +287,8 @@ def test_original_year_does_not_become_current_release_date(tmp_path, model, dis @pytest.mark.parametrize("mode", ["copy", "link", "softlink"]) -def test_real_transfer_followed_by_scrape_preserves_seed_and_updates_library(tmp_path, monkeypatch, mode): +@pytest.mark.parametrize("manual_directory", [False, True]) +def test_real_transfer_followed_by_scrape_preserves_seed_and_updates_library(tmp_path, monkeypatch, mode, manual_directory): """ 真实规划、存储执行及刮削入口串联后,补写只作用于最终命名的媒体库文件。 """ @@ -299,7 +300,8 @@ def test_real_transfer_followed_by_scrape_preserves_seed_and_updates_library(tmp info = MusicInfo.from_meta(meta) info.cover_url = "https://example.invalid/cover.png" planning_input = TransferPlanningInput(source_fileitem=source_item.model_dump(mode="json"), target_storage="local", - target_path=str(tmp_path / "library"), requested_transfer_type=mode, need_rename=True) + target_path=str(tmp_path / "library"), requested_transfer_type=mode, need_rename=True, + options={"music_target_path": str(tmp_path / "library")} if manual_directory else {}) monkeypatch.setattr("app.modules.filemanager.transhandler.eventmanager.send_event", Mock(return_value=None)) handler = TransHandler() checkpoint = handler.plan_transfer(planning_input, meta=meta, mediainfo=info, source_oper=storage, @@ -310,6 +312,8 @@ def test_real_transfer_followed_by_scrape_preserves_seed_and_updates_library(tmp assert result.success, result.message target = Path(checkpoint.final_target_path) assert target.name == "01 - Song.flac" + if manual_directory: + assert target.parent == tmp_path / "library" if mode != "copy": assert source.samefile(target) diff --git a/tests/test_music_track_alignment.py b/tests/test_music_track_alignment.py index 9299c2d76..dc607315a 100644 --- a/tests/test_music_track_alignment.py +++ b/tests/test_music_track_alignment.py @@ -10,7 +10,7 @@ import pytest from app.chain.media import MediaChain from app.chain.transfer.facade import TransferChain -from app.domain.context import MusicInfo +from app.domain.context import MusicAlbumInfo, MusicInfo from app.domain.meta.metamusic import MetaMusic from app.domain.music import align_music_tracks from tests.test_transfer_sync_extra_files import make_fileitem @@ -114,6 +114,45 @@ def test_duration_conflict_blocks_even_exact_title_and_position(manual): assert align_music_tracks([local], [_track("First", 1, 180)], allow_title_override=manual) == {} +def test_ignoring_duration_keeps_unique_title_and_position_evidence(): + """ + 手动忽略时长允许片段对位,同时保留重复曲目的歧义与原始时长。 + """ + local = MetaMusic(title="First", track_number=1, duration=30) + track = _track("First", 1, 240) + options = {"allow_title_override": True, "track_match": "ignore_duration"} + assert align_music_tracks([local], [track], **options) == {0: 0} + assert align_music_tracks([local, local], [track], **options) == {} + assert align_music_tracks([MetaMusic(title="Track", duration=30)], [track], **options) == {} + assert local.duration == 30 and track.duration == 240 + + +def test_sequential_alignment_requires_equal_counts_and_uses_input_order(): + """ + 用户明确顺序套用时跳过曲名曲序时长证据,数量不一致时不生成部分映射。 + """ + metas = [MetaMusic(title="Unrelated", track_number=99, duration=30), MetaMusic(title="Other", duration=40)] + tracks = [_track("First", 1, 240), _track("Second", 2, 300)] + assert align_music_tracks(metas, tracks, track_match="sequential") == {0: 0, 1: 1} + assert align_music_tracks(metas[:1], tracks, track_match="sequential") == {} + assert align_music_tracks(metas, tracks[:1], track_match="sequential") == {} + + +def test_selected_album_sequential_order_is_natural_and_independent_of_request_order(tmp_path, monkeypatch): + """ + 顺序套用按完整路径自然排序,目录扫描和倒序多选都将 2 放在 10 之前。 + """ + paths = [tmp_path / "10.flac", tmp_path / "2.flac"] + tracks = [_track("First", 1, 180), _track("Second", 2, 240)] + album = MusicAlbumInfo(media_source="musicbrainz", tracks=tracks) + monkeypatch.setattr("app.chain.media.album.AudioMetadataHelper.read_many", + lambda files: [MetaMusic(title=path.stem, track_number=99, duration=30) for path in files]) + for files in (paths, list(reversed(paths))): + matched = MediaChain._align_selected_music_album(files, album, track_match="sequential") + assert matched[str(paths[1].resolve())].title == "First" + assert matched[str(paths[0].resolve())].title == "Second" + + def test_conflicting_position_does_not_beat_exact_title_or_duration(): """ 错标曲序应由明确的曲名或唯一时长纠正,不能先按序号绑定。 diff --git a/version.py b/version.py index 15cc47ecf..c772ad29f 100644 --- a/version.py +++ b/version.py @@ -3,7 +3,7 @@ """ APP_VERSION = 'v3.2.6' -FRONTEND_VERSION = 'v3.2.6' +FRONTEND_VERSION = 'v3.2.7' # 本版本要求的最低 Docker 镜像系统基线(ISO 日期),与镜像内 /etc/moviepilot/system-baseline 比较。 # 低于该值的镜像拒绝应用内更新,提示用户先更新 Docker 镜像。只在修复严重系统级漏洞时提高, # 且在同一发布中把 docker/system-baseline 改成相同日期,保证新镜像自身满足要求。