refactor(music)!: remove Musixmatch and expose lyrics plugin types

BREAKING CHANGE: remove the Musixmatch module and settings without migration. Lyrics providers can use the public music candidate SDK and existing plugin module hook.
This commit is contained in:
jxxghp
2026-09-09 23:04:20 +08:00
parent 1899f63c75
commit 17eaf47c34
17 changed files with 273 additions and 278 deletions

View File

@@ -1,164 +0,0 @@
import time
from typing import Any, Optional, Tuple, Union
from app.adapters.network.http import RequestUtils
from app.domain.context import MusicInfo, MusicLyrics
from app.domain.meta.metamusic import MetaMusic
from app.modules import _ModuleBase
from app.runtime.log import logger
from app.runtime.settings import get_runtime_setting
from app.schemas.types import ModuleType, OtherModulesType
class MusixmatchModule(_ModuleBase):
"""使用用户授权的 Musixmatch 官方 API 获取同步或纯文本歌词。"""
_source = "musixmatch"
_cooldown_until = 0.0
def init_module(self) -> None:
"""初始化无持久状态的授权歌词模块。"""
def init_setting(self) -> Tuple[str, Union[str, bool]]:
"""仅在配置官方 API Key 后启用模块。"""
return "MUSIXMATCH_API_KEY", True
def stop(self) -> None:
"""停止模块;当前没有需要释放的资源。"""
def test(self) -> Tuple[bool, str]:
"""验证 API Key 和官方接口连通性。"""
if not str(get_runtime_setting('MUSIXMATCH_API_KEY') or "").strip():
return False, "Musixmatch API Key 未配置"
payload = self._request("matcher.lyrics.get", {"q_track": "test", "q_artist": "test"})
return (True, "") if payload is not None else (False, "Musixmatch API 连接或授权失败")
@staticmethod
def get_name() -> str:
"""返回模块展示名称。"""
return "Musixmatch"
@staticmethod
def get_type() -> ModuleType:
"""返回模块所属类型。"""
return ModuleType.Other
@staticmethod
def get_subtype() -> OtherModulesType:
"""返回 Musixmatch 模块子类型。"""
return OtherModulesType.Musixmatch
@staticmethod
def get_priority() -> int:
"""授权同步歌词优先于免费来源参与候选评分。"""
return 4
def music_lyrics_candidates(
self,
music: Union[MetaMusic, MusicInfo],
) -> list[MusicLyrics]:
"""按标题、艺术家和时长调用官方 matcher 接口。"""
title = str(getattr(music, "title", None) or "").strip()
artists = list(getattr(music, "artists", None) or [])
artist = str((artists[0] if artists else getattr(music, "album_artist", None)) or "").strip()
if not title or not artist:
return []
params: dict[str, Any] = {"q_track": title, "q_artist": artist}
duration = self._optional_int(getattr(music, "duration", None))
if duration:
params.update({
"f_subtitle_length": duration,
"f_subtitle_length_max_deviation": 2,
})
subtitle = self._response_item(self._request("matcher.subtitle.get", params), "subtitle")
if subtitle and not subtitle.get("restricted"):
body = str(subtitle.get("subtitle_body") or "").strip()
if body:
return [MusicLyrics(
provider=self._source,
provider_id=self._optional_text(subtitle.get("subtitle_id")),
synced_lyrics=body,
language=self._optional_text(subtitle.get("subtitle_language")),
match_score=95,
provider_priority=30,
)]
lyrics = self._response_item(
self._request("matcher.lyrics.get", {"q_track": title, "q_artist": artist}),
"lyrics",
)
if not lyrics or lyrics.get("restricted"):
return []
body = str(lyrics.get("lyrics_body") or "").strip()
instrumental = bool(lyrics.get("instrumental"))
if not body and not instrumental:
return []
return [MusicLyrics(
provider=self._source,
provider_id=self._optional_text(lyrics.get("lyrics_id")),
instrumental=instrumental,
plain_lyrics=body or None,
language=self._optional_text(lyrics.get("lyrics_language")),
match_score=92,
provider_priority=30,
)]
def _request(self, method: str, params: dict[str, Any]) -> Optional[dict[str, Any]]:
"""请求官方 API,并对限流或服务过载设置进程内冷却。"""
api_key = str(get_runtime_setting('MUSIXMATCH_API_KEY') or "").strip()
if not api_key or time.monotonic() < self._cooldown_until:
return None
response = RequestUtils(
ua=get_runtime_setting('USER_AGENT'),
proxies=get_runtime_setting('PROXY'),
timeout=20,
).get_res(
f"{str(get_runtime_setting('MUSIXMATCH_BASE_URL')).rstrip('/')}/{method}",
params={**params, "apikey": api_key},
)
if response is None:
return None
try:
if response.status_code in (429, 503):
retry_after = self._optional_int(response.headers.get("Retry-After")) or 60
type(self)._cooldown_until = time.monotonic() + retry_after
logger.warning(f"Musixmatch 进入冷却 {retry_after} 秒")
return None
if response.status_code != 200:
logger.warning(f"Musixmatch 请求失败:HTTP {response.status_code}")
return None
payload = response.json()
status = self._optional_int(
((payload.get("message") or {}).get("header") or {}).get("status_code")
) if isinstance(payload, dict) else None
if status != 200:
if status in (401, 402, 429):
logger.warning(f"Musixmatch API 拒绝请求:状态码 {status}")
return None
return payload
except (TypeError, ValueError) as err:
logger.warning(f"Musixmatch 响应解析失败:{err}")
return None
finally:
response.close()
@staticmethod
def _response_item(payload: Any, name: str) -> Optional[dict[str, Any]]:
"""从官方 message/body 包装中提取歌词或字幕对象。"""
if not isinstance(payload, dict):
return None
item = (((payload.get("message") or {}).get("body") or {}).get(name))
return item if isinstance(item, dict) else None
@staticmethod
def _optional_int(value: Any) -> Optional[int]:
"""安全转换整数响应字段。"""
try:
return int(float(value)) if value not in (None, "") else None
except (TypeError, ValueError):
return None
@staticmethod
def _optional_text(value: Any) -> Optional[str]:
"""安全转换非空文本字段。"""
text = str(value or "").strip()
return text or None

