mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-02 00:46:27 +08:00
feat(transfer): add name and target directory preview endpoint for recognition test
This commit is contained in:
@@ -2,9 +2,10 @@
|
||||
提供文件整理任务查询、执行、重试和控制接口。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, List, Literal, Optional
|
||||
from typing import Annotated, Any, List, Literal, Optional, Union
|
||||
|
||||
from fastapi import Depends, HTTPException, Query, status
|
||||
|
||||
@@ -22,7 +23,7 @@ from app.api.response import (
|
||||
ResponseAPIRouter,
|
||||
)
|
||||
from app.application.configuration import get_api_runtime_config_snapshot
|
||||
from app.application.directory import DirectoryHelper
|
||||
from app.application.directory import DirectoryHelper, build_media_library_path
|
||||
from app.application.history import TransferHistoryLookupService
|
||||
from app.application.transfer.execution import (
|
||||
TransferExecutionCommand,
|
||||
@@ -36,6 +37,11 @@ from app.application.transfer.execution import (
|
||||
)
|
||||
from app.chain.media import MediaChain
|
||||
from app.chain.transfer.facade import TransferChain
|
||||
from app.domain.context import MediaInfo, MusicInfo
|
||||
from app.domain.media import is_music_media_source
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.domain.meta.metamusic import MetaMusic
|
||||
from app.domain.metainfo import MetaInfo, MetaInfoPath
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.stop import runtime_stop_state
|
||||
from app.schemas.common import NameData as _SchemaNameData
|
||||
@@ -59,8 +65,9 @@ from app.schemas.transfer import TransferManualReviewDiscardRequest as _SchemaTr
|
||||
from app.schemas.transfer import TransferManualReviewPageData as _SchemaTransferManualReviewPageData
|
||||
from app.schemas.transfer import TransferManualReviewRequest as _SchemaTransferManualReviewRequest
|
||||
from app.schemas.transfer import TransferManualReviewTaskData as _SchemaTransferManualReviewTaskData
|
||||
from app.schemas.transfer import TransferNamePreviewData as _SchemaTransferNamePreviewData
|
||||
from app.schemas.transfer import TransferQueuePageData as _SchemaTransferQueuePageData
|
||||
from app.schemas.types import MUSIC_ENTITY_ALBUM, MUSIC_ENTITY_RECORDING, MediaType
|
||||
from app.schemas.types import MUSIC_ENTITY_ALBUM, MUSIC_ENTITY_RECORDING, MediaSource, MediaType
|
||||
|
||||
router = ResponseAPIRouter()
|
||||
|
||||
@@ -658,6 +665,189 @@ def query_name(
|
||||
return _SchemaResponse(success=True, data={"name": new_name})
|
||||
|
||||
|
||||
def _build_preview_metainfo(
|
||||
title: str,
|
||||
subtitle: Optional[str],
|
||||
custom_words: Optional[str],
|
||||
media_source: Optional[MediaSource],
|
||||
) -> tuple[MetaBase, Optional[Path]]:
|
||||
"""
|
||||
按与标题识别接口一致的口径构建整理预览元数据及可选源路径。
|
||||
|
||||
:param title: 种子名、文件名或完整路径
|
||||
:param subtitle: 可选副标题
|
||||
:param custom_words: 可选临时识别词(按行分隔)
|
||||
:param media_source: 可选请求级识别数据源
|
||||
:return: 解析后的元数据对象及路径形式输入的源路径
|
||||
"""
|
||||
custom_word_list = custom_words.split("\n") if custom_words else None
|
||||
has_path_sep = ("/" in title or "\\" in title) and "://" not in title
|
||||
normalized_title = title.replace("\\", "/")
|
||||
title_path = Path(normalized_title)
|
||||
src_path = title_path if has_path_sep else None
|
||||
|
||||
config = get_api_runtime_config_snapshot()
|
||||
known_extensions = {
|
||||
ext.lower()
|
||||
for ext in (*config.media_extensions, *config.audio_extensions)
|
||||
}
|
||||
if has_path_sep and title_path.suffix.lower() in known_extensions:
|
||||
metainfo: MetaBase = MetaInfoPath(
|
||||
title_path,
|
||||
custom_words=custom_word_list,
|
||||
)
|
||||
metainfo.title = title
|
||||
else:
|
||||
metainfo = MetaInfo(title, subtitle, custom_words=custom_word_list)
|
||||
|
||||
if is_music_media_source(media_source) and not isinstance(metainfo, MetaMusic):
|
||||
metainfo = MetaMusic.parse_query(title)
|
||||
return metainfo, src_path
|
||||
|
||||
|
||||
def _resolve_preview_target_dir(
|
||||
new_path: str,
|
||||
media_type: Optional[MediaType],
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
从重命名相对路径中推导媒体目标根目录名称。
|
||||
|
||||
:param new_path: 按当前重命名模板生成的相对路径
|
||||
:param media_type: 已识别媒体类型
|
||||
:return: 目标根目录路径文本;无目录层级时返回 None
|
||||
"""
|
||||
rename_path = Path(new_path)
|
||||
if media_type is not None:
|
||||
media_path = DirectoryHelper.get_media_root_path(
|
||||
rename_format=get_api_runtime_config_snapshot().rename_format(media_type),
|
||||
rename_path=rename_path,
|
||||
media_type=media_type,
|
||||
)
|
||||
if media_path:
|
||||
normalized = media_path.as_posix()
|
||||
if normalized and normalized != ".":
|
||||
return normalized
|
||||
parents = rename_path.parents
|
||||
fallback = parents[1].name if len(parents) > 2 else (parents[0].name if parents else "")
|
||||
return fallback or None
|
||||
|
||||
|
||||
def _resolve_preview_library_path(
|
||||
dir_helper: DirectoryHelper,
|
||||
mediainfo: Union[MediaInfo, MusicInfo],
|
||||
src_path: Optional[Path],
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
根据当前整理目录配置解析命中的媒体库目标父目录。
|
||||
|
||||
:param dir_helper: 目录配置与分类路径助手
|
||||
:param mediainfo: 已识别的影视或音乐信息
|
||||
:param src_path: 输入为文件路径时的源路径;种子名场景为空
|
||||
:return: 包含类型和分类子目录的媒体库父目录文本;未配置匹配整理目录时返回 None
|
||||
"""
|
||||
matched_dir = dir_helper.get_dir(media=mediainfo, src_path=src_path)
|
||||
if not matched_dir or not matched_dir.library_path:
|
||||
return None
|
||||
return build_media_library_path(
|
||||
matched_dir,
|
||||
mediainfo,
|
||||
directory_helper=dir_helper,
|
||||
).as_posix()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/name/preview",
|
||||
summary="预览整理后的名称与目标目录",
|
||||
response_model=_SchemaResponse[_SchemaTransferNamePreviewData],
|
||||
)
|
||||
async def preview_name(
|
||||
title: str,
|
||||
subtitle: Optional[str] = None,
|
||||
custom_words: Optional[str] = None,
|
||||
media_source: Optional[MediaSource] = None,
|
||||
media_id: Optional[str] = None,
|
||||
mtype: Optional[MediaType] = None,
|
||||
music_type: Optional[str] = None,
|
||||
_: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> Any:
|
||||
"""
|
||||
按当前重命名模板和分类、目录配置预览识别结果整理后的目录与文件名。
|
||||
|
||||
支持与标题识别测试相同的副标题、临时识别词与数据源参数;传入已识别的
|
||||
``media_source`` 与 ``media_id`` 时直接复用对应媒体身份,保证与识别结果一致。
|
||||
|
||||
:param title: 种子名、发布标题、文件名或完整文件路径
|
||||
:param subtitle: 可选副标题
|
||||
:param custom_words: 可选临时识别词(每行一条规则),仅用于本次预览
|
||||
:param media_source: 可选请求级识别数据源
|
||||
:param media_id: 可选已识别的原生媒体 ID,须与 ``media_source`` 配套使用
|
||||
:param mtype: 可选已识别媒体类型
|
||||
:param music_type: 可选音乐实体类型
|
||||
:param _: Token 校验载荷
|
||||
:return: 包含分类路径、目标目录名、最终文件名及完整目标路径的预览响应
|
||||
"""
|
||||
metainfo, src_path = _build_preview_metainfo(
|
||||
title=title,
|
||||
subtitle=subtitle,
|
||||
custom_words=custom_words,
|
||||
media_source=media_source,
|
||||
)
|
||||
mediainfo = await MediaChain().async_recognize_by_meta(
|
||||
metainfo,
|
||||
media_source=media_source,
|
||||
mtype=mtype,
|
||||
music_type=music_type,
|
||||
media_id=media_id if media_source and media_id else None,
|
||||
)
|
||||
if not mediainfo:
|
||||
return _SchemaResponse(success=False, message="未识别到媒体信息")
|
||||
|
||||
dir_helper = DirectoryHelper()
|
||||
category_resolution = dir_helper.resolve_media_category(mediainfo)
|
||||
if category_resolution.state == "invalid_path":
|
||||
return _SchemaResponse(
|
||||
success=False,
|
||||
message=category_resolution.message or "媒体分类目录路径无效",
|
||||
)
|
||||
category_path = "/".join(category_resolution.path) or None
|
||||
|
||||
try:
|
||||
new_path = await asyncio.to_thread(
|
||||
TransferChain().recommend_name,
|
||||
meta=metainfo,
|
||||
mediainfo=mediainfo,
|
||||
)
|
||||
except Exception as err:
|
||||
logger.warning(f"预览整理名称失败:{err}")
|
||||
return _SchemaResponse(
|
||||
success=False,
|
||||
message=f"重命名模板渲染失败:{err}",
|
||||
)
|
||||
if not new_path:
|
||||
return _SchemaResponse(success=False, message="未识别到新名称")
|
||||
|
||||
normalized_rename_path = Path(new_path).as_posix()
|
||||
file_name = Path(normalized_rename_path).name or None
|
||||
target_dir = _resolve_preview_target_dir(normalized_rename_path, mediainfo.type)
|
||||
library_path = _resolve_preview_library_path(dir_helper, mediainfo, src_path)
|
||||
full_path = (
|
||||
(Path(library_path) / normalized_rename_path).as_posix()
|
||||
if library_path
|
||||
else None
|
||||
)
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data=_SchemaTransferNamePreviewData(
|
||||
category=category_path,
|
||||
target_dir=target_dir,
|
||||
file_name=file_name,
|
||||
rename_path=normalized_rename_path,
|
||||
library_path=library_path,
|
||||
full_path=full_path,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/queue", summary="查询整理队列", response_model=List[_SchemaTransferJob])
|
||||
async def query_queue(_: _SchemaTokenPayload = Depends(verify_token), page: CompatiblePageParam = None, count: CompatibleCountParam = None) -> Any:
|
||||
"""
|
||||
|
||||
@@ -76,6 +76,61 @@ def build_media_download_path(
|
||||
return append_classification_category_path(download_path, category_path)
|
||||
|
||||
|
||||
def build_media_library_path(
|
||||
directory: _SchemaTransferDirectoryConf,
|
||||
media: DirectoryMedia,
|
||||
*,
|
||||
need_type_folder: Optional[bool] = None,
|
||||
need_category_folder: Optional[bool] = None,
|
||||
directory_helper: Optional["DirectoryHelper"] = None,
|
||||
) -> Path:
|
||||
"""
|
||||
按媒体库目录开关、媒体类型和分类配置构造最终媒体库目标父目录。
|
||||
|
||||
仅拼接目录路径,不访问文件系统也不创建目录。
|
||||
|
||||
:param directory: 包含媒体库根路径和类型/分类开关的目录配置
|
||||
:param media: 用于确定类型目录和自动分类的媒体信息
|
||||
:param need_type_folder: 是否添加类型目录;None 时沿用目录配置
|
||||
:param need_category_folder: 是否添加分类目录;None 时沿用目录配置
|
||||
:param directory_helper: 可选目录助手实例;为空时使用默认实例
|
||||
:return: 拼接后的媒体库目标父目录路径
|
||||
:raises ValueError: 目录未配置媒体库根路径
|
||||
"""
|
||||
if not directory.library_path:
|
||||
raise ValueError("媒体库目录路径为空")
|
||||
if need_type_folder is None:
|
||||
need_type_folder = directory.library_type_folder
|
||||
if need_category_folder is None:
|
||||
need_category_folder = directory.library_category_folder
|
||||
if not directory.media_type and need_type_folder and media.type:
|
||||
library_dir = Path(directory.library_path) / media.type.value
|
||||
elif directory.media_type and need_type_folder:
|
||||
type_folder = (
|
||||
classification_media_type(directory.media_type)
|
||||
or directory.media_type
|
||||
)
|
||||
library_dir = Path(directory.library_path) / type_folder
|
||||
else:
|
||||
library_dir = Path(directory.library_path)
|
||||
if need_category_folder:
|
||||
helper = directory_helper or DirectoryHelper()
|
||||
category_path = helper.category_path_for_directory(directory, media)
|
||||
if category_path:
|
||||
category_path = category_path_below_media_type(
|
||||
category_path,
|
||||
directory.media_type or media.type,
|
||||
type_folder_enabled=bool(need_type_folder),
|
||||
)
|
||||
if category_path:
|
||||
# 固定 ID 使用当前策略路径,旧配置和人工覆盖使用安全路径快照。
|
||||
library_dir = append_classification_category_path(
|
||||
library_dir,
|
||||
category_path,
|
||||
)
|
||||
return library_dir
|
||||
|
||||
|
||||
class DiskTopology(Protocol):
|
||||
"""
|
||||
描述本地路径磁盘拓扑判断能力。
|
||||
|
||||
@@ -258,12 +258,20 @@ class FileManagerModule(_ModuleBase):
|
||||
"""
|
||||
handler = TransHandler()
|
||||
rename_format = get_runtime_setting('RENAME_FORMAT')(mediainfo.type)
|
||||
# 仅保留受支持的媒体/音频/字幕/歌词扩展名,避免把种子名中的点分标签误作文件后缀。
|
||||
raw_suffix = Path(meta.title or "").suffix
|
||||
supported_exts = {
|
||||
ext.lower()
|
||||
for key in ("RMT_MEDIAEXT", "RMT_AUDIOEXT", "RMT_SUBEXT", "RMT_LYRICSEXT")
|
||||
for ext in (get_runtime_setting(key) or ())
|
||||
}
|
||||
file_ext = raw_suffix if raw_suffix and raw_suffix.lower() in supported_exts else ""
|
||||
path = handler.get_rename_path(
|
||||
template_string=rename_format,
|
||||
rename_dict=handler.get_naming_dict(meta=meta,
|
||||
mediainfo=mediainfo,
|
||||
episodes_info=episodes_info,
|
||||
file_ext=Path(meta.title or "").suffix)
|
||||
file_ext=file_ext)
|
||||
)
|
||||
return path.as_posix() if path else ""
|
||||
|
||||
|
||||
@@ -17,10 +17,9 @@ from app.application.audio import AudioMetadataHelper
|
||||
from app.application.classification.reference import (
|
||||
append_classification_category_path,
|
||||
category_path_below_media_type,
|
||||
classification_media_type,
|
||||
ensure_path_within_root,
|
||||
)
|
||||
from app.application.directory import DirectoryHelper
|
||||
from app.application.directory import DirectoryHelper, build_media_library_path
|
||||
from app.application.messaging.message import TemplateHelper
|
||||
from app.application.transfer.execution import (
|
||||
TransferExecutionConflictError,
|
||||
@@ -2806,42 +2805,12 @@ class TransHandler:
|
||||
:param need_category_folder: 是否添加分类目录;None 时沿用目录设置
|
||||
:return: 最终媒体库目录路径;不创建目录
|
||||
"""
|
||||
if not target_dir.library_path:
|
||||
raise ValueError("媒体库目录路径为空")
|
||||
if need_type_folder is None:
|
||||
need_type_folder = target_dir.library_type_folder
|
||||
if need_category_folder is None:
|
||||
need_category_folder = target_dir.library_category_folder
|
||||
if not target_dir.media_type and need_type_folder and mediainfo.type:
|
||||
library_dir = Path(target_dir.library_path) / mediainfo.type.value
|
||||
elif target_dir.media_type and need_type_folder:
|
||||
type_folder = (
|
||||
classification_media_type(target_dir.media_type)
|
||||
or target_dir.media_type
|
||||
)
|
||||
library_dir = Path(target_dir.library_path) / type_folder
|
||||
else:
|
||||
library_dir = Path(target_dir.library_path)
|
||||
if need_category_folder:
|
||||
helper = DirectoryHelper()
|
||||
category_path = helper.category_path_for_directory(
|
||||
target_dir,
|
||||
mediainfo,
|
||||
)
|
||||
if category_path:
|
||||
category_path = category_path_below_media_type(
|
||||
category_path,
|
||||
target_dir.media_type or mediainfo.type,
|
||||
type_folder_enabled=bool(need_type_folder),
|
||||
)
|
||||
if category_path:
|
||||
# 固定 ID 使用当前策略路径,旧配置和人工覆盖使用安全路径快照。
|
||||
library_dir = append_classification_category_path(
|
||||
library_dir,
|
||||
category_path,
|
||||
)
|
||||
|
||||
return library_dir
|
||||
return build_media_library_path(
|
||||
target_dir,
|
||||
mediainfo,
|
||||
need_type_folder=need_type_folder,
|
||||
need_category_folder=need_category_folder,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_naming_dict(
|
||||
|
||||
@@ -650,3 +650,34 @@ class EpisodeFormatRecommendData(BaseModel):
|
||||
reason: Optional[str] = Field(default=None, description="推荐或无法推荐剧集格式的主要原因")
|
||||
reasons: list[str] = Field(default_factory=list, description="剧集格式推荐的依据")
|
||||
message: Optional[str] = Field(default=None, description="面向调用方的结果说明")
|
||||
|
||||
|
||||
class TransferNamePreviewData(BaseModel):
|
||||
"""
|
||||
识别测试场景下的整理名称与目标目录预览结果。
|
||||
"""
|
||||
|
||||
category: Optional[str] = Field(
|
||||
default=None,
|
||||
description="命中的二级分类路径;未命中分类策略或未启用分类时为空",
|
||||
)
|
||||
target_dir: Optional[str] = Field(
|
||||
default=None,
|
||||
description="按当前重命名模板生成的媒体目标根目录名称;无目录层级时为空",
|
||||
)
|
||||
file_name: Optional[str] = Field(
|
||||
default=None,
|
||||
description="按当前重命名模板生成的最终文件名",
|
||||
)
|
||||
rename_path: Optional[str] = Field(
|
||||
default=None,
|
||||
description="按当前重命名模板生成的完整相对路径(包含季目录等中间层级)",
|
||||
)
|
||||
library_path: Optional[str] = Field(
|
||||
default=None,
|
||||
description="命中的媒体库目标父目录(含类型目录与分类目录);未匹配到已配置整理目录时为空",
|
||||
)
|
||||
full_path: Optional[str] = Field(
|
||||
default=None,
|
||||
description="结合匹配媒体库目录与重命名模板后的完整目标路径;未匹配到已配置整理目录时为空",
|
||||
)
|
||||
|
||||
@@ -978,8 +978,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10587,
|
||||
"edge_sha256": "56f720b09f77ac3ec847c28871320e07ed095adf11df0da815864aa4a2872901",
|
||||
"edge_count": 10594,
|
||||
"edge_sha256": "b2ea0244a1a2d0a0e8aeb1aee7a143d5cb54f4ea0e234e49a4fb431acab4a807",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -3507,6 +3507,13 @@
|
||||
"app.api.endpoints.transfer -> app.chain.media",
|
||||
"app.api.endpoints.transfer -> app.chain.transfer",
|
||||
"app.api.endpoints.transfer -> app.chain.transfer.facade",
|
||||
"app.api.endpoints.transfer -> app.domain",
|
||||
"app.api.endpoints.transfer -> app.domain.context",
|
||||
"app.api.endpoints.transfer -> app.domain.media",
|
||||
"app.api.endpoints.transfer -> app.domain.meta",
|
||||
"app.api.endpoints.transfer -> app.domain.meta.metabase",
|
||||
"app.api.endpoints.transfer -> app.domain.meta.metamusic",
|
||||
"app.api.endpoints.transfer -> app.domain.metainfo",
|
||||
"app.api.endpoints.transfer -> app.runtime",
|
||||
"app.api.endpoints.transfer -> app.runtime.errors",
|
||||
"app.api.endpoints.transfer -> app.runtime.log",
|
||||
|
||||
444
tests/test_transfer_name_preview.py
Normal file
444
tests/test_transfer_name_preview.py
Normal file
@@ -0,0 +1,444 @@
|
||||
"""
|
||||
整理名称与目标目录预览接口及推荐名称扩展名过滤回归测试。
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.endpoints import transfer as transfer_endpoint
|
||||
from app.application.classification.reference import ClassificationCategoryResolution
|
||||
from app.application.directory import DirectoryHelper, build_media_library_path
|
||||
from app.domain.context import MediaInfo, MusicInfo
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.modules.filemanager.module import FileManagerModule
|
||||
from app.modules.filemanager.transhandler import TransHandler
|
||||
from app.schemas.system import TransferDirectoryConf
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
|
||||
def _mock_runtime_config(
|
||||
*,
|
||||
movie_format: str = "{{title}}{% if year %} ({{year}}){% endif %}{% if tmdbid %} {tmdbid={{tmdbid}}}{% endif %}/{{title}}{% if year %} ({{year}}){% endif %}{% if videoFormat %} - {{videoFormat}}{% endif %}{{fileExt}}",
|
||||
tv_format: str = "{{title}}{% if year %} ({{year}}){% endif %}/Season {{season}}/{{title}} - {{season_episode}}{{fileExt}}",
|
||||
music_format: str = "{{album_artist or artist}}/{{album}}/{{title}}{{fileExt}}",
|
||||
) -> SimpleNamespace:
|
||||
"""
|
||||
构造整理预览使用的轻量运行时配置快照。
|
||||
|
||||
:param movie_format: 电影重命名模板
|
||||
:param tv_format: 电视剧重命名模板
|
||||
:param music_format: 音乐重命名模板
|
||||
:return: 包含扩展名列表和模板解析方法的模拟配置对象
|
||||
"""
|
||||
|
||||
def _rename_format(media_type: MediaType) -> str:
|
||||
"""
|
||||
按媒体类型返回对应的重命名模板。
|
||||
"""
|
||||
if media_type == MediaType.TV:
|
||||
return tv_format
|
||||
if media_type == MediaType.MUSIC:
|
||||
return music_format
|
||||
return movie_format
|
||||
|
||||
return SimpleNamespace(
|
||||
media_extensions=(".mkv", ".mp4", ".avi"),
|
||||
audio_extensions=(".flac", ".mp3"),
|
||||
subtitle_extensions=(".srt", ".ass"),
|
||||
lyrics_extensions=(".lrc",),
|
||||
rename_format=_rename_format,
|
||||
)
|
||||
|
||||
|
||||
def test_recommend_name_ignores_non_media_suffix_from_torrent_title(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
不带媒体文件后缀的种子名不应把点分发布标签误拼成文件扩展名。
|
||||
"""
|
||||
settings_map: dict[str, Any] = {
|
||||
"RENAME_FORMAT": lambda _media_type: "{{title}} ({{year}})/{{title}} ({{year}}){{fileExt}}",
|
||||
"RMT_MEDIAEXT": [".mkv", ".mp4"],
|
||||
"RMT_AUDIOEXT": [".flac"],
|
||||
"RMT_SUBEXT": [".srt"],
|
||||
"RMT_LYRICSEXT": [".lrc"],
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
"app.modules.filemanager.module.get_runtime_setting",
|
||||
lambda key: settings_map[key],
|
||||
)
|
||||
captured_exts: list[Optional[str]] = []
|
||||
|
||||
def _fake_naming_dict(
|
||||
*,
|
||||
meta: Any,
|
||||
mediainfo: Any,
|
||||
episodes_info: Any = None,
|
||||
file_ext: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
记录传入命名上下文的文件扩展名并返回最小模板变量。
|
||||
"""
|
||||
_ = (meta, episodes_info)
|
||||
captured_exts.append(file_ext)
|
||||
return {
|
||||
"title": mediainfo.title,
|
||||
"year": mediainfo.year,
|
||||
"fileExt": file_ext or "",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(TransHandler, "get_naming_dict", staticmethod(_fake_naming_dict))
|
||||
monkeypatch.setattr(
|
||||
TransHandler,
|
||||
"get_rename_path",
|
||||
staticmethod(
|
||||
lambda template_string, rename_dict, **_kwargs: Path(
|
||||
f"{rename_dict['title']} ({rename_dict['year']})/"
|
||||
f"{rename_dict['title']} ({rename_dict['year']}){rename_dict['fileExt']}"
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
mediainfo = MediaInfo()
|
||||
mediainfo.type = MediaType.MOVIE
|
||||
mediainfo.title = "海上钢琴师"
|
||||
mediainfo.year = "1998"
|
||||
|
||||
torrent_meta = MetaInfo("The.Legend.of.1900.1998.1080p.BluRay.x264-GROUP")
|
||||
torrent_result = FileManagerModule.recommend_name(torrent_meta, mediainfo)
|
||||
assert captured_exts[-1] == ""
|
||||
assert torrent_result == "海上钢琴师 (1998)/海上钢琴师 (1998)"
|
||||
|
||||
file_meta = MetaInfo("The.Legend.of.1900.1998.1080p.BluRay.mkv")
|
||||
file_result = FileManagerModule.recommend_name(file_meta, mediainfo)
|
||||
assert captured_exts[-1] == ".mkv"
|
||||
assert file_result == "海上钢琴师 (1998)/海上钢琴师 (1998).mkv"
|
||||
|
||||
|
||||
def test_build_media_library_path_matches_transhandler_dest_dir(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
共享媒体库路径构造函数应正确拼接类型与二级分类目录,并与整理处理器保持一致。
|
||||
"""
|
||||
mediainfo = MediaInfo()
|
||||
mediainfo.type = MediaType.MOVIE
|
||||
mediainfo.title = "海上钢琴师"
|
||||
mediainfo.set_library_category("外语电影")
|
||||
|
||||
directory = TransferDirectoryConf(
|
||||
name="电影库",
|
||||
library_path="/media",
|
||||
library_type_folder=True,
|
||||
library_category_folder=True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DirectoryHelper,
|
||||
"category_path_for_directory",
|
||||
lambda self, _dir, _media: ("外语电影",),
|
||||
)
|
||||
|
||||
expected = Path("/media/电影/外语电影")
|
||||
assert build_media_library_path(directory, mediainfo) == expected
|
||||
assert TransHandler.get_dest_dir(mediainfo, directory) == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preview_name_returns_category_dir_file_and_library_path(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
预览接口应返回命中的分类路径、目标目录名、最终文件名以及完整目标路径。
|
||||
"""
|
||||
mediainfo = MediaInfo()
|
||||
mediainfo.type = MediaType.MOVIE
|
||||
mediainfo.title = "海上钢琴师"
|
||||
mediainfo.year = "1998"
|
||||
mediainfo.tmdb_id = 10376
|
||||
mediainfo.set_library_category("外语电影")
|
||||
|
||||
captured_recognize: dict[str, Any] = {}
|
||||
|
||||
async def _fake_recognize_by_meta(
|
||||
self: Any,
|
||||
metainfo: Any,
|
||||
*,
|
||||
media_source: Any = None,
|
||||
mtype: Any = None,
|
||||
music_type: Any = None,
|
||||
media_id: Any = None,
|
||||
) -> MediaInfo:
|
||||
"""
|
||||
捕获识别调用参数并返回固定电影信息。
|
||||
"""
|
||||
_ = self
|
||||
captured_recognize.update(
|
||||
{
|
||||
"metainfo": metainfo,
|
||||
"media_source": media_source,
|
||||
"mtype": mtype,
|
||||
"music_type": music_type,
|
||||
"media_id": media_id,
|
||||
}
|
||||
)
|
||||
return mediainfo
|
||||
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint,
|
||||
"get_api_runtime_config_snapshot",
|
||||
_mock_runtime_config,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.MediaChain,
|
||||
"async_recognize_by_meta",
|
||||
_fake_recognize_by_meta,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.TransferChain,
|
||||
"recommend_name",
|
||||
lambda self, meta, mediainfo: "海上钢琴师 (1998) {tmdbid=10376}/海上钢琴师 (1998) - 1080p.mkv",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DirectoryHelper,
|
||||
"resolve_media_category",
|
||||
lambda self, media: ClassificationCategoryResolution(
|
||||
state="resolved",
|
||||
category_id=None,
|
||||
path=("外语电影",),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DirectoryHelper,
|
||||
"category_path_for_directory",
|
||||
lambda self, directory, media: ("外语电影",),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DirectoryHelper,
|
||||
"get_dir",
|
||||
lambda self, media=None, src_path=None: TransferDirectoryConf(
|
||||
name="电影库",
|
||||
library_path="/media",
|
||||
library_type_folder=True,
|
||||
library_category_folder=True,
|
||||
),
|
||||
)
|
||||
|
||||
response = await transfer_endpoint.preview_name(
|
||||
title="/downloads/The.Legend.of.1900.1998.1080p.mkv",
|
||||
subtitle="海上钢琴师",
|
||||
custom_words="屏蔽词",
|
||||
media_source=MediaSource.TMDB,
|
||||
media_id="10376",
|
||||
mtype=MediaType.MOVIE,
|
||||
)
|
||||
|
||||
assert response.success is True
|
||||
assert captured_recognize["media_source"] == MediaSource.TMDB
|
||||
assert captured_recognize["media_id"] == "10376"
|
||||
assert captured_recognize["mtype"] == MediaType.MOVIE
|
||||
assert response.data is not None
|
||||
assert response.data.category == "外语电影"
|
||||
assert response.data.target_dir == "海上钢琴师 (1998) {tmdbid=10376}"
|
||||
assert response.data.file_name == "海上钢琴师 (1998) - 1080p.mkv"
|
||||
assert response.data.rename_path == "海上钢琴师 (1998) {tmdbid=10376}/海上钢琴师 (1998) - 1080p.mkv"
|
||||
assert response.data.library_path == "/media/电影/外语电影"
|
||||
assert (
|
||||
response.data.full_path
|
||||
== "/media/电影/外语电影/海上钢琴师 (1998) {tmdbid=10376}/海上钢琴师 (1998) - 1080p.mkv"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preview_name_handles_tv_season_and_no_configured_directory(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
电视剧预览应保留季目录层级;未配置匹配整理目录时允许媒体库路径为空。
|
||||
"""
|
||||
mediainfo = MediaInfo()
|
||||
mediainfo.type = MediaType.TV
|
||||
mediainfo.title = "测试剧集"
|
||||
mediainfo.year = "2026"
|
||||
|
||||
async def _fake_recognize_by_meta(self: Any, metainfo: Any, **_kwargs: Any) -> MediaInfo:
|
||||
"""
|
||||
返回测试电视剧信息。
|
||||
"""
|
||||
_ = (self, metainfo)
|
||||
return mediainfo
|
||||
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint,
|
||||
"get_api_runtime_config_snapshot",
|
||||
_mock_runtime_config,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.MediaChain,
|
||||
"async_recognize_by_meta",
|
||||
_fake_recognize_by_meta,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.TransferChain,
|
||||
"recommend_name",
|
||||
lambda self, meta, mediainfo: "测试剧集 (2026)/Season 1/测试剧集 - S01E01",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DirectoryHelper,
|
||||
"resolve_media_category",
|
||||
lambda self, media: ClassificationCategoryResolution(
|
||||
state="resolved",
|
||||
category_id=None,
|
||||
path=("动漫", "日漫"),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(DirectoryHelper, "get_dir", lambda self, media=None, src_path=None: None)
|
||||
|
||||
response = await transfer_endpoint.preview_name(title="Test.Show.S01E01.1080p")
|
||||
|
||||
assert response.success is True
|
||||
assert response.data is not None
|
||||
assert response.data.category == "动漫/日漫"
|
||||
assert response.data.target_dir == "测试剧集 (2026)"
|
||||
assert response.data.file_name == "测试剧集 - S01E01"
|
||||
assert response.data.rename_path == "测试剧集 (2026)/Season 1/测试剧集 - S01E01"
|
||||
assert response.data.library_path is None
|
||||
assert response.data.full_path is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preview_name_handles_music_disc_directory(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
音乐预览遇到碟片子目录时,目标目录应回溯到专辑目录并保留完整相对路径。
|
||||
"""
|
||||
music_info = MusicInfo(
|
||||
title="晴天",
|
||||
artists=["周杰伦"],
|
||||
album="叶惠美",
|
||||
media_source=MediaSource.MusicBrainz,
|
||||
media_id="8f97b17d-1234-4abc-9def-1234567890ab",
|
||||
)
|
||||
|
||||
async def _fake_recognize_by_meta(self: Any, metainfo: Any, **_kwargs: Any) -> MusicInfo:
|
||||
"""
|
||||
返回测试音乐信息。
|
||||
"""
|
||||
_ = (self, metainfo)
|
||||
return music_info
|
||||
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint,
|
||||
"get_api_runtime_config_snapshot",
|
||||
_mock_runtime_config,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.MediaChain,
|
||||
"async_recognize_by_meta",
|
||||
_fake_recognize_by_meta,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.TransferChain,
|
||||
"recommend_name",
|
||||
lambda self, meta, mediainfo: "周杰伦/叶惠美/Disc 1/01 - 晴天.flac",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DirectoryHelper,
|
||||
"resolve_media_category",
|
||||
lambda self, media: ClassificationCategoryResolution(
|
||||
state="empty",
|
||||
category_id=None,
|
||||
path=(),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(DirectoryHelper, "get_dir", lambda self, media=None, src_path=None: None)
|
||||
|
||||
response = await transfer_endpoint.preview_name(
|
||||
title="周杰伦 - 晴天.flac",
|
||||
media_source=MediaSource.MusicBrainz,
|
||||
media_id="8f97b17d-1234-4abc-9def-1234567890ab",
|
||||
)
|
||||
|
||||
assert response.success is True
|
||||
assert response.data is not None
|
||||
assert response.data.category is None
|
||||
assert response.data.target_dir == "周杰伦/叶惠美"
|
||||
assert response.data.file_name == "01 - 晴天.flac"
|
||||
assert response.data.rename_path == "周杰伦/叶惠美/Disc 1/01 - 晴天.flac"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preview_name_reports_unrecognized_and_template_errors(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
未识别媒体或模板渲染失败时应返回结构化失败响应,而非抛出未处理异常。
|
||||
"""
|
||||
|
||||
async def _fake_unrecognized(self: Any, metainfo: Any, **_kwargs: Any) -> None:
|
||||
"""
|
||||
模拟识别失败返回空媒体信息。
|
||||
"""
|
||||
_ = (self, metainfo)
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint,
|
||||
"get_api_runtime_config_snapshot",
|
||||
_mock_runtime_config,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.MediaChain,
|
||||
"async_recognize_by_meta",
|
||||
_fake_unrecognized,
|
||||
)
|
||||
|
||||
unrecognized_response = await transfer_endpoint.preview_name(title="Unknown.Release")
|
||||
assert unrecognized_response.success is False
|
||||
assert "未识别到媒体信息" in (unrecognized_response.message or "")
|
||||
|
||||
mediainfo = MediaInfo()
|
||||
mediainfo.type = MediaType.MOVIE
|
||||
mediainfo.title = "海上钢琴师"
|
||||
|
||||
async def _fake_recognized(self: Any, metainfo: Any, **_kwargs: Any) -> MediaInfo:
|
||||
"""
|
||||
模拟识别成功以验证模板渲染失败路径。
|
||||
"""
|
||||
_ = (self, metainfo)
|
||||
return mediainfo
|
||||
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.MediaChain,
|
||||
"async_recognize_by_meta",
|
||||
_fake_recognized,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DirectoryHelper,
|
||||
"resolve_media_category",
|
||||
lambda self, media: ClassificationCategoryResolution(
|
||||
state="empty",
|
||||
category_id=None,
|
||||
path=(),
|
||||
),
|
||||
)
|
||||
|
||||
def _raise_template_error(self: Any, meta: Any, mediainfo: Any) -> str:
|
||||
"""
|
||||
模拟 Jinja2 模板语法错误。
|
||||
"""
|
||||
_ = (self, meta, mediainfo)
|
||||
raise ValueError("模板语法错误")
|
||||
|
||||
monkeypatch.setattr(
|
||||
transfer_endpoint.TransferChain,
|
||||
"recommend_name",
|
||||
_raise_template_error,
|
||||
)
|
||||
|
||||
error_response = await transfer_endpoint.preview_name(title="海上钢琴师.1998.mkv")
|
||||
assert error_response.success is False
|
||||
assert "重命名模板渲染失败" in (error_response.message or "")
|
||||
Reference in New Issue
Block a user