mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-30 07:56:21 +08:00
refactor(agent): unify tools behind API gateway and provider skills
This commit is contained in:
@@ -9,8 +9,11 @@ Command 实现由 startup 组合根在生命周期启动阶段注册,避免 ap
|
||||
agent.tools / api.endpoints -> application.commands <- startup(注册 Command 类)
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from app.schemas.types import EventType, NotificationChannel
|
||||
|
||||
# Command 类:由 startup/initializers/command.py 在显式启动阶段注册。
|
||||
_command_class: Any = None
|
||||
|
||||
@@ -31,9 +34,7 @@ def reset_command_class() -> None:
|
||||
def get_command_object() -> Any:
|
||||
"""返回命令注册表实例。"""
|
||||
if _command_class is None:
|
||||
raise RuntimeError(
|
||||
"命令服务未初始化:请先通过 register_command_class 注册 Command 类"
|
||||
)
|
||||
raise RuntimeError("命令服务未初始化:请先通过 register_command_class 注册 Command 类")
|
||||
return _command_class()
|
||||
|
||||
|
||||
@@ -50,3 +51,39 @@ def get_command(name: str) -> Optional[Any]:
|
||||
def init_commands(plugin_id: Optional[str] = None) -> None:
|
||||
"""初始化命令(可指定单个插件)。"""
|
||||
get_command_object().init_commands(plugin_id)
|
||||
|
||||
|
||||
def dispatch_command(
|
||||
command: str,
|
||||
*,
|
||||
user_id: str,
|
||||
channel: Optional[NotificationChannel] = None,
|
||||
source: Optional[str] = None,
|
||||
publish_event: Callable[[EventType, dict[str, Any]], Any],
|
||||
) -> dict[str, Any]:
|
||||
"""校验斜杠命令并通过注入的事件端口异步触发执行。"""
|
||||
normalized = command.strip()
|
||||
if not normalized:
|
||||
raise ValueError("命令不能为空")
|
||||
if not normalized.startswith("/"):
|
||||
normalized = f"/{normalized}"
|
||||
command_name = normalized.split()[0]
|
||||
matched = get_command(command_name)
|
||||
if matched is None:
|
||||
available = [f"{name} - {info.get('description', '无描述')}" for name, info in get_commands().items()]
|
||||
raise ValueError(f"命令 {command_name} 不存在" + (f";可用命令: {'; '.join(available)}" if available else ""))
|
||||
publish_event(
|
||||
EventType.CommandExcute,
|
||||
{
|
||||
"cmd": normalized,
|
||||
"user": user_id,
|
||||
"channel": channel,
|
||||
"source": source,
|
||||
},
|
||||
)
|
||||
return {
|
||||
"message": f"命令 {command_name} 已触发执行",
|
||||
"command": normalized,
|
||||
"command_desc": matched.get("description", ""),
|
||||
**({"plugin_id": matched["pid"]} if matched.get("pid") else {}),
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""下载任务查询与控制应用服务。"""
|
||||
|
||||
from typing import Callable, List, Optional
|
||||
from typing import Any, Callable, List, Optional
|
||||
|
||||
from app.application.directory import validate_download_save_path
|
||||
from app.application.history import DownloadHistorySnapshot
|
||||
from app.schemas.transfer import DownloaderTorrent, DownloadTaskMedia
|
||||
from app.schemas.types import TorrentStatus
|
||||
@@ -36,9 +37,7 @@ class DownloadTaskService:
|
||||
)
|
||||
if not torrents:
|
||||
return []
|
||||
history_map = self._get_history_by_hashes(
|
||||
[torrent.hash for torrent in torrents if torrent.hash]
|
||||
)
|
||||
history_map = self._get_history_by_hashes([torrent.hash for torrent in torrents if torrent.hash])
|
||||
for torrent in torrents:
|
||||
if not torrent.hash:
|
||||
continue
|
||||
@@ -81,3 +80,168 @@ class DownloadTaskService:
|
||||
) -> bool:
|
||||
"""删除单个下载任务。"""
|
||||
return self._remove_torrents(hashs=[hash_str], downloader=name)
|
||||
|
||||
|
||||
class DownloadTaskMutationService:
|
||||
"""执行单个下载任务的受控高级修改。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
list_torrents: Callable[..., list[Any]],
|
||||
set_tags: Callable[..., bool],
|
||||
set_downloading: Callable[..., bool],
|
||||
update_torrent: Callable[..., dict[str, bool]],
|
||||
) -> None:
|
||||
"""注入下载器查询和修改端口。"""
|
||||
self._list_torrents = list_torrents
|
||||
self._set_tags = set_tags
|
||||
self._set_downloading = set_downloading
|
||||
self._update_torrent = update_torrent
|
||||
|
||||
@staticmethod
|
||||
def _validate_hash(hash_value: str) -> None:
|
||||
"""校验 BitTorrent v1 Hash,拒绝模糊任务定位。"""
|
||||
if len(hash_value) != 40 or any(character not in "0123456789abcdefABCDEF" for character in hash_value):
|
||||
raise ValueError("hash 格式无效")
|
||||
|
||||
@staticmethod
|
||||
def _normalize_list(values: Optional[list[str]]) -> Optional[list[str]]:
|
||||
"""移除字符串列表中的空项。"""
|
||||
if values is None:
|
||||
return None
|
||||
return [str(value).strip() for value in values if str(value).strip()]
|
||||
|
||||
@staticmethod
|
||||
def _result(operation: str, success: bool, message: str) -> dict[str, Any]:
|
||||
"""构造一个稳定的子操作响应。"""
|
||||
return {
|
||||
"operation": operation,
|
||||
"success": success,
|
||||
"message": message,
|
||||
}
|
||||
|
||||
def update(
|
||||
self,
|
||||
*,
|
||||
hash_value: str,
|
||||
action: Optional[str] = None,
|
||||
tags: Optional[list[str]] = None,
|
||||
downloader: Optional[str] = None,
|
||||
download_limit: Optional[float] = None,
|
||||
upload_limit: Optional[float] = None,
|
||||
trackers: Optional[list[str]] = None,
|
||||
save_path: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
ratio_limit: Optional[float] = None,
|
||||
seeding_time_limit: Optional[int] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""校验并执行启停、标签、限速、Tracker 与保存位置修改。"""
|
||||
self._validate_hash(hash_value)
|
||||
if action not in {None, "start", "stop"}:
|
||||
raise ValueError("action 只支持 start 或 stop")
|
||||
tags = self._normalize_list(tags)
|
||||
trackers = self._normalize_list(trackers)
|
||||
mutation_values = (
|
||||
action,
|
||||
tags,
|
||||
download_limit,
|
||||
upload_limit,
|
||||
trackers,
|
||||
save_path,
|
||||
category,
|
||||
ratio_limit,
|
||||
seeding_time_limit,
|
||||
)
|
||||
if not any(value is not None and value != [] for value in mutation_values):
|
||||
raise ValueError("至少需要指定一个要更新的字段")
|
||||
resolved_downloader = downloader
|
||||
if not resolved_downloader:
|
||||
torrents = (
|
||||
self._list_torrents(
|
||||
hashs=[hash_value],
|
||||
include_all_tags=True,
|
||||
)
|
||||
or []
|
||||
)
|
||||
resolved_downloader = getattr(torrents[0], "downloader", None) if torrents else None
|
||||
if not resolved_downloader:
|
||||
raise ValueError("未找到下载任务或下载器不可用")
|
||||
if save_path is not None:
|
||||
save_path = validate_download_save_path(save_path)
|
||||
results = []
|
||||
if tags:
|
||||
success = bool(
|
||||
self._set_tags(
|
||||
hashs=[hash_value],
|
||||
tags=tags,
|
||||
downloader=resolved_downloader,
|
||||
)
|
||||
)
|
||||
results.append(
|
||||
self._result(
|
||||
"tags",
|
||||
success,
|
||||
f"成功设置标签:{', '.join(tags)}" if success else "设置标签失败",
|
||||
)
|
||||
)
|
||||
if action:
|
||||
success = bool(
|
||||
self._set_downloading(
|
||||
hash_str=hash_value,
|
||||
oper=action,
|
||||
name=resolved_downloader,
|
||||
)
|
||||
)
|
||||
action_name = "开始" if action == "start" else "暂停"
|
||||
results.append(
|
||||
self._result(
|
||||
action,
|
||||
success,
|
||||
f"成功{action_name}下载任务" if success else f"{action_name}下载任务失败",
|
||||
)
|
||||
)
|
||||
advanced_values = (
|
||||
download_limit,
|
||||
upload_limit,
|
||||
trackers,
|
||||
save_path,
|
||||
category,
|
||||
ratio_limit,
|
||||
seeding_time_limit,
|
||||
)
|
||||
if any(value is not None and value != [] for value in advanced_values):
|
||||
update_result = (
|
||||
self._update_torrent(
|
||||
hash_string=hash_value,
|
||||
downloader=resolved_downloader,
|
||||
download_limit=download_limit,
|
||||
upload_limit=upload_limit,
|
||||
tracker_list=trackers,
|
||||
save_path=save_path,
|
||||
category=category,
|
||||
ratio_limit=ratio_limit,
|
||||
seeding_time_limit=seeding_time_limit,
|
||||
)
|
||||
or {}
|
||||
)
|
||||
labels = {
|
||||
"limits": "限速/做种策略",
|
||||
"trackers": "Tracker",
|
||||
"save_path": "保存目录",
|
||||
"category": "分类",
|
||||
}
|
||||
for operation, success in update_result.items():
|
||||
label = labels.get(operation, operation)
|
||||
results.append(
|
||||
self._result(
|
||||
operation,
|
||||
bool(success),
|
||||
f"{label}修改成功" if success else f"{label}修改失败或下载器不支持",
|
||||
)
|
||||
)
|
||||
return {
|
||||
"hash": hash_value,
|
||||
"downloader": resolved_downloader,
|
||||
"results": results,
|
||||
}
|
||||
|
||||
678
app/application/filtering.py
Normal file
678
app/application/filtering.py
Normal file
@@ -0,0 +1,678 @@
|
||||
"""过滤规则查询、校验、序列化和引用处理应用服务。"""
|
||||
|
||||
import copy
|
||||
import re
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from typing import Any, Dict, Iterable, Optional
|
||||
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.rules import (
|
||||
BUILTIN_RULE_SET,
|
||||
AsyncRuleGroupMutationService,
|
||||
RuleHelper,
|
||||
RuleParser,
|
||||
)
|
||||
from app.application.subscription.contract import SubscriptionRepository
|
||||
from app.schemas.rule import CustomRule
|
||||
from app.schemas.system import FilterRuleGroup
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
RULE_ID_PATTERN = re.compile(r"^[A-Za-z0-9]+$")
|
||||
RULE_TOKEN_PATTERN = re.compile(r"[A-Za-z][A-Za-z0-9]*|[0-9][A-Za-z0-9]+")
|
||||
NUMERIC_RANGE_PATTERN = re.compile(r"^\d+(?:\.\d+)?(?:\s*-\s*\d+(?:\.\d+)?)?$")
|
||||
RuleConfigPublisher = Callable[[SystemConfigKey, Any], Awaitable[None]]
|
||||
|
||||
MEDIA_TYPE_ALIASES = {
|
||||
"movie": "电影",
|
||||
"film": "电影",
|
||||
"tv": "电视剧",
|
||||
"series": "电视剧",
|
||||
"show": "电视剧",
|
||||
"music": "音乐",
|
||||
"电影": "电影",
|
||||
"电视剧": "电视剧",
|
||||
"音乐": "音乐",
|
||||
}
|
||||
|
||||
RULE_STRING_SYNTAX = {
|
||||
"level_separator": ">",
|
||||
"and_operator": "&",
|
||||
"not_operator": "!",
|
||||
"supported_grouping": "Parentheses are supported inside a single level.",
|
||||
"spacing_note": "Prefer spaces around '&', and '>' for readability; use '!RULE' for negation.",
|
||||
"match_order": "Levels are evaluated from left to right. The first matched level wins and stops further matching.",
|
||||
"match_result": "If no level matches, the torrent is filtered out. If a level matches, the torrent is kept.",
|
||||
"writing_workflow": [
|
||||
"First query built-in rules and custom rules to learn valid rule IDs.",
|
||||
"Compose one priority level with '&', '!' and optional parentheses.",
|
||||
"Join multiple priority levels with '>' from highest priority to lowest priority.",
|
||||
"Use spaces around '&', and '>' for readability.",
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"description": "Prefer torrents with special subtitles and Chinese dubbing at 4K, otherwise fall back to Chinese subtitles and Chinese dubbing at 4K.",
|
||||
"rule_string": "SPECSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL > CNSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL",
|
||||
},
|
||||
{
|
||||
"description": "Inside one level, require 4K and reject Blu-ray source.",
|
||||
"rule_string": "4K & !BLU",
|
||||
},
|
||||
{
|
||||
"description": "Inside one level, accept either special subtitles or Chinese subtitles, then also require 1080P.",
|
||||
"rule_string": "(SPECSUB | CNSUB) & 1080P",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def normalize_optional_text(value: Optional[str]) -> Optional[str]:
|
||||
"""把空白字符串折叠为 None,避免保存无意义的空值。"""
|
||||
if value is None:
|
||||
return None
|
||||
value = str(value).strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def normalize_media_type(value: Optional[str]) -> Optional[str]:
|
||||
"""兼容英中文媒体类型输入,最终统一为后端实际使用的中文值。"""
|
||||
value = normalize_optional_text(value)
|
||||
if not value:
|
||||
return None
|
||||
normalized = MEDIA_TYPE_ALIASES.get(value.lower(), value)
|
||||
if normalized not in {"电影", "电视剧", "音乐"}:
|
||||
raise ValueError("media_type 仅支持 '电影'、'电视剧'、'音乐'、'movie'、'tv' 或 'music'")
|
||||
return normalized
|
||||
|
||||
|
||||
def validate_numeric_range(field_name: str, value: Optional[str]) -> Optional[str]:
|
||||
"""校验 size_range / publish_time 这类单值或区间值。"""
|
||||
value = normalize_optional_text(value)
|
||||
if not value:
|
||||
return None
|
||||
if not NUMERIC_RANGE_PATTERN.match(value):
|
||||
raise ValueError(f"{field_name} 格式无效,支持 '1000' 或 '1000-5000' 这类数字区间格式")
|
||||
|
||||
parts = [float(item.strip()) for item in value.split("-")]
|
||||
if len(parts) == 2 and parts[0] > parts[1]:
|
||||
raise ValueError(f"{field_name} 区间起始值不能大于结束值")
|
||||
return value
|
||||
|
||||
|
||||
def validate_seeders(value: Optional[str]) -> Optional[str]:
|
||||
"""做种人数最终会被 int() 解析,这里提前拦住非法值。"""
|
||||
value = normalize_optional_text(value)
|
||||
if not value:
|
||||
return None
|
||||
if not value.isdigit():
|
||||
raise ValueError("seeders 必须是非负整数")
|
||||
return value
|
||||
|
||||
|
||||
def get_builtin_rules() -> Dict[str, dict]:
|
||||
"""返回内置规则的深拷贝,避免调用方误改共享常量。"""
|
||||
return copy.deepcopy(BUILTIN_RULE_SET)
|
||||
|
||||
|
||||
def get_custom_rules() -> list[CustomRule]:
|
||||
return RuleHelper().get_custom_rules()
|
||||
|
||||
|
||||
def get_rule_groups() -> list[FilterRuleGroup]:
|
||||
return RuleHelper().get_rule_groups()
|
||||
|
||||
|
||||
def build_custom_rule_map(rules: Optional[Iterable[CustomRule]] = None) -> Dict[str, CustomRule]:
|
||||
return {rule.id: rule for rule in (rules or get_custom_rules()) if rule.id}
|
||||
|
||||
|
||||
def build_rule_group_map(
|
||||
groups: Optional[Iterable[FilterRuleGroup]] = None,
|
||||
) -> Dict[str, FilterRuleGroup]:
|
||||
return {group.name: group for group in (groups or get_rule_groups()) if group.name}
|
||||
|
||||
|
||||
def extract_rule_tokens(rule_string: Optional[str]) -> list[str]:
|
||||
"""从规则串里提取规则 ID,用于引用分析和未知规则校验。"""
|
||||
if not rule_string:
|
||||
return []
|
||||
# dict.fromkeys 用来在保留顺序的同时去重,便于展示和报错。
|
||||
return list(dict.fromkeys(RULE_TOKEN_PATTERN.findall(rule_string)))
|
||||
|
||||
|
||||
def parse_rule_string(rule_string: str) -> dict:
|
||||
"""使用后端同款 RuleParser 解析规则串,并拆出每一层的元数据。"""
|
||||
normalized = normalize_optional_text(rule_string)
|
||||
if not normalized:
|
||||
raise ValueError("rule_string 不能为空")
|
||||
|
||||
parser = RuleParser()
|
||||
levels = [level.strip() for level in normalized.split(">")]
|
||||
if any(not level for level in levels):
|
||||
raise ValueError("rule_string 不能包含空层级,请检查 '>' 两侧内容")
|
||||
|
||||
parsed_levels = []
|
||||
for index, level in enumerate(levels, start=1):
|
||||
try:
|
||||
parser.parse(level)
|
||||
except Exception as exc: # pragma: no cover - 依赖 pyparsing 的具体异常
|
||||
raise ValueError(f"规则串第 {index} 层语法错误: {exc}") from exc
|
||||
|
||||
parsed_levels.append(
|
||||
{
|
||||
"priority": index,
|
||||
"expression": level,
|
||||
"referenced_rules": extract_rule_tokens(level),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"rule_string": " > ".join(levels),
|
||||
"levels": parsed_levels,
|
||||
"referenced_rules": extract_rule_tokens(normalized),
|
||||
}
|
||||
|
||||
|
||||
def validate_rule_string(rule_string: str, available_rule_ids: Iterable[str]) -> dict:
|
||||
"""校验规则串语法和引用规则是否都存在。"""
|
||||
parsed = parse_rule_string(rule_string)
|
||||
available_ids = set(available_rule_ids)
|
||||
unknown_rules = sorted({rule_id for rule_id in parsed["referenced_rules"] if rule_id not in available_ids})
|
||||
if unknown_rules:
|
||||
raise ValueError(f"rule_string 引用了不存在的规则: {', '.join(unknown_rules)}")
|
||||
return parsed
|
||||
|
||||
|
||||
def serialize_builtin_rule(rule_id: str, payload: dict) -> dict:
|
||||
"""把内置规则整理成适合 Agent 阅读的结构。"""
|
||||
data = copy.deepcopy(payload)
|
||||
data["id"] = rule_id
|
||||
data["source"] = "builtin"
|
||||
return data
|
||||
|
||||
|
||||
def serialize_custom_rule(rule: CustomRule, group_refs: Optional[list[str]] = None) -> dict:
|
||||
data = rule.model_dump(exclude_none=True)
|
||||
data["source"] = "custom"
|
||||
data["referenced_by_rule_groups"] = group_refs or []
|
||||
return data
|
||||
|
||||
|
||||
def serialize_rule_group(group: FilterRuleGroup, usage: Optional[dict] = None) -> dict:
|
||||
"""查询时尽量附带解析结果,便于 Agent 理解优先级层级。"""
|
||||
data = group.model_dump(exclude_none=True)
|
||||
if group.rule_string:
|
||||
try:
|
||||
parsed = parse_rule_string(group.rule_string)
|
||||
data["levels"] = parsed["levels"]
|
||||
data["referenced_rules"] = parsed["referenced_rules"]
|
||||
data["syntax_valid"] = True
|
||||
except ValueError as exc:
|
||||
data["syntax_valid"] = False
|
||||
data["syntax_error"] = str(exc)
|
||||
data["referenced_rules"] = extract_rule_tokens(group.rule_string)
|
||||
else:
|
||||
data["syntax_valid"] = False
|
||||
data["syntax_error"] = "rule_string 为空"
|
||||
data["referenced_rules"] = []
|
||||
data["usage"] = usage or default_rule_group_usage()
|
||||
return data
|
||||
|
||||
|
||||
def default_rule_group_usage() -> dict:
|
||||
return {
|
||||
"used_in_global_search": False,
|
||||
"used_in_global_subscribe": False,
|
||||
"used_in_global_best_version": False,
|
||||
"subscribes": [],
|
||||
}
|
||||
|
||||
|
||||
async def collect_rule_group_usages(
|
||||
repository: SubscriptionRepository,
|
||||
group_names: Optional[Iterable[str]] = None,
|
||||
) -> Dict[str, dict]:
|
||||
"""收集规则组在全局配置和订阅上的引用情况。"""
|
||||
target_names = set(group_names or [])
|
||||
search_groups = set(get_configured_system_config().get(SystemConfigKey.SearchFilterRuleGroups) or [])
|
||||
subscribe_groups = set(get_configured_system_config().get(SystemConfigKey.SubscribeFilterRuleGroups) or [])
|
||||
best_version_groups = set(get_configured_system_config().get(SystemConfigKey.BestVersionFilterRuleGroups) or [])
|
||||
|
||||
usage_map = {name: default_rule_group_usage() for name in target_names}
|
||||
|
||||
def ensure_usage(name: str) -> dict:
|
||||
if name not in usage_map:
|
||||
usage_map[name] = default_rule_group_usage()
|
||||
return usage_map[name]
|
||||
|
||||
for name in search_groups:
|
||||
if target_names and name not in target_names:
|
||||
continue
|
||||
ensure_usage(name)["used_in_global_search"] = True
|
||||
for name in subscribe_groups:
|
||||
if target_names and name not in target_names:
|
||||
continue
|
||||
ensure_usage(name)["used_in_global_subscribe"] = True
|
||||
for name in best_version_groups:
|
||||
if target_names and name not in target_names:
|
||||
continue
|
||||
ensure_usage(name)["used_in_global_best_version"] = True
|
||||
|
||||
subscribes = await repository.async_list()
|
||||
for subscribe in subscribes:
|
||||
filter_groups = (
|
||||
[str(name) for name in subscribe.filter_groups] if isinstance(subscribe.filter_groups, list) else []
|
||||
)
|
||||
for name in filter_groups:
|
||||
if target_names and name not in target_names:
|
||||
continue
|
||||
ensure_usage(name)["subscribes"].append(
|
||||
{
|
||||
"subscribe_id": subscribe.id,
|
||||
"name": subscribe.name,
|
||||
"season": subscribe.season,
|
||||
"type": subscribe.type,
|
||||
"username": subscribe.username,
|
||||
"best_version": bool(subscribe.best_version),
|
||||
}
|
||||
)
|
||||
|
||||
return usage_map
|
||||
|
||||
|
||||
def collect_custom_rule_group_refs(
|
||||
rule_groups: Iterable[FilterRuleGroup],
|
||||
rule_ids: Optional[Iterable[str]] = None,
|
||||
) -> Dict[str, list[str]]:
|
||||
"""收集自定义规则被哪些规则组引用。"""
|
||||
target_rule_ids = set(rule_ids or [])
|
||||
refs: Dict[str, list[str]] = {rule_id: [] for rule_id in target_rule_ids}
|
||||
|
||||
for group in rule_groups:
|
||||
if not group.name or not group.rule_string:
|
||||
continue
|
||||
referenced = set(extract_rule_tokens(group.rule_string))
|
||||
for rule_id in referenced:
|
||||
if target_rule_ids and rule_id not in target_rule_ids:
|
||||
continue
|
||||
refs.setdefault(rule_id, []).append(group.name)
|
||||
|
||||
for names in refs.values():
|
||||
names.sort()
|
||||
return refs
|
||||
|
||||
|
||||
def normalize_custom_rule(
|
||||
rule_id: str,
|
||||
name: str,
|
||||
include: Optional[str],
|
||||
exclude: Optional[str],
|
||||
size_range: Optional[str],
|
||||
seeders: Optional[str],
|
||||
publish_time: Optional[str],
|
||||
existing_rules: Iterable[CustomRule],
|
||||
original_rule_id: Optional[str] = None,
|
||||
) -> CustomRule:
|
||||
"""新增/更新自定义规则时统一走这里,避免多处散落校验逻辑。"""
|
||||
normalized_rule_id = normalize_optional_text(rule_id)
|
||||
normalized_name = normalize_optional_text(name)
|
||||
if not normalized_rule_id:
|
||||
raise ValueError("rule_id 不能为空")
|
||||
if not normalized_name:
|
||||
raise ValueError("name 不能为空")
|
||||
if not RULE_ID_PATTERN.match(normalized_rule_id):
|
||||
raise ValueError("rule_id 仅支持英文字母和数字")
|
||||
if normalized_rule_id in BUILTIN_RULE_SET and normalized_rule_id != original_rule_id:
|
||||
raise ValueError(f"rule_id '{normalized_rule_id}' 与内置规则冲突,不能覆盖内置规则")
|
||||
|
||||
for existing_rule in existing_rules:
|
||||
if existing_rule.id == normalized_rule_id and existing_rule.id != original_rule_id:
|
||||
raise ValueError(f"rule_id '{normalized_rule_id}' 已存在")
|
||||
if existing_rule.name == normalized_name and existing_rule.id != original_rule_id:
|
||||
raise ValueError(f"规则名称 '{normalized_name}' 已存在")
|
||||
|
||||
return CustomRule(
|
||||
id=normalized_rule_id,
|
||||
name=normalized_name,
|
||||
include=normalize_optional_text(include),
|
||||
exclude=normalize_optional_text(exclude),
|
||||
size_range=validate_numeric_range("size_range", size_range),
|
||||
seeders=validate_seeders(seeders),
|
||||
publish_time=validate_numeric_range("publish_time", publish_time),
|
||||
)
|
||||
|
||||
|
||||
def normalize_rule_group(
|
||||
name: str,
|
||||
rule_string: str,
|
||||
media_type: Optional[str],
|
||||
category: Optional[str],
|
||||
existing_groups: Iterable[FilterRuleGroup],
|
||||
available_rule_ids: Iterable[str],
|
||||
original_name: Optional[str] = None,
|
||||
) -> tuple[FilterRuleGroup, dict]:
|
||||
"""新增/更新规则组时统一校验名字、适用范围和规则串。"""
|
||||
normalized_name = normalize_optional_text(name)
|
||||
if not normalized_name:
|
||||
raise ValueError("规则组名称不能为空")
|
||||
|
||||
for group in existing_groups:
|
||||
if group.name == normalized_name and group.name != original_name:
|
||||
raise ValueError(f"规则组名称 '{normalized_name}' 已存在")
|
||||
|
||||
normalized_media_type = normalize_media_type(media_type)
|
||||
normalized_category = normalize_optional_text(category)
|
||||
if normalized_category and not normalized_media_type:
|
||||
raise ValueError("设置 category 时必须同时设置 media_type")
|
||||
|
||||
parsed = validate_rule_string(rule_string, available_rule_ids)
|
||||
return (
|
||||
FilterRuleGroup(
|
||||
name=normalized_name,
|
||||
rule_string=parsed["rule_string"],
|
||||
media_type=normalized_media_type,
|
||||
category=normalized_category,
|
||||
),
|
||||
parsed,
|
||||
)
|
||||
|
||||
|
||||
async def save_system_config(
|
||||
key: SystemConfigKey,
|
||||
value: Any,
|
||||
publish_config_changed: RuleConfigPublisher,
|
||||
) -> Optional[bool]:
|
||||
"""通过统一入口保存配置并补发 ConfigChanged 事件。"""
|
||||
normalized_value = value
|
||||
if isinstance(normalized_value, list):
|
||||
normalized_value = [item for item in normalized_value if item is not None and item != ""]
|
||||
normalized_value = normalized_value or None
|
||||
|
||||
success = await get_configured_system_config().async_set(key, normalized_value)
|
||||
if success:
|
||||
await publish_config_changed(key, normalized_value)
|
||||
return success
|
||||
|
||||
|
||||
def replace_rule_id_in_rule_string(rule_string: str, old_rule_id: str, new_rule_id: str) -> str:
|
||||
"""只替换完整 token,避免误伤其他规则名。"""
|
||||
pattern = re.compile(rf"(?<![A-Za-z0-9]){re.escape(old_rule_id)}(?![A-Za-z0-9])")
|
||||
return pattern.sub(new_rule_id, rule_string)
|
||||
|
||||
|
||||
class FilterRuleService:
|
||||
"""提供过滤规则和规则组的查询与事务化修改用例。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
subscriptions: SubscriptionRepository,
|
||||
mutation_scope: Callable[[], AbstractAsyncContextManager[AsyncRuleGroupMutationService]],
|
||||
publish_config_changed: RuleConfigPublisher,
|
||||
) -> None:
|
||||
"""注入订阅端口、规则组事务作用域和配置事件发布端口。"""
|
||||
self._subscriptions = subscriptions
|
||||
self._mutation_scope = mutation_scope
|
||||
self._publish_config_changed = publish_config_changed
|
||||
|
||||
@staticmethod
|
||||
def query_builtin(rule_ids: Optional[list[str]] = None) -> dict[str, Any]:
|
||||
"""查询内置过滤规则及规则串语法。"""
|
||||
rules = get_builtin_rules()
|
||||
if rule_ids:
|
||||
target_ids = set(rule_ids)
|
||||
rules = {key: value for key, value in rules.items() if key in target_ids}
|
||||
serialized = [serialize_builtin_rule(rule_id, payload) for rule_id, payload in rules.items()]
|
||||
return {
|
||||
"count": len(serialized),
|
||||
"rule_string_syntax": RULE_STRING_SYNTAX,
|
||||
"rules": serialized,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def query_custom(
|
||||
rule_ids: Optional[list[str]] = None,
|
||||
*,
|
||||
include_group_refs: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""查询自定义过滤规则及规则组引用。"""
|
||||
rules = get_custom_rules()
|
||||
if rule_ids:
|
||||
target_ids = set(rule_ids)
|
||||
rules = [rule for rule in rules if rule.id in target_ids]
|
||||
refs = (
|
||||
collect_custom_rule_group_refs(
|
||||
get_rule_groups(),
|
||||
[rule.id for rule in rules if rule.id],
|
||||
)
|
||||
if include_group_refs
|
||||
else {}
|
||||
)
|
||||
serialized = [serialize_custom_rule(rule, refs.get(rule.id)) for rule in rules]
|
||||
return {"count": len(serialized), "rules": serialized}
|
||||
|
||||
async def query_groups(
|
||||
self,
|
||||
group_names: Optional[list[str]] = None,
|
||||
*,
|
||||
include_usage: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""查询规则组、解析层级和可选引用位置。"""
|
||||
groups = get_rule_groups()
|
||||
if group_names:
|
||||
target_names = set(group_names)
|
||||
groups = [group for group in groups if group.name in target_names]
|
||||
usage = (
|
||||
await collect_rule_group_usages(
|
||||
self._subscriptions,
|
||||
[group.name for group in groups if group.name],
|
||||
)
|
||||
if include_usage
|
||||
else {}
|
||||
)
|
||||
serialized = [serialize_rule_group(group, usage.get(group.name)) for group in groups]
|
||||
return {
|
||||
"count": len(serialized),
|
||||
"rule_string_syntax": RULE_STRING_SYNTAX,
|
||||
"rule_groups": serialized,
|
||||
}
|
||||
|
||||
async def add_custom(self, **values: Any) -> dict[str, Any]:
|
||||
"""校验并新增一条自定义过滤规则。"""
|
||||
rules = get_custom_rules()
|
||||
new_rule = normalize_custom_rule(existing_rules=rules, **values)
|
||||
rules.append(new_rule)
|
||||
await save_system_config(
|
||||
SystemConfigKey.CustomFilterRules,
|
||||
[rule.model_dump(exclude_none=True) for rule in rules],
|
||||
self._publish_config_changed,
|
||||
)
|
||||
return {
|
||||
"message": f"已新增自定义过滤规则 {new_rule.id}",
|
||||
"custom_rule": serialize_custom_rule(new_rule),
|
||||
"count": len(rules),
|
||||
}
|
||||
|
||||
async def update_custom(
|
||||
self,
|
||||
*,
|
||||
current_rule_id: str,
|
||||
new_rule_id: Optional[str] = None,
|
||||
name: Optional[str] = None,
|
||||
include: Optional[str] = None,
|
||||
exclude: Optional[str] = None,
|
||||
size_range: Optional[str] = None,
|
||||
seeders: Optional[str] = None,
|
||||
publish_time: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""更新自定义规则,并在改名时原子重写规则组引用。"""
|
||||
rules = get_custom_rules()
|
||||
current = next((rule for rule in rules if rule.id == current_rule_id), None)
|
||||
if current is None:
|
||||
raise ValueError(f"自定义过滤规则 '{current_rule_id}' 不存在")
|
||||
updated = normalize_custom_rule(
|
||||
rule_id=new_rule_id or current.id,
|
||||
name=name if name is not None else current.name,
|
||||
include=include if include is not None else current.include,
|
||||
exclude=exclude if exclude is not None else current.exclude,
|
||||
size_range=size_range if size_range is not None else current.size_range,
|
||||
seeders=seeders if seeders is not None else current.seeders,
|
||||
publish_time=(publish_time if publish_time is not None else current.publish_time),
|
||||
existing_rules=rules,
|
||||
original_rule_id=current.id,
|
||||
)
|
||||
expected_rules = [rule.model_dump(exclude_none=True) for rule in rules]
|
||||
final_rules = [updated if rule.id == current.id else rule for rule in rules]
|
||||
rule_definitions = [rule.model_dump(exclude_none=True) for rule in final_rules]
|
||||
groups = get_rule_groups()
|
||||
updated_groups = groups
|
||||
renamed_refs: list[str] = []
|
||||
if updated.id != current.id:
|
||||
updated_groups = []
|
||||
for group in groups:
|
||||
new_rule_string = replace_rule_id_in_rule_string(
|
||||
group.rule_string or "",
|
||||
current.id or "",
|
||||
updated.id or "",
|
||||
)
|
||||
if new_rule_string != (group.rule_string or ""):
|
||||
renamed_refs.append(group.name or "")
|
||||
group = group.model_copy(update={"rule_string": new_rule_string})
|
||||
updated_groups.append(group)
|
||||
expected_groups = [group.model_dump(exclude_none=True) for group in groups]
|
||||
group_definitions = [group.model_dump(exclude_none=True) for group in updated_groups]
|
||||
async with self._mutation_scope() as mutation:
|
||||
await mutation.apply(
|
||||
group_definitions,
|
||||
expected_rule_groups=expected_groups,
|
||||
custom_rules=rule_definitions,
|
||||
expected_custom_rules=expected_rules,
|
||||
)
|
||||
await self._publish_config_changed(SystemConfigKey.CustomFilterRules, rule_definitions)
|
||||
await self._publish_config_changed(SystemConfigKey.UserFilterRuleGroups, group_definitions)
|
||||
else:
|
||||
await save_system_config(
|
||||
SystemConfigKey.CustomFilterRules,
|
||||
rule_definitions,
|
||||
self._publish_config_changed,
|
||||
)
|
||||
refs = collect_custom_rule_group_refs(updated_groups, [updated.id]).get(updated.id, [])
|
||||
return {
|
||||
"message": f"已更新自定义过滤规则 {updated.id}",
|
||||
"custom_rule": serialize_custom_rule(updated, refs),
|
||||
"rule_groups_updated_for_rule_id_rename": renamed_refs,
|
||||
}
|
||||
|
||||
async def delete_custom(self, rule_id: str) -> dict[str, Any]:
|
||||
"""删除未被规则组引用的自定义过滤规则。"""
|
||||
rules = get_custom_rules()
|
||||
if not any(rule.id == rule_id for rule in rules):
|
||||
raise ValueError(f"自定义过滤规则 '{rule_id}' 不存在")
|
||||
refs = collect_custom_rule_group_refs(get_rule_groups(), [rule_id]).get(rule_id, [])
|
||||
if refs:
|
||||
raise ValueError(f"自定义过滤规则 '{rule_id}' 仍被规则组引用: {', '.join(refs)}")
|
||||
remaining = [rule for rule in rules if rule.id != rule_id]
|
||||
await save_system_config(
|
||||
SystemConfigKey.CustomFilterRules,
|
||||
[rule.model_dump(exclude_none=True) for rule in remaining],
|
||||
self._publish_config_changed,
|
||||
)
|
||||
return {
|
||||
"message": f"已删除自定义过滤规则 {rule_id}",
|
||||
"count": len(remaining),
|
||||
}
|
||||
|
||||
async def add_group(
|
||||
self,
|
||||
*,
|
||||
name: str,
|
||||
rule_string: str,
|
||||
media_type: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""校验并新增规则组。"""
|
||||
groups = get_rule_groups()
|
||||
available_ids = set(get_builtin_rules()) | set(build_custom_rule_map())
|
||||
new_group, parsed = normalize_rule_group(
|
||||
name,
|
||||
rule_string,
|
||||
media_type,
|
||||
category,
|
||||
groups,
|
||||
available_ids,
|
||||
)
|
||||
expected = [group.model_dump(exclude_none=True) for group in groups]
|
||||
definitions = [*expected, new_group.model_dump(exclude_none=True)]
|
||||
async with self._mutation_scope() as mutation:
|
||||
await mutation.apply(definitions, expected_rule_groups=expected)
|
||||
await self._publish_config_changed(SystemConfigKey.UserFilterRuleGroups, definitions)
|
||||
usage = await collect_rule_group_usages(self._subscriptions, [new_group.name])
|
||||
return {
|
||||
"message": f"已新增规则组 {new_group.name}",
|
||||
"rule_group": serialize_rule_group(new_group, usage.get(new_group.name)),
|
||||
"parsed": parsed,
|
||||
"count": len(definitions),
|
||||
}
|
||||
|
||||
async def update_group(
|
||||
self,
|
||||
*,
|
||||
current_name: str,
|
||||
new_name: Optional[str] = None,
|
||||
rule_string: Optional[str] = None,
|
||||
media_type: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""更新规则组并原子重写全局配置和订阅引用。"""
|
||||
groups = get_rule_groups()
|
||||
current = next((group for group in groups if group.name == current_name), None)
|
||||
if current is None:
|
||||
raise ValueError(f"规则组 '{current_name}' 不存在")
|
||||
available_ids = set(get_builtin_rules()) | set(build_custom_rule_map())
|
||||
updated, parsed = normalize_rule_group(
|
||||
new_name or current.name or "",
|
||||
rule_string if rule_string is not None else current.rule_string or "",
|
||||
media_type if media_type is not None else current.media_type,
|
||||
category if category is not None else current.category,
|
||||
groups,
|
||||
available_ids,
|
||||
original_name=current.name,
|
||||
)
|
||||
expected = [group.model_dump(exclude_none=True) for group in groups]
|
||||
final_groups = [updated if group.name == current.name else group for group in groups]
|
||||
definitions = [group.model_dump(exclude_none=True) for group in final_groups]
|
||||
async with self._mutation_scope() as mutation:
|
||||
result = await mutation.apply(
|
||||
definitions,
|
||||
expected_rule_groups=expected,
|
||||
previous_name=current.name,
|
||||
current_name=updated.name,
|
||||
)
|
||||
await self._publish_config_changed(SystemConfigKey.UserFilterRuleGroups, definitions)
|
||||
usage = await collect_rule_group_usages(self._subscriptions, [updated.name])
|
||||
return {
|
||||
"message": f"已更新规则组 {updated.name}",
|
||||
"rule_group": serialize_rule_group(updated, usage.get(updated.name)),
|
||||
"parsed": parsed,
|
||||
"reference_updates": result.to_dict(),
|
||||
}
|
||||
|
||||
async def delete_group(self, name: str) -> dict[str, Any]:
|
||||
"""删除规则组并原子清理全部引用。"""
|
||||
groups = get_rule_groups()
|
||||
if not any(group.name == name for group in groups):
|
||||
raise ValueError(f"规则组 '{name}' 不存在")
|
||||
expected = [group.model_dump(exclude_none=True) for group in groups]
|
||||
remaining = [group for group in groups if group.name != name]
|
||||
definitions = [group.model_dump(exclude_none=True) for group in remaining]
|
||||
async with self._mutation_scope() as mutation:
|
||||
result = await mutation.apply(
|
||||
definitions,
|
||||
expected_rule_groups=expected,
|
||||
previous_name=name,
|
||||
)
|
||||
await self._publish_config_changed(SystemConfigKey.UserFilterRuleGroups, definitions)
|
||||
return {
|
||||
"message": f"已删除规则组 {name}",
|
||||
"count": len(remaining),
|
||||
"reference_updates": result.to_dict(),
|
||||
}
|
||||
@@ -30,7 +30,7 @@ import aiofiles # type: ignore[import-untyped]
|
||||
|
||||
from app.application import agent as agent_application
|
||||
from app.application.agent import is_audio_input_available, transcribe_audio
|
||||
from app.application.commands import get_command, get_commands
|
||||
from app.application.commands import dispatch_command, get_command, get_commands
|
||||
from app.application.configuration import get_api_runtime_config_snapshot
|
||||
from app.application.messaging.chat import (
|
||||
AgentChatPersistenceService,
|
||||
@@ -1253,7 +1253,7 @@ async def terminate_web_agent_audio_process(
|
||||
return
|
||||
try:
|
||||
await process.communicate()
|
||||
except (OSError, ProcessLookupError):
|
||||
except OSError, ProcessLookupError:
|
||||
pass
|
||||
|
||||
|
||||
@@ -1705,6 +1705,24 @@ def build_web_agent_command_items() -> list[dict[str, Any]]:
|
||||
return sorted(items, key=lambda item: (item["category"], item["command"]))
|
||||
|
||||
|
||||
def dispatch_web_agent_command(
|
||||
command: str,
|
||||
*,
|
||||
user_id: str,
|
||||
channel: Optional[NotificationChannel],
|
||||
source: Optional[str],
|
||||
publish_event: Callable[[Any, dict[str, Any]], Any],
|
||||
) -> dict[str, Any]:
|
||||
"""经消息应用边界校验并触发一条 Agent 斜杠命令。"""
|
||||
return dispatch_command(
|
||||
command,
|
||||
user_id=user_id,
|
||||
channel=channel,
|
||||
source=source,
|
||||
publish_event=publish_event,
|
||||
)
|
||||
|
||||
|
||||
def extract_web_agent_slash_command(text: str) -> Optional[str]:
|
||||
"""
|
||||
从 WebAgent 输入中提取斜杠命令名。
|
||||
|
||||
85
app/application/music/projection.py
Normal file
85
app/application/music/projection.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""音乐实体面向 API 和 Agent 的有界结果投影。"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.domain.context import (
|
||||
MusicAlbumInfo,
|
||||
MusicArtistInfo,
|
||||
MusicInfo,
|
||||
)
|
||||
from app.schemas.types import media_type_to_agent
|
||||
|
||||
MUSIC_TRACK_PREVIEW_LIMIT = 100
|
||||
MUSIC_RELEASE_PREVIEW_LIMIT = 20
|
||||
|
||||
|
||||
def simplify_music_info(info: MusicInfo) -> dict[str, Any]:
|
||||
"""精简音乐列表项,同时保留订阅和下载所需的稳定身份。"""
|
||||
payload = {
|
||||
"title": info.title,
|
||||
"year": info.year,
|
||||
"type": media_type_to_agent(info.type),
|
||||
"music_type": info.music_type,
|
||||
"artists": list(info.artists or []),
|
||||
"artist_ids": list(info.artist_ids or []),
|
||||
"artist": info.artist,
|
||||
"album": info.album,
|
||||
"album_id": info.album_id,
|
||||
"album_type": info.album_type,
|
||||
"release_date": info.release_date,
|
||||
"disc_number": info.disc_number,
|
||||
"track_number": info.track_number,
|
||||
"total_tracks": info.total_tracks,
|
||||
"duration": info.duration,
|
||||
"isrc": info.isrc,
|
||||
"version": info.version,
|
||||
"genres": list(info.genres or []),
|
||||
"category": info.category,
|
||||
"listen_count": info.listen_count,
|
||||
"media_source": info.media_source,
|
||||
"media_id": info.media_id,
|
||||
"poster_path": info.poster_path,
|
||||
"detail_link": info.detail_link,
|
||||
"overview": info.overview,
|
||||
}
|
||||
return {key: value for key, value in payload.items() if value not in (None, "", [])}
|
||||
|
||||
|
||||
def simplify_music_album(
|
||||
info: MusicAlbumInfo,
|
||||
*,
|
||||
track_limit: int = MUSIC_TRACK_PREVIEW_LIMIT,
|
||||
) -> dict[str, Any]:
|
||||
"""精简专辑详情并限制曲目和发行版本预览,避免撑大 Agent 上下文。"""
|
||||
normalized_track_limit = max(1, min(track_limit, MUSIC_TRACK_PREVIEW_LIMIT))
|
||||
tracks = list(info.tracks or [])
|
||||
releases = list(info.releases or [])
|
||||
payload = simplify_music_info(info.to_music_info())
|
||||
payload.update(
|
||||
{
|
||||
"release_date": info.release_date,
|
||||
"secondary_types": list(info.secondary_types or []),
|
||||
"tags": list(info.tags or []),
|
||||
"rating": info.rating,
|
||||
"rating_votes": info.rating_votes,
|
||||
"tracks": [simplify_music_info(track) for track in tracks[:normalized_track_limit]],
|
||||
"tracks_total": len(tracks),
|
||||
"tracks_truncated": len(tracks) > normalized_track_limit,
|
||||
"releases": [release.to_dict() for release in releases[:MUSIC_RELEASE_PREVIEW_LIMIT]],
|
||||
"releases_total": len(releases),
|
||||
"releases_truncated": len(releases) > MUSIC_RELEASE_PREVIEW_LIMIT,
|
||||
}
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def simplify_music_artist(info: MusicArtistInfo) -> dict[str, Any]:
|
||||
"""精简艺术家详情,明确其仅用于浏览而非订阅或下载。"""
|
||||
payload = info.to_dict()
|
||||
payload.pop("raw_data", None)
|
||||
payload.pop("mediaid_prefix", None)
|
||||
payload["type"] = media_type_to_agent(info.type)
|
||||
payload["media_source"] = info.media_source
|
||||
payload["media_id"] = info.media_id
|
||||
payload["subscribable"] = False
|
||||
return {key: value for key, value in payload.items() if value not in (None, "", [])}
|
||||
@@ -1,6 +1,8 @@
|
||||
"""插件持久化数据查询与写用例。"""
|
||||
"""插件持久化数据查询、投影与写用例。"""
|
||||
|
||||
from typing import Protocol
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from typing import Any, Optional, Protocol
|
||||
|
||||
from app.schemas.common import JsonData
|
||||
|
||||
@@ -57,3 +59,89 @@ class DeletePluginDataCommand:
|
||||
except Exception:
|
||||
self._unit_of_work.rollback()
|
||||
raise
|
||||
|
||||
|
||||
DEFAULT_PLUGIN_DATA_PREVIEW_CHARS = 12_000
|
||||
MAX_PLUGIN_DATA_PREVIEW_CHARS = 50_000
|
||||
PLUGIN_DATA_KEY_PREVIEW_LIMIT = 50
|
||||
PLUGIN_DATA_TRUNCATION_SUFFIX = "\n...(插件数据内容过长,已截断)"
|
||||
|
||||
|
||||
def clamp_preview_chars(max_chars: Optional[int]) -> int:
|
||||
"""约束插件数据预览长度,避免结果无限膨胀。"""
|
||||
if max_chars is None:
|
||||
return DEFAULT_PLUGIN_DATA_PREVIEW_CHARS
|
||||
return max(512, min(int(max_chars), MAX_PLUGIN_DATA_PREVIEW_CHARS))
|
||||
|
||||
|
||||
def build_preview_payload(value: Any, max_chars: Optional[int]) -> tuple[bool, int, int, str]:
|
||||
"""稳定序列化插件数据并生成有界预览。"""
|
||||
serialized = json.dumps(value, ensure_ascii=False, indent=2, default=str)
|
||||
preview_limit = clamp_preview_chars(max_chars)
|
||||
if len(serialized) <= preview_limit:
|
||||
return False, len(serialized), len(serialized), serialized
|
||||
preview = serialized[:preview_limit] + PLUGIN_DATA_TRUNCATION_SUFFIX
|
||||
return True, len(serialized), len(preview), preview
|
||||
|
||||
|
||||
class PluginDataQueryService:
|
||||
"""查询已安装插件数据并对大结果执行稳定裁剪。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
repository: PluginDataQueryRepository,
|
||||
snapshot: Callable[[str], Optional[dict[str, Any]]],
|
||||
) -> None:
|
||||
"""注入插件数据仓储和安装态快照查询函数。"""
|
||||
self._repository = repository
|
||||
self._snapshot = snapshot
|
||||
|
||||
async def query(
|
||||
self,
|
||||
plugin_id: str,
|
||||
*,
|
||||
key: Optional[str] = None,
|
||||
max_chars: Optional[int] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""读取单键或全部数据,并返回上下文安全的投影。"""
|
||||
plugin = self._snapshot(plugin_id)
|
||||
if plugin is None:
|
||||
raise ValueError(f"插件 {plugin_id} 不存在")
|
||||
if key:
|
||||
value = await self._repository.get(plugin_id, key)
|
||||
if value is None:
|
||||
return {
|
||||
**plugin,
|
||||
"key": key,
|
||||
"found": False,
|
||||
"message": f"插件 {plugin_id} 没有数据项 {key}",
|
||||
}
|
||||
truncated, total_chars, returned_chars, preview = build_preview_payload(value, max_chars)
|
||||
result = {
|
||||
**plugin,
|
||||
"key": key,
|
||||
"found": True,
|
||||
"truncated": truncated,
|
||||
"total_chars": total_chars,
|
||||
"returned_chars": returned_chars,
|
||||
}
|
||||
result["value_preview" if truncated else "value"] = preview if truncated else value
|
||||
return result
|
||||
data = await self._repository.list(plugin_id)
|
||||
keys = list(data)
|
||||
result = {
|
||||
**plugin,
|
||||
"count": len(data),
|
||||
"keys": keys[:PLUGIN_DATA_KEY_PREVIEW_LIMIT],
|
||||
"keys_truncated": len(keys) > PLUGIN_DATA_KEY_PREVIEW_LIMIT,
|
||||
}
|
||||
truncated, total_chars, returned_chars, preview = build_preview_payload(data, max_chars)
|
||||
result.update(
|
||||
{
|
||||
"truncated": truncated,
|
||||
"total_chars": total_chars,
|
||||
"returned_chars": returned_chars,
|
||||
"data_preview" if truncated else "data": (preview if truncated else data),
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
357
app/application/plugin/management.py
Normal file
357
app/application/plugin/management.py
Normal file
@@ -0,0 +1,357 @@
|
||||
"""插件目录、生命周期和数据投影应用能力。"""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from anyio import to_thread
|
||||
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.plugin.gateway import get_plugin_install_service
|
||||
from app.application.plugin.runtime import get_plugin_manager
|
||||
from app.domain.plugin import is_local_plugin_source
|
||||
from app.schemas.plugin import PluginRuntimeStatus
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
DEFAULT_PLUGIN_CANDIDATE_LIMIT = 50
|
||||
MAX_PLUGIN_CANDIDATE_LIMIT = 200
|
||||
|
||||
|
||||
def get_plugin_snapshot(plugin_id: str) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
获取已安装插件的基础信息快照。
|
||||
"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
for plugin in plugin_manager.get_local_plugins():
|
||||
if plugin.id == plugin_id:
|
||||
return {
|
||||
"plugin_id": plugin.id,
|
||||
"plugin_name": plugin.plugin_name,
|
||||
"plugin_version": plugin.plugin_version,
|
||||
"state": plugin.state,
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def refresh_plugin_registrations(plugin_id: str) -> None:
|
||||
"""重新注册插件的定时任务、命令和动态 API 路由。"""
|
||||
# 这些依赖只在真正执行重载时才导入,避免普通查询工具引入不必要的初始化开销。
|
||||
from app.application.commands import init_commands
|
||||
from app.application.plugin.routes import register_plugin_api
|
||||
from app.application.scheduling import update_plugin_job
|
||||
|
||||
update_plugin_job(plugin_id)
|
||||
init_commands(plugin_id)
|
||||
register_plugin_api(plugin_id)
|
||||
|
||||
|
||||
def reload_plugin_runtime(plugin_id: str) -> PluginRuntimeStatus:
|
||||
"""重载插件实例并重新注册其命令、定时任务和 API。"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
with plugin_manager.mutation(f"重载插件 {plugin_id}"):
|
||||
runtime_status = plugin_manager.reload_plugin(plugin_id)
|
||||
refresh_plugin_registrations(plugin_id)
|
||||
return runtime_status
|
||||
|
||||
|
||||
def summarize_plugin(plugin: Any) -> dict[str, Any]:
|
||||
"""
|
||||
提取插件对象中对 Agent 有价值的摘要字段。
|
||||
"""
|
||||
repo_url = getattr(plugin, "repo_url", None)
|
||||
return {
|
||||
"id": getattr(plugin, "id", None),
|
||||
"plugin_name": getattr(plugin, "plugin_name", None),
|
||||
"plugin_desc": getattr(plugin, "plugin_desc", None),
|
||||
"plugin_version": getattr(plugin, "plugin_version", None),
|
||||
"plugin_author": getattr(plugin, "plugin_author", None),
|
||||
"installed": bool(getattr(plugin, "installed", False)),
|
||||
"has_update": bool(getattr(plugin, "has_update", False)),
|
||||
"system_version_compatible": getattr(plugin, "system_version_compatible", True) is not False,
|
||||
"system_version": getattr(plugin, "system_version", None),
|
||||
"system_version_message": getattr(plugin, "system_version_message", None),
|
||||
"state": bool(getattr(plugin, "state", False)),
|
||||
"repo_url": repo_url,
|
||||
"source": "local_repo" if is_local_plugin_source(repo_url) else "market",
|
||||
}
|
||||
|
||||
|
||||
def _merge_plugin_source_metadata(plugin: Any, source_plugin: Any) -> Any:
|
||||
"""
|
||||
将插件市场或本地仓库中的来源元数据合并到已安装插件对象。
|
||||
"""
|
||||
repo_url = getattr(source_plugin, "repo_url", None)
|
||||
if repo_url:
|
||||
setattr(plugin, "repo_url", repo_url)
|
||||
|
||||
for attr in (
|
||||
"has_update",
|
||||
"release",
|
||||
"system_version",
|
||||
"system_version_compatible",
|
||||
"system_version_message",
|
||||
):
|
||||
value = getattr(source_plugin, attr, None)
|
||||
if value is not None:
|
||||
setattr(plugin, attr, value)
|
||||
|
||||
return plugin
|
||||
|
||||
|
||||
def _map_plugins_by_id(plugins: list[Any]) -> dict[str, Any]:
|
||||
"""
|
||||
按插件 ID 建立稳定映射,保留同 ID 首个候选来源。
|
||||
"""
|
||||
plugin_map: dict[str, Any] = {}
|
||||
for plugin in plugins:
|
||||
plugin_id = getattr(plugin, "id", None)
|
||||
if plugin_id and plugin_id not in plugin_map:
|
||||
plugin_map[plugin_id] = plugin
|
||||
return plugin_map
|
||||
|
||||
|
||||
async def enrich_installed_plugin_sources(
|
||||
installed_plugins: list[Any],
|
||||
force_refresh: bool = False,
|
||||
) -> list[Any]:
|
||||
"""
|
||||
为已安装插件补齐安装来源仓库地址。
|
||||
|
||||
本地插件对象只包含运行目录中的静态元数据,通常没有 repo_url。这里按需从
|
||||
本地插件仓库和插件市场补齐来源,保证 Agent 后续安装、升级判断可以拿到仓库地址。
|
||||
"""
|
||||
missing_source_plugins = [plugin for plugin in installed_plugins if not getattr(plugin, "repo_url", None)]
|
||||
if not missing_source_plugins:
|
||||
return installed_plugins
|
||||
|
||||
plugin_manager = get_plugin_manager()
|
||||
local_repo_map = _map_plugins_by_id(plugin_manager.get_local_repo_plugins())
|
||||
for plugin in missing_source_plugins:
|
||||
source_plugin = local_repo_map.get(getattr(plugin, "id", None))
|
||||
if source_plugin:
|
||||
_merge_plugin_source_metadata(plugin, source_plugin)
|
||||
|
||||
missing_source_plugins = [plugin for plugin in installed_plugins if not getattr(plugin, "repo_url", None)]
|
||||
if not missing_source_plugins:
|
||||
return installed_plugins
|
||||
|
||||
market_plugins = await plugin_manager.async_get_online_plugins(force=force_refresh)
|
||||
market_map = _map_plugins_by_id(market_plugins or [])
|
||||
for plugin in missing_source_plugins:
|
||||
source_plugin = market_map.get(getattr(plugin, "id", None))
|
||||
if source_plugin:
|
||||
_merge_plugin_source_metadata(plugin, source_plugin)
|
||||
|
||||
return installed_plugins
|
||||
|
||||
|
||||
async def load_market_plugins(force_refresh: bool = False) -> list[Any]:
|
||||
"""
|
||||
聚合插件市场与本地插件仓库中的候选插件。
|
||||
"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
online_plugins = await plugin_manager.async_get_online_plugins(force=force_refresh)
|
||||
local_repo_plugins = plugin_manager.get_local_repo_plugins()
|
||||
if not online_plugins and not local_repo_plugins:
|
||||
return []
|
||||
return plugin_manager.process_plugins_list(online_plugins + local_repo_plugins, [])
|
||||
|
||||
|
||||
def list_installed_plugins() -> list[Any]:
|
||||
"""
|
||||
返回当前已安装插件列表。
|
||||
"""
|
||||
plugin_manager = get_plugin_manager()
|
||||
return [plugin for plugin in plugin_manager.get_local_plugins() if plugin.installed]
|
||||
|
||||
|
||||
def _normalize_text(value: Optional[str]) -> str:
|
||||
return (value or "").strip().lower()
|
||||
|
||||
|
||||
def is_exact_plugin_match(plugin: Any, query: str) -> bool:
|
||||
"""
|
||||
精确匹配插件 ID 或插件名称,用于安全地自动选择候选。
|
||||
"""
|
||||
normalized_query = _normalize_text(query)
|
||||
return normalized_query in {
|
||||
_normalize_text(getattr(plugin, "id", None)),
|
||||
_normalize_text(getattr(plugin, "plugin_name", None)),
|
||||
}
|
||||
|
||||
|
||||
def search_plugin_candidates(query: str, plugins: list[Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按插件 ID、名称、描述和作者搜索候选,并返回打分结果。
|
||||
"""
|
||||
normalized_query = _normalize_text(query)
|
||||
if not normalized_query:
|
||||
return []
|
||||
|
||||
tokens = [token for token in normalized_query.replace("-", " ").split() if token]
|
||||
matches: list[dict[str, Any]] = []
|
||||
|
||||
for plugin in plugins:
|
||||
plugin_id = _normalize_text(getattr(plugin, "id", None))
|
||||
plugin_name = _normalize_text(getattr(plugin, "plugin_name", None))
|
||||
plugin_desc = _normalize_text(getattr(plugin, "plugin_desc", None))
|
||||
plugin_author = _normalize_text(getattr(plugin, "plugin_author", None))
|
||||
haystack = "\n".join([plugin_id, plugin_name, plugin_desc, plugin_author])
|
||||
|
||||
score = 0
|
||||
if normalized_query == plugin_id:
|
||||
score = 100
|
||||
elif normalized_query == plugin_name:
|
||||
score = 95
|
||||
elif plugin_id.startswith(normalized_query):
|
||||
score = 85
|
||||
elif plugin_name.startswith(normalized_query):
|
||||
score = 80
|
||||
elif normalized_query in plugin_id:
|
||||
score = 75
|
||||
elif normalized_query in plugin_name:
|
||||
score = 70
|
||||
elif tokens and all(token in plugin_name for token in tokens):
|
||||
score = 68
|
||||
elif tokens and all(token in plugin_id for token in tokens):
|
||||
score = 66
|
||||
elif normalized_query in plugin_desc:
|
||||
score = 45
|
||||
elif normalized_query in plugin_author:
|
||||
score = 40
|
||||
elif tokens and all(token in haystack for token in tokens):
|
||||
score = 35
|
||||
|
||||
if score <= 0:
|
||||
continue
|
||||
|
||||
matches.append(
|
||||
{
|
||||
"plugin": plugin,
|
||||
"score": score,
|
||||
"exact": is_exact_plugin_match(plugin, normalized_query),
|
||||
}
|
||||
)
|
||||
|
||||
return sorted(
|
||||
matches,
|
||||
key=lambda item: (
|
||||
-item["score"],
|
||||
not item["exact"],
|
||||
-int(bool(getattr(item["plugin"], "has_update", False))),
|
||||
-int(bool(getattr(item["plugin"], "installed", False))),
|
||||
-int(getattr(item["plugin"], "add_time", 0) or 0),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def summarize_candidates(
|
||||
matches: list[dict[str, Any]], limit: int = DEFAULT_PLUGIN_CANDIDATE_LIMIT
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
压缩候选列表,避免一次性把完整市场数据返回给 Agent。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
**summarize_plugin(item["plugin"]),
|
||||
"score": item["score"],
|
||||
"exact": item["exact"],
|
||||
}
|
||||
for item in matches[:limit]
|
||||
]
|
||||
|
||||
|
||||
async def install_plugin_runtime(
|
||||
plugin_id: str,
|
||||
repo_url: Optional[str],
|
||||
force: bool = False,
|
||||
*,
|
||||
explicit_source: bool = False,
|
||||
) -> tuple[bool, str, bool]:
|
||||
"""
|
||||
按现有插件接口的行为安装插件,并刷新运行态注册信息。
|
||||
"""
|
||||
result = await get_plugin_install_service().install(
|
||||
plugin_id=plugin_id,
|
||||
repo_url=repo_url or None,
|
||||
force=force,
|
||||
explicit_source=explicit_source,
|
||||
)
|
||||
return result.success, result.message, result.refreshed_only
|
||||
|
||||
|
||||
async def inspect_plugin_sources(
|
||||
plugin_id: str,
|
||||
*,
|
||||
force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""返回 Agent 可展示的脱敏来源候选与当前准入状态。"""
|
||||
inspection = await get_plugin_install_service().inspect_source(
|
||||
plugin_id=plugin_id,
|
||||
force=force,
|
||||
)
|
||||
candidates = [candidate.public_dict() for candidate in inspection.online_candidates]
|
||||
if inspection.local_candidate is not None:
|
||||
candidates.append(inspection.local_candidate.public_dict())
|
||||
return {
|
||||
"selection_status": inspection.selection.status.value,
|
||||
"selection_reason": inspection.selection.reason,
|
||||
"inventory_complete": inspection.inventory_complete,
|
||||
"candidates": candidates,
|
||||
}
|
||||
|
||||
|
||||
async def uninstall_plugin_runtime(plugin_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
按现有卸载逻辑移除插件,并清理运行态注册与分组信息。
|
||||
"""
|
||||
from app.application.plugin.folders import remove_plugin_from_folders
|
||||
from app.application.plugin.routes import remove_plugin_api
|
||||
from app.application.scheduling import remove_plugin_job
|
||||
|
||||
plugin_manager = get_plugin_manager()
|
||||
with plugin_manager.mutation(f"卸载插件 {plugin_id}"):
|
||||
virtual_instance = plugin_manager.get_plugin_instance(plugin_id)
|
||||
source_instances = plugin_manager.get_plugin_source_instances(plugin_id)
|
||||
if not virtual_instance and source_instances:
|
||||
instance_ids = "、".join(item.instance_id for item in source_instances)
|
||||
raise ValueError(f"请先卸载该插件的分身:{instance_ids}")
|
||||
|
||||
config_oper = get_configured_system_config()
|
||||
install_plugins = config_oper.get(SystemConfigKey.UserInstalledPlugins) or []
|
||||
if plugin_id in install_plugins:
|
||||
install_plugins = [plugin for plugin in install_plugins if plugin != plugin_id]
|
||||
await config_oper.async_set(
|
||||
SystemConfigKey.UserInstalledPlugins,
|
||||
install_plugins,
|
||||
)
|
||||
|
||||
remove_plugin_api(plugin_id)
|
||||
remove_plugin_job(plugin_id)
|
||||
|
||||
plugin_class = plugin_manager.plugins.get(plugin_id)
|
||||
was_clone = bool(getattr(plugin_class, "is_clone", False))
|
||||
clone_files_removed = False
|
||||
|
||||
if virtual_instance:
|
||||
plugin_manager.delete_plugin_config(plugin_id, force=True)
|
||||
plugin_manager.delete_plugin_data(plugin_id, force=True)
|
||||
plugin_manager.delete_plugin_instance(plugin_id)
|
||||
elif was_clone:
|
||||
plugin_manager.delete_plugin_config(plugin_id)
|
||||
plugin_manager.delete_plugin_data(plugin_id)
|
||||
try:
|
||||
clone_files_removed = await to_thread.run_sync(
|
||||
plugin_manager.remove_plugin_package,
|
||||
plugin_id,
|
||||
)
|
||||
if clone_files_removed:
|
||||
plugin_manager.plugins.pop(plugin_id, None)
|
||||
except Exception:
|
||||
clone_files_removed = False
|
||||
|
||||
remove_plugin_from_folders(plugin_id)
|
||||
plugin_manager.remove_plugin(plugin_id)
|
||||
|
||||
return {
|
||||
"was_clone": was_clone,
|
||||
"clone_files_removed": clone_files_removed,
|
||||
}
|
||||
66
app/application/security/secrets.py
Normal file
66
app/application/security/secrets.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""跨 API、Agent 和宿主回执使用的敏感字段身份判定。"""
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
_MAX_FIELD_NAME_CHARS = 256
|
||||
_ACRONYM_BOUNDARY_PATTERN = re.compile(r"(?<=[A-Z])(?=[A-Z][a-z])")
|
||||
_CAMEL_CASE_BOUNDARY_PATTERN = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
|
||||
_SECRET_FIELD_NAMES = frozenset(
|
||||
{
|
||||
"access_token",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"api_token",
|
||||
"auth_header",
|
||||
"authorization",
|
||||
"client_secret",
|
||||
"cookie",
|
||||
"passkey",
|
||||
"passwd",
|
||||
"password",
|
||||
"private_key",
|
||||
"pwd",
|
||||
"refresh_token",
|
||||
"secret",
|
||||
"secret_access_key",
|
||||
"secret_key",
|
||||
"token",
|
||||
}
|
||||
)
|
||||
_SECRET_FIELD_ENDINGS = tuple(f"_{name}" for name in _SECRET_FIELD_NAMES)
|
||||
_SECRET_SETTING_NAMES = frozenset(
|
||||
{
|
||||
# CookieCloud 的用户 key 没有类型后缀,但与密码共同构成端到端加密凭据。
|
||||
"cookiecloud_key",
|
||||
}
|
||||
)
|
||||
_SECRET_SETTING_ENDINGS = ("_encrypt_key",)
|
||||
|
||||
|
||||
def _normalize_field_name(value: Any) -> str:
|
||||
"""将短字段名规范化为 snake_case,非字符串不参与身份推导。"""
|
||||
if type(value) is not str:
|
||||
return ""
|
||||
text = value.strip()
|
||||
if len(text) > _MAX_FIELD_NAME_CHARS:
|
||||
text = text[-_MAX_FIELD_NAME_CHARS:]
|
||||
text = _ACRONYM_BOUNDARY_PATTERN.sub("_", text)
|
||||
text = _CAMEL_CASE_BOUNDARY_PATTERN.sub("_", text)
|
||||
return re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")
|
||||
|
||||
|
||||
def is_secret_setting_key(key: Any) -> bool:
|
||||
"""按完整字段或类型后缀识别凭据,避免误伤 token 统计与过期配置。"""
|
||||
normalized = _normalize_field_name(key)
|
||||
if not normalized:
|
||||
return False
|
||||
return (
|
||||
normalized in _SECRET_FIELD_NAMES
|
||||
or normalized in _SECRET_SETTING_NAMES
|
||||
or normalized.endswith(_SECRET_FIELD_ENDINGS)
|
||||
or normalized.endswith(_SECRET_SETTING_ENDINGS)
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["is_secret_setting_key"]
|
||||
633
app/application/settings.py
Normal file
633
app/application/settings.py
Normal file
@@ -0,0 +1,633 @@
|
||||
"""系统设置元数据、查询更新语义和敏感值脱敏能力。"""
|
||||
|
||||
import copy
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.application.configuration import (
|
||||
RuntimeSettingsService,
|
||||
SystemConfigService,
|
||||
)
|
||||
from app.application.plugin.runtime import plugin_system_config_mutation
|
||||
from app.application.security.secrets import is_secret_setting_key
|
||||
from app.runtime.config import Settings
|
||||
from app.schemas.types import SystemConfigKey
|
||||
|
||||
SystemSettingPublisher = Callable[[Any, Any], Awaitable[None]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SettingSpec:
|
||||
"""描述一个可被 Agent 读写的系统设置项。"""
|
||||
|
||||
key: str
|
||||
source: str
|
||||
group: str
|
||||
label: str
|
||||
systemconfig_key: Optional[SystemConfigKey] = None
|
||||
|
||||
|
||||
SYSTEMCONFIG_SETTING_METADATA = {
|
||||
SystemConfigKey.Downloaders.value: {
|
||||
"group": "downloaders",
|
||||
"label": "下载器配置",
|
||||
},
|
||||
SystemConfigKey.MediaServers.value: {
|
||||
"group": "media_servers",
|
||||
"label": "媒体服务器配置",
|
||||
},
|
||||
SystemConfigKey.Notifications.value: {
|
||||
"group": "notifications",
|
||||
"label": "消息通知配置",
|
||||
},
|
||||
SystemConfigKey.NotificationSwitchs.value: {
|
||||
"group": "notification_switches",
|
||||
"label": "通知场景开关",
|
||||
},
|
||||
SystemConfigKey.Directories.value: {
|
||||
"group": "directories",
|
||||
"label": "目录配置",
|
||||
},
|
||||
SystemConfigKey.Storages.value: {
|
||||
"group": "storages",
|
||||
"label": "存储配置",
|
||||
},
|
||||
SystemConfigKey.IndexerSites.value: {
|
||||
"group": "search_sites",
|
||||
"label": "搜索站点范围",
|
||||
},
|
||||
SystemConfigKey.RssSites.value: {
|
||||
"group": "subscribe_sites",
|
||||
"label": "订阅站点范围",
|
||||
},
|
||||
SystemConfigKey.UserSiteAuthParams.value: {
|
||||
"group": "site_auth",
|
||||
"label": "站点认证参数",
|
||||
},
|
||||
SystemConfigKey.AIAgentConfig.value: {
|
||||
"group": "ai_agent",
|
||||
"label": "AI 智能体配置",
|
||||
},
|
||||
SystemConfigKey.AIAgentMcpServers.value: {
|
||||
"group": "ai_agent",
|
||||
"label": "AI 智能体外部 MCP 服务器",
|
||||
},
|
||||
SystemConfigKey.CustomIdentifiers.value: {
|
||||
"group": "custom_identifiers",
|
||||
"label": "自定义识别词",
|
||||
},
|
||||
SystemConfigKey.EpisodeFormatRuleTable.value: {
|
||||
"group": "transfer",
|
||||
"label": "集数定位规则词表",
|
||||
},
|
||||
SystemConfigKey.CustomReleaseGroups.value: {
|
||||
"group": "customization",
|
||||
"label": "自定义制作组/字幕组",
|
||||
},
|
||||
SystemConfigKey.Customization.value: {
|
||||
"group": "customization",
|
||||
"label": "自定义占位符",
|
||||
},
|
||||
SystemConfigKey.TransferExcludeWords.value: {
|
||||
"group": "transfer",
|
||||
"label": "整理屏蔽词",
|
||||
},
|
||||
SystemConfigKey.TorrentsPriority.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "种子优先级规则",
|
||||
},
|
||||
SystemConfigKey.CustomFilterRules.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "用户自定义规则",
|
||||
},
|
||||
SystemConfigKey.UserFilterRuleGroups.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "用户规则组",
|
||||
},
|
||||
SystemConfigKey.SearchFilterRuleGroups.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "搜索默认过滤规则组",
|
||||
},
|
||||
SystemConfigKey.SubscribeFilterRuleGroups.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "订阅默认过滤规则组",
|
||||
},
|
||||
SystemConfigKey.BestVersionFilterRuleGroups.value: {
|
||||
"group": "filter_rules",
|
||||
"label": "洗版默认过滤规则组",
|
||||
},
|
||||
SystemConfigKey.SubscribeDefaultParams.value: {
|
||||
"group": "subscribe_defaults",
|
||||
"label": "订阅默认参数",
|
||||
},
|
||||
SystemConfigKey.DefaultMovieSubscribeConfig.value: {
|
||||
"group": "subscribe_defaults",
|
||||
"label": "默认电影订阅规则",
|
||||
},
|
||||
SystemConfigKey.DefaultTvSubscribeConfig.value: {
|
||||
"group": "subscribe_defaults",
|
||||
"label": "默认电视剧订阅规则",
|
||||
},
|
||||
SystemConfigKey.DefaultMusicSubscribeConfig.value: {
|
||||
"group": "subscribe_defaults",
|
||||
"label": "默认音乐订阅规则",
|
||||
},
|
||||
SystemConfigKey.UserInstalledPlugins.value: {
|
||||
"group": "plugins",
|
||||
"label": "已安装插件列表",
|
||||
},
|
||||
SystemConfigKey.PluginFolders.value: {
|
||||
"group": "plugins",
|
||||
"label": "插件文件夹分组配置",
|
||||
},
|
||||
SystemConfigKey.PluginInstallReport.value: {
|
||||
"group": "plugins",
|
||||
"label": "插件安装统计",
|
||||
},
|
||||
SystemConfigKey.NotificationSendTime.value: {
|
||||
"group": "notifications",
|
||||
"label": "通知发送时间",
|
||||
},
|
||||
SystemConfigKey.NotificationTemplates.value: {
|
||||
"group": "notifications",
|
||||
"label": "通知模板",
|
||||
},
|
||||
SystemConfigKey.ScrapingSwitchs.value: {
|
||||
"group": "scraping",
|
||||
"label": "刮削开关设置",
|
||||
},
|
||||
SystemConfigKey.FollowSubscribers.value: {
|
||||
"group": "subscribe_sites",
|
||||
"label": "Follow 订阅分享者",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
LIST_ITEM_MATCH_FIELD_DEFAULTS = {
|
||||
SystemConfigKey.Downloaders.value: "name",
|
||||
SystemConfigKey.MediaServers.value: "name",
|
||||
SystemConfigKey.Notifications.value: "name",
|
||||
SystemConfigKey.NotificationSwitchs.value: "type",
|
||||
SystemConfigKey.Directories.value: "name",
|
||||
SystemConfigKey.Storages.value: "name",
|
||||
}
|
||||
|
||||
|
||||
GROUP_ALIASES = {
|
||||
"all": "all",
|
||||
"全部": "all",
|
||||
"settings": "settings",
|
||||
"basic": "settings",
|
||||
"基础设置": "settings",
|
||||
"基础配置": "settings",
|
||||
"systemconfig": "systemconfig",
|
||||
"system_config": "systemconfig",
|
||||
"系统设置": "systemconfig",
|
||||
"系统配置": "systemconfig",
|
||||
"downloaders": "downloaders",
|
||||
"downloader": "downloaders",
|
||||
"下载器": "downloaders",
|
||||
"media_servers": "media_servers",
|
||||
"mediaservers": "media_servers",
|
||||
"media-servers": "media_servers",
|
||||
"媒体服务器": "media_servers",
|
||||
"notifications": "notifications",
|
||||
"notification": "notifications",
|
||||
"消息通知": "notifications",
|
||||
"通知": "notifications",
|
||||
"notification_switches": "notification_switches",
|
||||
"notification_switchs": "notification_switches",
|
||||
"通知开关": "notification_switches",
|
||||
"storages": "storages",
|
||||
"storage": "storages",
|
||||
"存储": "storages",
|
||||
"directories": "directories",
|
||||
"directory": "directories",
|
||||
"目录": "directories",
|
||||
"search_sites": "search_sites",
|
||||
"indexer_sites": "search_sites",
|
||||
"搜索站点": "search_sites",
|
||||
"subscribe_sites": "subscribe_sites",
|
||||
"rss_sites": "subscribe_sites",
|
||||
"订阅站点": "subscribe_sites",
|
||||
"site_auth": "site_auth",
|
||||
"site_auth_params": "site_auth",
|
||||
"站点认证": "site_auth",
|
||||
"ai_agent": "ai_agent",
|
||||
"agent": "ai_agent",
|
||||
"智能体": "ai_agent",
|
||||
"custom_identifiers": "custom_identifiers",
|
||||
"自定义识别词": "custom_identifiers",
|
||||
"filter_rules": "filter_rules",
|
||||
"过滤规则": "filter_rules",
|
||||
"subscribe_defaults": "subscribe_defaults",
|
||||
"订阅默认": "subscribe_defaults",
|
||||
"plugins": "plugins",
|
||||
"插件": "plugins",
|
||||
"customization": "customization",
|
||||
"自定义": "customization",
|
||||
"transfer": "transfer",
|
||||
"整理": "transfer",
|
||||
"scraping": "scraping",
|
||||
"刮削": "scraping",
|
||||
"misc": "misc",
|
||||
"其他": "misc",
|
||||
}
|
||||
|
||||
|
||||
# 这些前缀共同组成可启动、推理和扩展 AI Agent 的同一业务配置域。
|
||||
AI_AGENT_CORE_SETTING_PREFIXES = (
|
||||
"AI_AGENT_",
|
||||
"LLM_",
|
||||
"AUDIO_INPUT_",
|
||||
"AUDIO_OUTPUT_",
|
||||
"AI_RECOMMEND_",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_token(value: str) -> str:
|
||||
return str(value).strip().lower().replace("-", "_")
|
||||
|
||||
|
||||
def _resolve_core_setting_group(key: str) -> str:
|
||||
"""根据基础设置的业务归属返回 Agent 可查询的分类。"""
|
||||
|
||||
if key.startswith(AI_AGENT_CORE_SETTING_PREFIXES):
|
||||
return "ai_agent"
|
||||
return "settings"
|
||||
|
||||
|
||||
def _build_specs() -> tuple[dict[str, SettingSpec], dict[str, SettingSpec]]:
|
||||
core_specs = {
|
||||
key: SettingSpec(
|
||||
key=key,
|
||||
source="settings",
|
||||
group=_resolve_core_setting_group(key),
|
||||
label=key,
|
||||
)
|
||||
for key in Settings.model_fields.keys()
|
||||
}
|
||||
system_specs = {}
|
||||
for item in SystemConfigKey:
|
||||
metadata = SYSTEMCONFIG_SETTING_METADATA.get(item.value, {})
|
||||
system_specs[item.value] = SettingSpec(
|
||||
key=item.value,
|
||||
source="systemconfig",
|
||||
group=metadata.get("group", "misc"),
|
||||
label=metadata.get("label", item.value),
|
||||
systemconfig_key=item,
|
||||
)
|
||||
return core_specs, system_specs
|
||||
|
||||
|
||||
CORE_SETTING_SPECS, SYSTEMCONFIG_SETTING_SPECS = _build_specs()
|
||||
ALL_SETTING_SPECS = {**CORE_SETTING_SPECS, **SYSTEMCONFIG_SETTING_SPECS}
|
||||
|
||||
|
||||
SETTING_KEY_ALIASES = {}
|
||||
for key in CORE_SETTING_SPECS:
|
||||
SETTING_KEY_ALIASES[_normalize_token(key)] = key
|
||||
for item in SystemConfigKey:
|
||||
SETTING_KEY_ALIASES[_normalize_token(item.value)] = item.value
|
||||
SETTING_KEY_ALIASES[_normalize_token(item.name)] = item.value
|
||||
|
||||
SINGLE_KEY_GROUP_ALIASES = {
|
||||
_normalize_token(alias): next(
|
||||
(spec.key for spec in ALL_SETTING_SPECS.values() if spec.group == canonical_group),
|
||||
None,
|
||||
)
|
||||
for alias, canonical_group in GROUP_ALIASES.items()
|
||||
if canonical_group not in {"all", "settings", "systemconfig"}
|
||||
and len([spec.key for spec in ALL_SETTING_SPECS.values() if spec.group == canonical_group]) == 1
|
||||
}
|
||||
|
||||
|
||||
def normalize_group(group: Optional[str]) -> str:
|
||||
if not group:
|
||||
return "all"
|
||||
normalized = GROUP_ALIASES.get(_normalize_token(group))
|
||||
if not normalized:
|
||||
raise ValueError(
|
||||
"group 不支持,支持值包括 all/settings/systemconfig 以及"
|
||||
" downloaders、media_servers、notifications、storages、directories、"
|
||||
"search_sites、subscribe_sites、site_auth、ai_agent 等分类别名"
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def resolve_setting_spec(setting_key: Optional[str]) -> Optional[SettingSpec]:
|
||||
"""把精确键名、枚举名或单键分组别名解析为统一的设置定义。"""
|
||||
|
||||
if not setting_key:
|
||||
return None
|
||||
|
||||
normalized = _normalize_token(setting_key)
|
||||
resolved_key = SETTING_KEY_ALIASES.get(normalized) or SINGLE_KEY_GROUP_ALIASES.get(normalized)
|
||||
if not resolved_key:
|
||||
return None
|
||||
return ALL_SETTING_SPECS.get(resolved_key)
|
||||
|
||||
|
||||
def list_setting_specs(group: Optional[str] = "all", keyword: Optional[str] = None) -> list[SettingSpec]:
|
||||
"""按分组和关键字筛选可查询的设置项。"""
|
||||
|
||||
normalized_group = normalize_group(group)
|
||||
if normalized_group == "all":
|
||||
specs = list(ALL_SETTING_SPECS.values())
|
||||
elif normalized_group == "settings":
|
||||
specs = list(CORE_SETTING_SPECS.values())
|
||||
elif normalized_group == "systemconfig":
|
||||
specs = list(SYSTEMCONFIG_SETTING_SPECS.values())
|
||||
else:
|
||||
specs = [spec for spec in ALL_SETTING_SPECS.values() if spec.group == normalized_group]
|
||||
|
||||
if keyword:
|
||||
normalized_keyword = _normalize_token(keyword)
|
||||
specs = [
|
||||
spec
|
||||
for spec in specs
|
||||
if normalized_keyword in _normalize_token(spec.key)
|
||||
or normalized_keyword in _normalize_token(spec.group)
|
||||
or normalized_keyword in _normalize_token(spec.label)
|
||||
]
|
||||
|
||||
return sorted(specs, key=lambda spec: (spec.source, spec.group, spec.key))
|
||||
|
||||
|
||||
def get_default_list_match_field(setting_key: str) -> Optional[str]:
|
||||
return LIST_ITEM_MATCH_FIELD_DEFAULTS.get(setting_key)
|
||||
|
||||
|
||||
def redact_secret_value(value: Any, *, redact_scalar: bool = False) -> Any:
|
||||
"""递归脱敏配置值中的密钥、Cookie、Token 等敏感字段。"""
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
key: "***" if is_secret_setting_key(str(key)) else redact_secret_value(item, redact_scalar=redact_scalar)
|
||||
for key, item in value.items()
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [redact_secret_value(item, redact_scalar=redact_scalar) for item in value]
|
||||
if isinstance(value, str):
|
||||
return "***" if value and redact_scalar else value
|
||||
return value
|
||||
|
||||
|
||||
def should_redact_setting(spec: SettingSpec, value: Any) -> bool:
|
||||
"""判断某项设置在默认查询响应中是否需要脱敏。"""
|
||||
if is_secret_setting_key(spec.key):
|
||||
return True
|
||||
if isinstance(value, dict):
|
||||
return any(is_secret_setting_key(str(key)) for key in value.keys())
|
||||
if isinstance(value, list):
|
||||
return any(should_redact_setting(spec, item) for item in value if isinstance(item, dict))
|
||||
return False
|
||||
|
||||
|
||||
class SystemSettingsService:
|
||||
"""提供 Agent 与管理 API 共用的受控系统设置查询和更新。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
runtime_settings: RuntimeSettingsService,
|
||||
system_config: SystemConfigService,
|
||||
publish_config_changed: SystemSettingPublisher,
|
||||
) -> None:
|
||||
"""注入部署设置、持久化配置和配置事件发布端口。"""
|
||||
self._runtime_settings = runtime_settings
|
||||
self._system_config = system_config
|
||||
self._publish_config_changed = publish_config_changed
|
||||
|
||||
def _load(self, spec: SettingSpec) -> Any:
|
||||
"""按设置来源读取当前值。"""
|
||||
if spec.source == "settings":
|
||||
return self._runtime_settings.get(spec.key)
|
||||
return self._system_config.get(spec.systemconfig_key)
|
||||
|
||||
@staticmethod
|
||||
def _summarize(value: Any, *, redacted: bool = False) -> dict[str, Any]:
|
||||
"""生成有界值摘要,避免配置列表和字典挤占响应上下文。"""
|
||||
summary: dict[str, Any] = {
|
||||
"has_value": value is not None,
|
||||
"value_type": type(value).__name__,
|
||||
"redacted": redacted,
|
||||
}
|
||||
if isinstance(value, list):
|
||||
summary["item_count"] = len(value)
|
||||
if value:
|
||||
summary["item_type"] = type(value[0]).__name__
|
||||
elif isinstance(value, dict):
|
||||
keys = list(value)
|
||||
summary["item_count"] = len(keys)
|
||||
summary["keys_preview"] = keys[:10]
|
||||
summary["keys_truncated"] = len(keys) > 10
|
||||
elif isinstance(value, str):
|
||||
summary["length"] = len(value)
|
||||
summary["value_preview"] = value[:200]
|
||||
summary["value_truncated"] = len(value) > 200
|
||||
elif value is not None:
|
||||
summary["value_preview"] = value
|
||||
return summary
|
||||
|
||||
def query(
|
||||
self,
|
||||
*,
|
||||
setting_key: Optional[str] = None,
|
||||
group: Optional[str] = "all",
|
||||
keyword: Optional[str] = None,
|
||||
include_values: Optional[bool] = None,
|
||||
show_secrets: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""查询登记设置,并在未授权明文读取时递归脱敏。"""
|
||||
if setting_key:
|
||||
spec = resolve_setting_spec(setting_key)
|
||||
if spec is None:
|
||||
raise ValueError(f"系统设置项 '{setting_key}' 不存在")
|
||||
specs = [spec]
|
||||
else:
|
||||
specs = list_setting_specs(group=group, keyword=keyword)
|
||||
if not specs:
|
||||
raise ValueError("没有找到匹配的系统设置项")
|
||||
should_include_values = include_values if include_values is not None else len(specs) == 1
|
||||
payload = []
|
||||
for spec in specs:
|
||||
value = self._load(spec)
|
||||
redacted = should_redact_setting(spec, value) and not show_secrets
|
||||
response_value = (
|
||||
redact_secret_value(
|
||||
value,
|
||||
redact_scalar=is_secret_setting_key(spec.key),
|
||||
)
|
||||
if redacted
|
||||
else value
|
||||
)
|
||||
item = {
|
||||
"setting_key": spec.key,
|
||||
"source": spec.source,
|
||||
"group": spec.group,
|
||||
"label": spec.label,
|
||||
**self._summarize(response_value, redacted=redacted),
|
||||
}
|
||||
if should_include_values:
|
||||
item["value"] = response_value
|
||||
payload.append(item)
|
||||
return {
|
||||
"matched_count": len(payload),
|
||||
"include_values": should_include_values,
|
||||
"show_secrets": show_secrets,
|
||||
"settings": payload,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_systemconfig_value(value: Any) -> Any:
|
||||
"""将只含空项的列表折叠为空配置。"""
|
||||
if isinstance(value, list):
|
||||
filtered = [item for item in value if item is not None]
|
||||
return filtered or None
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _resolve_list_match(
|
||||
spec: SettingSpec,
|
||||
operation: str,
|
||||
value: Any,
|
||||
match_field: Optional[str],
|
||||
match_value: Any,
|
||||
) -> tuple[Optional[str], Any]:
|
||||
"""解析列表项修改使用的稳定匹配字段和值。"""
|
||||
resolved_field = match_field or get_default_list_match_field(spec.key)
|
||||
resolved_value = match_value
|
||||
if isinstance(value, dict):
|
||||
if not resolved_field:
|
||||
raise ValueError(f"{operation} 需要提供 match_field,或使用带默认匹配字段的系统配置项")
|
||||
if resolved_value is None:
|
||||
resolved_value = value.get(resolved_field)
|
||||
if resolved_value is None:
|
||||
raise ValueError(f"{operation} 缺少匹配值,请在 value.{resolved_field} 或 match_value 中提供")
|
||||
elif resolved_value is None:
|
||||
resolved_value = value
|
||||
return resolved_field, resolved_value
|
||||
|
||||
@classmethod
|
||||
def _prepare_next_value(
|
||||
cls,
|
||||
spec: SettingSpec,
|
||||
current_value: Any,
|
||||
value: Any,
|
||||
operation: str,
|
||||
remove_keys: Optional[list[str]],
|
||||
match_field: Optional[str],
|
||||
match_value: Any,
|
||||
) -> Any:
|
||||
"""按显式更新语义构造下一配置值。"""
|
||||
if operation == "replace":
|
||||
return value
|
||||
if operation == "merge_dict":
|
||||
if current_value is not None and not isinstance(current_value, dict):
|
||||
raise ValueError("merge_dict 仅支持当前值为 dict 的设置项")
|
||||
if value is not None and not isinstance(value, dict):
|
||||
raise ValueError("merge_dict 的 value 必须是 dict 或 null")
|
||||
next_value = dict(current_value or {})
|
||||
next_value.update(value or {})
|
||||
for key in remove_keys or []:
|
||||
next_value.pop(key, None)
|
||||
return next_value
|
||||
if operation not in {"upsert_list_item", "remove_list_item"}:
|
||||
raise ValueError(f"不支持的操作: {operation}")
|
||||
if current_value is not None and not isinstance(current_value, list):
|
||||
raise ValueError(f"{operation} 仅支持当前值为 list 的设置项")
|
||||
next_items = list(copy.deepcopy(current_value or []))
|
||||
resolved_field, resolved_value = cls._resolve_list_match(spec, operation, value, match_field, match_value)
|
||||
if operation == "upsert_list_item":
|
||||
if value is None:
|
||||
raise ValueError("upsert_list_item 必须提供 value")
|
||||
for index, item in enumerate(next_items):
|
||||
matched = (
|
||||
isinstance(item, dict) and resolved_field and item.get(resolved_field) == resolved_value
|
||||
) or (not resolved_field and item == resolved_value)
|
||||
if matched:
|
||||
next_items[index] = value
|
||||
break
|
||||
else:
|
||||
next_items.append(value)
|
||||
return next_items
|
||||
return [
|
||||
item
|
||||
for item in next_items
|
||||
if not (isinstance(item, dict) and resolved_field and item.get(resolved_field) == resolved_value)
|
||||
and not (not resolved_field and item == resolved_value)
|
||||
]
|
||||
|
||||
async def update(
|
||||
self,
|
||||
*,
|
||||
setting_key: str,
|
||||
value: Any = None,
|
||||
operation: str = "replace",
|
||||
remove_keys: Optional[list[str]] = None,
|
||||
match_field: Optional[str] = None,
|
||||
match_value: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""更新登记设置并发布统一配置变更事件。"""
|
||||
spec = resolve_setting_spec(setting_key)
|
||||
if spec is None:
|
||||
raise ValueError(f"系统设置项 '{setting_key}' 不存在")
|
||||
mutation_key = spec.systemconfig_key if spec.source == "systemconfig" else None
|
||||
with plugin_system_config_mutation(mutation_key):
|
||||
previous_value = self._load(spec)
|
||||
next_value = self._prepare_next_value(
|
||||
spec,
|
||||
previous_value,
|
||||
value,
|
||||
operation,
|
||||
remove_keys,
|
||||
match_field,
|
||||
match_value,
|
||||
)
|
||||
message = ""
|
||||
event_value = next_value
|
||||
if spec.source == "settings":
|
||||
success, message = self._runtime_settings.update(spec.key, next_value)
|
||||
if success is False:
|
||||
raise ValueError(message or f"更新设置 {spec.key} 失败")
|
||||
changed = success is True
|
||||
else:
|
||||
event_value = self._normalize_systemconfig_value(next_value)
|
||||
changed = bool(
|
||||
await self._system_config.async_set(
|
||||
spec.systemconfig_key,
|
||||
event_value,
|
||||
)
|
||||
)
|
||||
if changed:
|
||||
await self._publish_config_changed(spec.key, event_value)
|
||||
saved_value = self._load(spec)
|
||||
redact_values = should_redact_setting(spec, previous_value) or should_redact_setting(spec, saved_value)
|
||||
return {
|
||||
"message": message or (f"系统设置 {spec.key} 已更新" if changed else "配置值未发生变化"),
|
||||
"changed": changed,
|
||||
"operation": operation,
|
||||
"setting": {
|
||||
"setting_key": spec.key,
|
||||
"source": spec.source,
|
||||
"group": spec.group,
|
||||
"label": spec.label,
|
||||
},
|
||||
"values_redacted": redact_values,
|
||||
"previous_value": (
|
||||
redact_secret_value(
|
||||
previous_value,
|
||||
redact_scalar=is_secret_setting_key(spec.key),
|
||||
)
|
||||
if redact_values
|
||||
else previous_value
|
||||
),
|
||||
"saved_value": (
|
||||
redact_secret_value(
|
||||
saved_value,
|
||||
redact_scalar=is_secret_setting_key(spec.key),
|
||||
)
|
||||
if redact_values
|
||||
else saved_value
|
||||
),
|
||||
}
|
||||
@@ -19,9 +19,7 @@ from app.schemas.types import SystemConfigKey
|
||||
if TYPE_CHECKING:
|
||||
from app.application.rules import AsyncRuleGroupMutationService
|
||||
|
||||
PLUGIN_MARKET_WIKI_URL = (
|
||||
"https://raw.githubusercontent.com/jxxghp/MoviePilot-Wiki/main/plugin.md"
|
||||
)
|
||||
PLUGIN_MARKET_WIKI_URL = "https://raw.githubusercontent.com/jxxghp/MoviePilot-Wiki/main/plugin.md"
|
||||
_DATABASE_BACKUP_SETTING_KEYS = {
|
||||
"DB_BACKUP_ENABLE",
|
||||
"DB_BACKUP_CRON",
|
||||
@@ -209,6 +207,14 @@ class SystemService:
|
||||
self._plugin_mutation = plugin_mutation
|
||||
self._rule_group_mutation = rule_group_mutation
|
||||
|
||||
async def publish_config_changed(
|
||||
self,
|
||||
key: Any,
|
||||
value: JsonData = None,
|
||||
) -> None:
|
||||
"""发布一项已经持久化完成的系统配置变更。"""
|
||||
await self._events.publish(key, value)
|
||||
|
||||
async def read_log(self, logfile: str) -> str:
|
||||
"""读取日志并按旧接口语义倒序返回。"""
|
||||
text = await self._logs.read(logfile)
|
||||
@@ -261,9 +267,7 @@ class SystemService:
|
||||
if fetched.status_code is None:
|
||||
return SystemOperationResult(False, "无法访问 Wiki 插件仓库清单")
|
||||
if fetched.status_code != 200:
|
||||
return SystemOperationResult(
|
||||
False, f"访问 Wiki 插件仓库清单失败,状态码:{fetched.status_code}"
|
||||
)
|
||||
return SystemOperationResult(False, f"访问 Wiki 插件仓库清单失败,状态码:{fetched.status_code}")
|
||||
if not fetched.repos:
|
||||
return SystemOperationResult(False, "未在 Wiki 中识别到插件仓库地址")
|
||||
local_repos = self._split_repos(self.settings.get("PLUGIN_MARKET", ""))
|
||||
@@ -348,9 +352,7 @@ class SystemService:
|
||||
def upgrade(self, mode: str | None) -> SystemOperationResult:
|
||||
"""仅保留兼容的开发分支更新入口。"""
|
||||
if str(mode or "").strip().lower() != "dev":
|
||||
return SystemOperationResult(
|
||||
False, "Release 更新请使用 /system/update/check、download 和 install 接口"
|
||||
)
|
||||
return SystemOperationResult(False, "Release 更新请使用 /system/update/check、download 和 install 接口")
|
||||
if not self._control.can_restart():
|
||||
return SystemOperationResult(False, "当前运行环境不支持升级操作!")
|
||||
success, message = self._control.upgrade_dev()
|
||||
@@ -391,10 +393,8 @@ class SystemService:
|
||||
cron = str(env.get("DB_BACKUP_CRON", self.settings.get("DB_BACKUP_CRON")) or "").strip()
|
||||
if cron:
|
||||
try:
|
||||
TimerUtils.normalize_schedule_trigger(
|
||||
"cron", cron, self.settings.get("TZ")
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
TimerUtils.normalize_schedule_trigger("cron", cron, self.settings.get("TZ"))
|
||||
except TypeError, ValueError:
|
||||
return "数据库备份周期格式不正确"
|
||||
backup_path = env.get("DB_BACKUP_PATH", self.settings.get("DB_BACKUP_PATH"))
|
||||
if backup_path is not None and not isinstance(backup_path, str):
|
||||
@@ -408,7 +408,7 @@ class SystemService:
|
||||
return f"{label}必须是大于等于 0 的整数"
|
||||
try:
|
||||
converted = int(value)
|
||||
except (TypeError, ValueError):
|
||||
except TypeError, ValueError:
|
||||
return f"{label}必须是大于等于 0 的整数"
|
||||
if converted < 0 or str(value).strip() != str(converted):
|
||||
return f"{label}必须是大于等于 0 的整数"
|
||||
|
||||
Reference in New Issue
Block a user