View File

@@ -1,19 +0,0 @@
schema_version = 1
id = "MusixmatchModule"
kind = "host_module"
entrypoint = "app.modules.musixmatch:MusixmatchModule"
depends_on = []
[metadata]
name = "Musixmatch"
type = "other"
subtype = "Musixmatch"
priority = 4
[activation]
policy = "when_configured"
watch = ["MUSIXMATCH_API_KEY", "MUSIXMATCH_BASE_URL"]
[activation.selector]
kind = "setting_truthy"
key = "MUSIXMATCH_API_KEY"

View File

@@ -404,10 +404,6 @@ class ConfigModel(BaseModel):
THEAUDIODB_API_KEY: str = "123"
# LRCLIB 服务地址,可指向兼容官方 API 的自建实例
LRCLIB_BASE_URL: str = "https://lrclib.net"
# Musixmatch 官方 API Key;留空时不加载该歌词来源
MUSIXMATCH_API_KEY: str = ""
# Musixmatch 官方或授权代理 API 根地址
MUSIXMATCH_BASE_URL: str = "https://api.musixmatch.com/ws/1.1"
# 单次音乐刮削批次用于在线歌词查询的总预算(秒)
LYRICS_BATCH_TIMEOUT: int = 120
# 供应商要求的重试等待超过该值时进入冷却,不阻塞整个批次

View File

@@ -69,7 +69,6 @@ BASELINE_ASSESSED_MODULES = frozenset(
"lrclib",
"mediavault",
"musicbrainz",
"musixmatch",
"navidrome",
"plex",
"postgresql",

View File

@@ -643,8 +643,9 @@ class ModuleType(Enum):
Other = "other"
# 其他杂项模块类型
class OtherModulesType(Enum):
"""标识字幕、歌词等不属于专用服务分类的模块。"""
# 字幕
Subtitle = "站点字幕"
# Fanart
@@ -663,8 +664,6 @@ class OtherModulesType(Enum):
ListenBrainz = "ListenBrainz"
# LRCLIB 歌词
Lrclib = "LRCLIB"
# Musixmatch 授权歌词
Musixmatch = "Musixmatch"
# AcoustID 音频指纹
AcoustId = "AcoustID"

View File

@@ -1,6 +1,6 @@
"""插件使用的媒体上下文、标题解析、识别类型和媒体身份规则。"""
"""插件使用的媒体上下文、歌词候选、标题解析、识别类型和媒体身份规则。"""
from app.domain.context import Context, MediaInfo, TorrentInfo
from app.domain.context import Context, MediaInfo, MusicInfo, MusicLyrics, TorrentInfo
from app.domain.meta.customization import set_custom_separator
from app.domain.meta.metaanime import MetaAnime
from app.domain.meta.metabase import MetaBase
@@ -52,6 +52,8 @@ __all__ = [
"MetaInfoPath",
"MetaMusic",
"MetaVideo",
"MusicInfo",
"MusicLyrics",
"NfoReader",
"Tokens",
"MusicNameContext",

View File

@@ -756,8 +756,8 @@ flowchart LR
| 指标 | 当前值 |
|---|---:|
| Python 模块 | 995 |
| 内部导入边 | 8,458 |
| Python 模块 | 994 |
| 内部导入边 | 8,445 |
| 非平凡 SCC | 1(精确 containment 的 TMDB 移植包环) |
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
| Direct egress | 53(债务已清零,53 条精确 containment) |

View File

@@ -94,7 +94,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁
| 指标 | 当前值 | 解释 |
|---|---:|---|
| 宿主 Python 模块 / 内部依赖边 | 995 / 8,458 | `dependency-baseline.json` 当前快照;分类、下载资源归类、订阅搜索、整理恢复与 Agent 计划模块的受控依赖 |
| 宿主 Python 模块 / 内部依赖边 | 994 / 8,445 | `dependency-baseline.json` 当前快照;分类、下载资源归类、订阅搜索、整理恢复与 Agent 计划模块的受控依赖 |
| 非平凡 SCC | 1 | 仅保留精确 containment 的 29 模块 TMDB 移植包环 |
| 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 |
| Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 |
@@ -102,7 +102,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁
| Event Contract | 53 | 均已有 payload model,但当前全部是 diagnostic enforcement |
| Python 源码量 | 305,884 行 | 排除 `app/plugins/**`;61 个文件超过 1,000 行,11 个超过 2,000 行 |
| 长方法 | 290 个超过 80 行 | AST 统计排除 `app/plugins/**`;65 个超过 150 行,21 个超过 250 行 |
| 全量 mypy 历史债务 | 9,409 / 511 文件 | Agent API 重构后的现状基线;canonical Facade 与 endpoint 类型边界已补齐,低水位只允许继续下降 |
| 全量 mypy 历史债务 | 9,408 / 510 文件 | Agent API 重构后的现状基线;canonical Facade 与 endpoint 类型边界已补齐,低水位只允许继续下降 |
| Ruff 历史诊断 | 534 | 低水位门禁通过,但规则集只覆盖 `E4/E7/E9/F/I` |
| 覆盖率固定基线 | Application 80.00%,Domain 80.00% | Chain、Runtime、Agent、Adapter、Startup 未进入包级覆盖率门禁 |

View File

@@ -466,7 +466,6 @@ moviepilot config set ACOUSTID_API_KEY your-acoustid-client-key
moviepilot config set LRCLIB_BASE_URL https://lrclib.net
moviepilot config set LYRICS_BATCH_TIMEOUT 120
moviepilot config set LYRICS_PROVIDER_RETRY_MAX_WAIT 5
moviepilot config set MUSIXMATCH_API_KEY your-authorized-api-key
moviepilot config set MUSIC_METADATA_TO_SIMPLIFIED true
moviepilot config set MUSIC_RELEASE_REGION_PRIORITY CN,TW,HK
moviepilot config set MUSIC_RELEASE_SCRIPT_PRIORITY Hans,Hant,Latn
@@ -489,7 +488,7 @@ moviepilot config describe API_TOKEN --show-secrets
- `config keys` 显示配置项名称、类型和默认值
- `ACOUSTID_API_KEY` 内置可用默认值,也可在前端“高级设置 - 媒体”或配置命令中覆盖;本地安装需要系统可执行路径中存在 Chromaprint `fpcalc`,官方 Docker 镜像已内置
- `LRCLIB_BASE_URL` 默认使用官方实例,也可指向兼容 LRCLIB API 的自建实例;`LYRICS_BATCH_TIMEOUT` 限制单次专辑刮削的在线歌词总预算,`LYRICS_PROVIDER_RETRY_MAX_WAIT` 决定长 `Retry-After` 进入来源冷却而非阻塞批次
- `THEAUDIODB_API_KEY` 用于音乐元数据及纯文本歌词兜底,默认 `123` 为官方公开 V1 Key;`MUSIXMATCH_API_KEY` 留空时不加载 Musixmatch,配置后只调用官方或 `MUSIXMATCH_BASE_URL` 指定的授权代理,使用者必须遵守对应账户的歌词存储和展示授权
- `THEAUDIODB_API_KEY` 用于音乐元数据及纯文本歌词兜底,默认 `123` 为官方公开 V1 Key;额外歌词来源可通过插件提供,接入方式见[歌词插件开发说明](https://github.com/jxxghp/MoviePilot-Plugins/blob/main/docs/faq/21-register-lyrics-provider.md)
- `MUSIC_METADATA_TO_SIMPLIFIED` 默认开启;开启后会将识别结果中的曲名、艺术家、专辑和分类等标准音乐元数据转换为简体中文,不转换歌词与来源原始响应
- `MUSIC_RELEASE_REGION_PRIORITY` 与 `MUSIC_RELEASE_SCRIPT_PRIORITY` 分别使用逗号分隔的 ISO 3166-1 地区代码和 ISO 15924 文字代码;仅在 MusicBrainz 候选结构同样可信时作为发行版本排序依据,最多使用前三项
- `config describe` 显示单个配置项的类型、默认值和当前值

View File

@@ -377,7 +377,9 @@ SSE 的 `candidate_items` 是站点原始返回数量,`match_counts` 记录身
| GET | `/api/v1/recommend/music_weekly` | 浏览本周热门音乐,参数:`page`、`count` |
| GET | `/api/v1/recommend/music_douban` | 浏览豆瓣音乐新碟榜,参数:`page`、`count` |
专辑下载与订阅按“整包”处理:下载层会读取种子文件清单并以专辑 `total_tracks` 校验独立音频文件数量;未确认完整覆盖时不会把专辑订阅销订,也不会把部分曲目报告为完整专辑已入库。音乐整理会迁移与音轨同目录、同主干名的 `.lrc`、`.txt` 和 `.lyricsfile.yaml` 旁挂歌词。音乐刮削默认使用“质量升级”策略:先读取已有旁挂和 MP3/FLAC/Ogg/MP4 内嵌歌词,再聚合插件、LRCLIB、可选 Musixmatch 和 TheAudioDB 纯文本候选;逐字 Lyricsfile、逐行同步 LRC、纯文本依次降级,任何覆盖入口都不会用低质量结果替换高质量歌词。LRCLIB 的 Lyricsfile 会保留为 `.lyricsfile.yaml`,同时生成播放器兼容的 `.lrc`。
专辑下载与订阅按“整包”处理:下载层会读取种子文件清单并以专辑 `total_tracks` 校验独立音频文件数量;未确认完整覆盖时不会把专辑订阅销订,也不会把部分曲目报告为完整专辑已入库。音乐整理会迁移与音轨同目录、同主干名的 `.lrc`、`.txt` 和 `.lyricsfile.yaml` 旁挂歌词。音乐刮削默认使用“质量升级”策略:先读取已有旁挂和 MP3/FLAC/Ogg/MP4 内嵌歌词,再聚合插件、LRCLIB 和 TheAudioDB 纯文本候选;逐字 Lyricsfile、逐行同步 LRC、纯文本依次降级,任何覆盖入口都不会用低质量结果替换高质量歌词。Lyricsfile 会保留为 `.lyricsfile.yaml`,同时生成播放器兼容的 `.lrc`。
插件可通过 `get_module()` 注册 `music_lyrics_candidates(music)`,负责匹配并下载歌词内容,返回 `list[MusicLyrics]` 参与宿主择优;`MetaMusic`、`MusicInfo` 和 `MusicLyrics` 均可从 `app.sdk.media` 导入。该接口不需要注册 HTTP 路由,歌词文件仍由刮削链统一写入。完整契约和示例见[歌词插件开发说明](https://github.com/jxxghp/MoviePilot-Plugins/blob/main/docs/faq/21-register-lyrics-provider.md)。
音乐订阅可使用 `audio_quality=hires|lossless|lossy`(支持正则组合)、`audio_format`、`min_bitrate`、`min_bit_depth`、`min_sample_rate` 过滤资源。`best_version=1` 开启音质洗版,系统按格式、无损属性、位深、采样率和码率换算 0-100 优先级,只下载高于 `current_priority` 的候选;DSD 或 24-bit/192 kHz 无损资源达到终态 100。内置规则 `HIRES`、`LOSSLESS`、`FLAC`、`ALAC`、`APE`、`WAV`、`DSD`、`MP3`、`AAC`、`OPUS`、`BITRATE320`、`BITRATE256`、`BITRATE192` 可用于自定义过滤规则组。

View File

@@ -560,6 +560,11 @@ is itself part of the plugin ABI stays at its established path as a thin facade;
new plugin-facing symbols are exported deliberately through `app/sdk` and its
architecture snapshot, not through incidental module globals.
歌词来源插件通过 `get_module()` 注册 `music_lyrics_candidates(music)`,使用
`app.sdk.media` 的 `MetaMusic`、`MusicInfo` 和 `MusicLyrics` 公共类型。插件拥有
来源匹配与歌词内容下载;`LyricsChain` 聚合插件和内置来源候选,`ScrapingChain`
拥有质量保护与存储写入。SDK 仅导出既有领域类型,不复制歌词解析或刮削实现。
## Existing Chain, Module and DB Layers
### Chain layer

View File

@@ -1074,8 +1074,8 @@
"runtime_only": true
}
},
"edge_count": 8458,
"edge_sha256": "77a25667756a4b63d8487ac44252d77662044f1ea74d7c77dc0e4383a22d5f10",
"edge_count": 8445,
"edge_sha256": "7acc7fea7e9d6568c856c6227994ac8ffb6557e93ff575f1e7650783d081acd2",
"edges": [
"app -> app.foundation",
"app -> app.foundation.environment",
@@ -7117,19 +7117,6 @@
"app.modules.musicbrainz.cache -> app.runtime.settings",
"app.modules.musicbrainz.cache -> app.schemas",
"app.modules.musicbrainz.cache -> app.schemas.types",
"app.modules.musixmatch -> app.adapters",
"app.modules.musixmatch -> app.adapters.network",
"app.modules.musixmatch -> app.adapters.network.http",
"app.modules.musixmatch -> app.domain",
"app.modules.musixmatch -> app.domain.context",
"app.modules.musixmatch -> app.domain.meta",
"app.modules.musixmatch -> app.domain.meta.metamusic",
"app.modules.musixmatch -> app.modules",
"app.modules.musixmatch -> app.runtime",
"app.modules.musixmatch -> app.runtime.log",
"app.modules.musixmatch -> app.runtime.settings",
"app.modules.musixmatch -> app.schemas",
"app.modules.musixmatch -> app.schemas.types",
"app.modules.navidrome -> app.application",
"app.modules.navidrome -> app.application.mediaserver",
"app.modules.navidrome -> app.domain",
@@ -9536,7 +9523,7 @@
"app.workflow.actions.transfer_file -> app.workflow",
"app.workflow.actions.transfer_file -> app.workflow.actions"
],
"module_count": 995,
"module_count": 994,
"modules": [
"app",
"app.adapters",
@@ -10218,7 +10205,6 @@
"app.modules.mediavault.module",
"app.modules.musicbrainz",
"app.modules.musicbrainz.cache",
"app.modules.musixmatch",
"app.modules.navidrome",
"app.modules.navidrome.navidrome",
"app.modules.plex",

View File

@@ -1927,9 +1927,6 @@
"type-arg": 3,
"union-attr": 1
},
"app/modules/musixmatch/__init__.py": {
"no-any-return": 1
},
"app/modules/navidrome/__init__.py": {
"arg-type": 9,
"type-arg": 1,

View File

@@ -10000,6 +10000,16 @@
"name": "MetaVideo",
"target": "app.domain.meta.metavideo.MetaVideo"
},
{
"kind": "import",
"name": "MusicInfo",
"target": "app.domain.context.MusicInfo"
},
{
"kind": "import",
"name": "MusicLyrics",
"target": "app.domain.context.MusicLyrics"
},
{
"kind": "import",
"name": "MusicNameContext",

229
tests/test_lyrics_plugin.py Normal file
View File

@@ -0,0 +1,229 @@
"""公开歌词插件合同从能力注册、候选调度到旁挂文件写入的回归测试。"""
from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import Mock
import pytest
from app.application.audio import AudioMetadataHelper
from app.chain.lyrics import LyricsChain
from app.chain.scraping import ScrapingChain
from app.domain import context
from app.modules.lrclib import LrclibModule
from app.runtime.extensions.module.dispatcher import ModuleInvocationDispatcher
from app.runtime.extensions.plugin.projection import PluginProjection
from app.schemas.workflow import FileItem
from app.sdk import media
from app.sdk.media import MetaMusic, MusicInfo, MusicLyrics
class _LyricsPlugin:
"""按插件公开注册协议声明歌词候选实现。"""
def __init__(self, callback: Callable, enabled: bool = True) -> None:
"""保存候选查询入口和启用状态。"""
self.callback = callback
self.enabled = enabled
def get_name(self) -> str:
"""返回插件能力投影使用的展示名称。"""
return "测试歌词源"
def get_state(self) -> bool:
"""只允许启用状态的歌词源参与查询。"""
return self.enabled
def get_module(self) -> dict[str, Callable]:
"""使用公开候选方法名注册查询实现。"""
return {"music_lyrics_candidates": self.callback}
@pytest.fixture
def lyrics_runtime(monkeypatch) -> Callable:
"""构造真实插件投影和模块调度器,只回放 LRCLIB 的外部响应。"""
def build(plugins: dict[str, _LyricsPlugin]) -> SimpleNamespace:
"""为给定插件建立隔离的歌词链及其宿主来源。"""
builtin = LrclibModule()
request = Mock(return_value={
"id": 1,
"plainLyrics": "内置歌词",
"instrumental": False,
})
monkeypatch.setattr(builtin, "_request_json", request)
projection = PluginProjection(plugins)
plugin_error = Mock()
system_error = Mock()
dispatcher = ModuleInvocationDispatcher(
module_catalog=SimpleNamespace(
get_running_modules=lambda method: [builtin] if hasattr(builtin, method) else [],
),
plugin_catalog=SimpleNamespace(get_plugin_modules=projection.modules),
plugin_error_handler=plugin_error,
system_error_handler=system_error,
rate_limit_handler=Mock(),
)
chain = object.__new__(LyricsChain)
chain._module_dispatcher = dispatcher
chain.deadline = None
chain.budget_exceeded = False
return SimpleNamespace(
chain=chain,
projection=projection,
request=request,
plugin_error=plugin_error,
system_error=system_error,
)
return build
def test_lyrics_sdk_exports_preserve_canonical_identity() -> None:
"""插件公开类型必须与宿主候选判断和音乐输入使用同一实现。"""
assert MusicInfo is context.MusicInfo
assert MusicLyrics is context.MusicLyrics
assert {"MusicInfo", "MusicLyrics", "MetaMusic"} <= set(media.__all__)
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("music_type", [MetaMusic, MusicInfo])
async def test_registered_lyrics_plugins_merge_with_builtin_and_isolate_failures(
lyrics_runtime: Callable, asynchronous: bool, music_type: type,
) -> None:
"""新歌词接口应聚合多个启用插件和内置源,空值与异常不得阻断后续来源。"""
music = music_type(title="晴天", artists=["周杰伦"], album="叶惠美", duration=269)
calls = []
first_lyrics = MusicLyrics(provider="first", plain_lyrics="插件文本", match_score=100)
second_lyrics = MusicLyrics(
provider="second", synced_lyrics="[00:01.00]插件同步歌词", match_score=95,
)
def empty(music: Any) -> list[MusicLyrics]:
"""模拟插件未匹配到当前音轨。"""
calls.append(("empty", music))
return []
def broken(music: Any) -> list[MusicLyrics]:
"""模拟单个歌词源下载失败。"""
calls.append(("broken", music))
raise RuntimeError("歌词源不可用")
def first(music: Any) -> list[MusicLyrics]:
"""返回第一个同步插件的纯文本候选。"""
calls.append(("first", music))
return [first_lyrics]
def second(music: Any) -> list[MusicLyrics]:
"""返回第二个插件已下载的同步歌词内容。"""
calls.append(("second", music))
return [second_lyrics]
async def async_second(music: Any) -> list[MusicLyrics]:
"""验证异步入口可以混合同步与协程插件。"""
return second(music)
disabled = Mock()
runtime = lyrics_runtime({
"Empty": _LyricsPlugin(empty),
"Broken": _LyricsPlugin(broken),
"First": _LyricsPlugin(first),
"Disabled": _LyricsPlugin(disabled, enabled=False),
"Second": _LyricsPlugin(async_second if asynchronous else second),
})
candidates = (
await runtime.chain.async_get_music_lyrics_candidates(music)
if asynchronous else runtime.chain.get_music_lyrics_candidates(music)
)
assert [candidate.provider for candidate in candidates] == ["lrclib", "first", "second"]
assert candidates[1:] == [first_lyrics, second_lyrics]
assert calls == [(name, music) for name in ("empty", "broken", "first", "second")]
disabled.assert_not_called()
runtime.plugin_error.assert_called_once()
assert runtime.plugin_error.call_args.args[1:4] == (
"Broken", "测试歌词源", "music_lyrics_candidates",
)
runtime.system_error.assert_not_called()
assert runtime.request.call_count == 2
runtime.request.assert_called_with(
"/api/get",
params={"track_name": "晴天", "artist_name": "周杰伦", "album_name": "叶惠美", "duration": 269},
)
@pytest.mark.parametrize("storage", ["local", "remote"])
@pytest.mark.parametrize(
("contents", "extension", "expected"),
[
({"plain_lyrics": "插件纯文本"}, ".txt", "插件纯文本\n"),
({"synced_lyrics": "[00:01.00]插件同步歌词"}, ".lrc", "[00:01.00]插件同步歌词\n"),
],
)
def test_registered_lyrics_plugin_writes_through_music_scraping(
lyrics_runtime: Callable, monkeypatch, tmp_path: Path,
storage: str, contents: dict, extension: str, expected: str,
) -> None:
"""真实音乐刮削应把插件返回的最优歌词保存为本地旁挂文件或上传原存储目录。"""
music = MusicInfo(title="晴天", artists=["周杰伦"], music_type="recording")
lyric = MusicLyrics(provider="example", match_score=100, provider_priority=30, **contents)
callback = Mock(side_effect=lambda music: [lyric])
runtime = lyrics_runtime({"Example": _LyricsPlugin(callback)})
def create_lyrics_chain(deadline: float) -> LyricsChain:
"""保留刮削创建的查询预算,并使用隔离注册的真实歌词链。"""
runtime.chain.deadline = deadline
return runtime.chain
monkeypatch.setattr("app.chain.scraping.LyricsChain", create_lyrics_chain)
monkeypatch.setattr(AudioMetadataHelper, "read_lyrics", lambda _path: None)
local_path = tmp_path / "晴天.flac"
local_path.write_bytes(b"audio")
fileitem = FileItem(
storage=storage,
path=local_path.as_posix() if storage == "local" else "/music/晴天.flac",
name="晴天.flac", type="file", extension="flac",
)
parent = FileItem(storage=storage, path="/music", type="dir")
uploaded = {}
def upload(target: FileItem, path: Path, new_name: str) -> bool:
"""在远端上传边界读取真实生成文件,保留目录和内容证据。"""
assert target is parent
uploaded[new_name] = path.read_text(encoding="utf-8")
return True
scraping = object.__new__(ScrapingChain)
scraping.storagechain = SimpleNamespace(
download_file=Mock(return_value=local_path),
get_file_item=Mock(return_value=None),
get_parent_item=Mock(return_value=parent),
upload_file=Mock(side_effect=upload),
)
scraping.runtime_config = SimpleNamespace(lyrics_batch_timeout=30)
scraping.scraping_policies = SimpleNamespace(
option=lambda _target, metadata: SimpleNamespace(
is_skip=metadata != "lyrics", is_overwrite=False, is_upgrade=True,
),
)
success, message = scraping.scrape_music_metadata(
fileitem, mediainfo=music, audio_files=[fileitem],
)
assert success is True
assert "歌词新增 1 首" in message
callback.assert_called_once_with(music=music)
runtime.plugin_error.assert_not_called()
runtime.system_error.assert_not_called()
if storage == "local":
assert local_path.with_suffix(extension).read_text(encoding="utf-8") == expected
scraping.storagechain.upload_file.assert_not_called()
else:
assert uploaded == {f"晴天{extension}": expected}
assert not local_path.with_suffix(extension).exists()
assert local_path.read_bytes() == b"audio"

View File

@@ -583,14 +583,16 @@ from app.runtime.extensions.module.adapter import (
registry = build_host_module_registry()
specs = registry.list_specs()
assert len(specs) == 41
assert len(specs) == 40
adapter = HostModuleAdapter()
lifecycle_events = []
instances = {}
def make_recorder(operation, capability_id):
'''为每个模块保存独立的生命周期调用记录。'''
def record(instance):
'''记录生命周期操作与实际模块实例身份。'''
lifecycle_events.append((operation, capability_id, id(instance)))
return record
@@ -630,14 +632,16 @@ from app.schemas.types import EventType
registry = build_host_module_registry()
specs = registry.list_specs()
assert len(specs) == 41
assert len(specs) == 40
spec_by_id = {spec.id: spec for spec in specs}
events = {spec.id: [] for spec in specs}
adapter = HostModuleAdapter()
def make_recorder(operation, capability_id):
'''构造按模块身份分类的生命周期记录器。'''
def record(instance):
'''保存当前操作及实例身份以验证重载复用。'''
events[capability_id].append((operation, id(instance)))
return record
@@ -672,6 +676,7 @@ for spec in specs:
config_values.update({key: list(value) for key, value in enabled_service_values.items()})
def get_config(_self, key=None):
'''将真实模块配置查询限制到用例构造的内存配置。'''
key_value = getattr(key, "value", key)
if key_value is None:
return dict(config_values)
@@ -797,7 +802,7 @@ from app.runtime.extensions.module.adapter import (
registry = build_host_module_registry()
specs = registry.list_specs()
assert len(specs) == 41
assert len(specs) == 40
configured_specs = tuple(
spec for spec in specs
if spec.activation is ActivationPolicy.WHEN_CONFIGURED
@@ -881,6 +886,7 @@ from app.db.oper.systemconfig import SystemConfigOper
from app.runtime.config import settings
def empty_config(self, key=None):
'''以空配置验证未启用模块不会加载外部服务实现。'''
return {} if key is None else []
SystemConfigOper.get = empty_config
@@ -893,12 +899,12 @@ from app.application.module import configure_module_runtime
configure_module_runtime(lambda: ModuleManager())
manager = ModuleManager()
assert len(manager.list_specs()) == 41
assert len(manager.list_specs()) == 40
assert manager.get_specs() == manager.list_specs()
from app.api.endpoints.system import modulelist
response = modulelist(None)
assert len(response.data["modules"]) == 41
assert len(response.data["modules"]) == 40
heavy_prefixes = (
"lark_oapi",
@@ -1007,7 +1013,7 @@ from app.runtime.extensions.module.manager import ModuleManager
manager = ModuleManager()
modules = manager.get_modules()
assert len(modules) == len(manager.list_specs()) == 41
assert len(modules) == len(manager.list_specs()) == 40
for spec in manager.list_specs():
implementation = modules[spec.id]
assert implementation.get_name() == spec.metadata["name"]

View File

@@ -1,52 +0,0 @@
from app.domain.context import MusicInfo
from app.modules.musixmatch import MusixmatchModule
def _payload(name: str, item: dict) -> dict:
"""构造 Musixmatch 官方 message/body 响应包装。"""
return {
"message": {
"header": {"status_code": 200},
"body": {name: item},
}
}
def test_musixmatch_prefers_authorized_subtitle(monkeypatch) -> None:
"""官方 matcher 返回可用字幕时不应再请求纯文本歌词。"""
module = MusixmatchModule()
calls = []
def request(method, params):
calls.append((method, params))
return _payload("subtitle", {
"subtitle_id": 12,
"subtitle_body": "[00:01.00]Track",
"subtitle_language": "en",
"restricted": 0,
})
monkeypatch.setattr(module, "_request", request)
results = module.music_lyrics_candidates(
MusicInfo(title="Track", artists=["Artist"], duration=180)
)
assert len(results) == 1
assert results[0].synced_lyrics == "[00:01.00]Track"
assert calls[0][0] == "matcher.subtitle.get"
assert calls[0][1]["f_subtitle_length_max_deviation"] == 2
assert len(calls) == 1
def test_musixmatch_restricted_results_are_not_saved(monkeypatch) -> None:
"""授权计划标记 restricted 的字幕和歌词均不得写入本地。"""
module = MusixmatchModule()
responses = iter([
_payload("subtitle", {"restricted": 1, "subtitle_body": "blocked"}),
_payload("lyrics", {"restricted": 1, "lyrics_body": "blocked"}),
])
monkeypatch.setattr(module, "_request", lambda *_args, **_kwargs: next(responses))
assert module.music_lyrics_candidates(
MusicInfo(title="Track", artists=["Artist"])
) == []