mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-30 16:05:05 +08:00
fix(subscribe): 展开短标签过滤条件并补充批次拒绝统计 (#7644)
* fix(subscribe): 展开短标签过滤条件并补充批次拒绝统计 * fix(torrent): 兼容标题首尾特效词边界并排除 HDRip/DVD 误匹配
This commit is contained in:
@@ -6,6 +6,7 @@ from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Iterator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
@@ -45,6 +46,31 @@ def _detail_objects(details: Mapping[str, JsonData], field_name: str) -> list[di
|
||||
return [value for value in values if isinstance(value, dict)] if isinstance(values, list) else []
|
||||
|
||||
|
||||
def _sorted_reason_counts(reasons: Iterable[str]) -> dict[str, int]:
|
||||
"""
|
||||
按命中数量降序、文案升序汇总过滤拒绝原因,保持输出稳定可读。
|
||||
"""
|
||||
counts = Counter(reason for reason in reasons if reason)
|
||||
return {
|
||||
reason: count
|
||||
for reason, count in sorted(counts.items(), key=lambda item: (-item[1], item[0]))
|
||||
}
|
||||
|
||||
|
||||
def _decode_rejected_tracking(entries: Iterable[str]) -> dict[str, str]:
|
||||
"""
|
||||
从持久化去重记录还原当前仍处于拒绝状态的资源键及原因。
|
||||
"""
|
||||
restored: dict[str, str] = {}
|
||||
for entry in entries:
|
||||
if not isinstance(entry, str) or not entry:
|
||||
continue
|
||||
key, separator, reason = entry.partition(":")
|
||||
if key:
|
||||
restored[key] = reason if separator and reason else "不符合订阅筛选条件"
|
||||
return restored
|
||||
|
||||
|
||||
def activity_time() -> str:
|
||||
"""
|
||||
返回可排序的 UTC 活动时间。
|
||||
@@ -211,7 +237,8 @@ class SubscriptionActivityRun:
|
||||
self.started_at = activity_time()
|
||||
self.status = "running"
|
||||
self.finished_at: str | None = None
|
||||
self.counts: dict[str, int] = {"sites": 0, "requested_sites": 0, "discovered": 0, "related": 0, "qualified": 0, "submitted": 0,
|
||||
self.counts: dict[str, int] = {"sites": 0, "requested_sites": 0, "discovered": 0, "related": 0, "rejected": 0,
|
||||
"qualified": 0, "submitted": 0,
|
||||
"initial_submitted": 0, "upgrade_submitted": 0, "full_upgrade_submitted": 0}
|
||||
self.details: dict[str, JsonData] = {
|
||||
"rules": {key: subscribe.to_dict().get(key) for key in RULE_FIELDS},
|
||||
@@ -219,6 +246,7 @@ class SubscriptionActivityRun:
|
||||
}
|
||||
self._resources: dict[str, dict[str, JsonData]] = {}
|
||||
self._related: set[str] = set()
|
||||
self._rejected_reasons: dict[str, str] = {}
|
||||
self._qualified: set[str] = set()
|
||||
self._submitted: set[str] = set()
|
||||
self._failed: set[str] = set()
|
||||
@@ -227,6 +255,17 @@ class SubscriptionActivityRun:
|
||||
self._planned_sites: set[int] = set()
|
||||
self._lock = RLock()
|
||||
|
||||
def _sync_rejection_summary(self) -> None:
|
||||
"""
|
||||
将当前拒绝集合同步到汇总计数与按原因分类统计,不受资源明细条数上限截断影响。
|
||||
"""
|
||||
self.counts["rejected"] = len(self._rejected_reasons)
|
||||
reason_counts = _sorted_reason_counts(self._rejected_reasons.values())
|
||||
if reason_counts:
|
||||
self.details["rejection_reasons"] = cast(JsonData, reason_counts)
|
||||
else:
|
||||
self.details.pop("rejection_reasons", None)
|
||||
|
||||
def resource(self, context: object, decision: str, reason: str | None = None) -> None:
|
||||
"""
|
||||
按站点和资源稳定键去重,保留标题、阶段和用户可理解的原因。
|
||||
@@ -257,6 +296,11 @@ class SubscriptionActivityRun:
|
||||
self._failed.discard(key)
|
||||
if decision == "failed" and key not in self._submitted:
|
||||
self._failed.add(key)
|
||||
if decision == "rejected" and key not in self._qualified and key not in self._submitted and key not in self._failed:
|
||||
self._rejected_reasons[key] = str(reason or "不符合订阅筛选条件")
|
||||
elif decision in {"qualified", "submitted", "failed"}:
|
||||
self._rejected_reasons.pop(key, None)
|
||||
self._sync_rejection_summary()
|
||||
self.counts["download_failed"] = len(self._failed)
|
||||
if key in self._submitted:
|
||||
decision, reason = "submitted", None
|
||||
@@ -329,7 +373,9 @@ class SubscriptionActivityRun:
|
||||
return SubscriptionActivity(
|
||||
self.subscribe.activity_key or "", self.event_id, self.kind, self.source,
|
||||
self.status, self.started_at, self.finished_at, dict(self.counts), copy.deepcopy(self.details),
|
||||
{"related": sorted(self._related), "qualified": sorted(self._qualified), "submitted": sorted(self._submitted), "failed": sorted(self._failed),
|
||||
{"related": sorted(self._related),
|
||||
"rejected": [f"{key}:{reason}" for key, reason in sorted(self._rejected_reasons.items())],
|
||||
"qualified": sorted(self._qualified), "submitted": sorted(self._submitted), "failed": sorted(self._failed),
|
||||
"requested_sites": [str(site_id) for site_id in sorted(self._requested_sites)],
|
||||
"planned_sites": [str(site_id) for site_id in sorted(self._planned_sites)]},
|
||||
)
|
||||
@@ -344,13 +390,24 @@ class SubscriptionActivityRun:
|
||||
if event.details.get("phase") == "queued":
|
||||
self.details["rules"] = {key: self.subscribe.to_dict().get(key) for key in RULE_FIELDS}
|
||||
self._related.update(event.tracking.get("related", []))
|
||||
self._rejected_reasons.update(_decode_rejected_tracking(event.tracking.get("rejected", [])))
|
||||
self._qualified.update(event.tracking.get("qualified", []))
|
||||
self._submitted.update(event.tracking.get("submitted", []))
|
||||
self._failed.update(event.tracking.get("failed", []))
|
||||
self._requested_sites.update(int(site_id) for site_id in event.tracking.get("requested_sites", []))
|
||||
self._planned_sites.update(int(site_id) for site_id in event.tracking.get("planned_sites", []))
|
||||
for resource in _detail_objects(self.details, "resources"):
|
||||
self._resources[str(resource["resource_id"])] = resource
|
||||
resource_id = str(resource["resource_id"])
|
||||
self._resources[resource_id] = resource
|
||||
if (
|
||||
resource.get("decision") == "rejected"
|
||||
and resource_id not in self._rejected_reasons
|
||||
and resource_id not in self._qualified
|
||||
and resource_id not in self._submitted
|
||||
and resource_id not in self._failed
|
||||
):
|
||||
self._rejected_reasons[resource_id] = str(resource.get("reason") or "不符合订阅筛选条件")
|
||||
self._sync_rejection_summary()
|
||||
for site in _detail_objects(self.details, "sites"):
|
||||
self._sites[int(cast(int, site["id"]))] = site
|
||||
if site.get("attempted", site["status"] != "waiting") is True:
|
||||
@@ -413,6 +470,14 @@ class SubscriptionActivityService:
|
||||
run.status = "not_submitted" if run.counts["qualified"] else "empty"
|
||||
if failures and "reason" not in run.details:
|
||||
run.details["reason"] = f"本轮有 {failures} 个站点请求未成功,其余处理结果已保留"
|
||||
elif run.counts.get("rejected") and not run.counts.get("qualified") and "reason" not in run.details:
|
||||
reasons = run.details.get("rejection_reasons")
|
||||
reason_items = (
|
||||
";".join(f"{name}({count})" for name, count in list(reasons.items())[:3])
|
||||
if isinstance(reasons, Mapping) and reasons
|
||||
else "不符合订阅筛选条件"
|
||||
)
|
||||
run.details["reason"] = f"匹配到 {run.counts['rejected']} 个相关资源,均未通过过滤条件:{reason_items}"
|
||||
|
||||
@contextmanager
|
||||
def scope(self, subscribe: SubscriptionSnapshot, kind: str, source: str, run_id: str | None = None) -> Iterator[SubscriptionActivityRun]:
|
||||
|
||||
@@ -277,6 +277,8 @@ class SearchTaskSnapshot:
|
||||
:param download_counts: 任务活动累计的成功提交分类计数;旧活动为空
|
||||
:param downloads: 本任务活动中保留的成功下载安全摘要;最多 100 条
|
||||
:param pending_site_ids: 等待恢复的站点标识;None 表示尚未限定站点范围
|
||||
:param rejected_count: 匹配订阅目标但未通过附加参数、优先级规则或洗版条件而被过滤拒绝的资源数量
|
||||
:param rejection_reasons: 任务内被过滤拒绝资源的按原因汇总计数
|
||||
"""
|
||||
|
||||
task_id: str
|
||||
@@ -300,6 +302,8 @@ class SearchTaskSnapshot:
|
||||
pending_site_ids: Optional[tuple[int, ...]] = None
|
||||
download_counts: dict[str, int] = field(default_factory=dict)
|
||||
downloads: tuple[dict[str, JsonData], ...] = ()
|
||||
rejected_count: int = 0
|
||||
rejection_reasons: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
@@ -32,6 +32,7 @@ from app.application.subscription.contract import (
|
||||
)
|
||||
from app.application.subscription.delete import AsyncUnitOfWork
|
||||
from app.application.subscription.observability import subscription_log_scope
|
||||
from app.domain.torrent import normalize_filter_payload
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.common import JsonData
|
||||
from app.schemas.event import SubscribeModifiedEventData
|
||||
@@ -46,11 +47,13 @@ def _normalized_subscription_patch(
|
||||
payload: dict[str, JsonData],
|
||||
) -> SubscriptionPatch:
|
||||
"""
|
||||
按订阅媒体类型规范化人工分类稳定引用并构造写入补丁。
|
||||
按订阅媒体类型规范化人工分类稳定引用与筛选短标签,并构造写入补丁。
|
||||
"""
|
||||
normalized = normalize_classification_reference_payload(
|
||||
payload,
|
||||
media_type=subscribe.type,
|
||||
normalized = normalize_filter_payload(
|
||||
normalize_classification_reference_payload(
|
||||
payload,
|
||||
media_type=subscribe.type,
|
||||
)
|
||||
)
|
||||
identity_fields = ("type", "media_source", "media_id", "season", "episode_group", "music_type")
|
||||
if any(field in payload and payload[field] != getattr(subscribe, field) for field in identity_fields):
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
订阅执行状态的业务投影与访问范围治理。
|
||||
"""
|
||||
|
||||
from collections import Counter
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, Protocol
|
||||
@@ -65,6 +66,8 @@ class SubscriptionBatchStatus:
|
||||
:param downloads: 批次内成功下载安全摘要;最多返回 100 条
|
||||
:param downloads_omitted: 超出明细上限或已被活动裁剪的成功下载数量
|
||||
:param skipped_count: 本轮无需执行而跳过的任务数量
|
||||
:param rejected_count: 匹配订阅目标但因质量、分辨率、特效、优先级或洗版规则被过滤拒绝的资源数量
|
||||
:param rejection_reasons: 批次内被过滤拒绝资源的按原因汇总计数
|
||||
"""
|
||||
|
||||
batch_id: str
|
||||
@@ -86,6 +89,8 @@ class SubscriptionBatchStatus:
|
||||
download_counts: dict[str, int] = field(default_factory=dict)
|
||||
downloads: tuple[dict[str, JsonData], ...] = ()
|
||||
downloads_omitted: int = 0
|
||||
rejected_count: int = 0
|
||||
rejection_reasons: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
|
||||
class SubscriptionExecutionReadRepository(Protocol):
|
||||
@@ -276,10 +281,21 @@ class SubscriptionExecutionStatusService:
|
||||
download_counts = {key: sum(task.download_counts.get(key, 0) for task in tasks)
|
||||
for key in ("submitted", "initial_submitted", "upgrade_submitted", "full_upgrade_submitted")}
|
||||
downloads = tuple(resource for task in tasks for resource in task.downloads)[:100]
|
||||
reason_counter: Counter[str] = Counter()
|
||||
for task in tasks:
|
||||
for reason, count in task.rejection_reasons.items():
|
||||
if reason and count > 0:
|
||||
reason_counter[reason] += count
|
||||
rejection_reasons = {
|
||||
reason: count
|
||||
for reason, count in sorted(reason_counter.items(), key=lambda item: (-item[1], item[0]))
|
||||
}
|
||||
return SubscriptionBatchStatus(
|
||||
download_counts=download_counts,
|
||||
downloads=downloads,
|
||||
downloads_omitted=max(0, download_counts["submitted"] - len(downloads)),
|
||||
rejected_count=sum(task.rejected_count for task in tasks),
|
||||
rejection_reasons=rejection_reasons,
|
||||
batch_id=batch.batch_id,
|
||||
source=batch.source,
|
||||
state=batch.state,
|
||||
|
||||
@@ -29,6 +29,7 @@ from app.application.subscription.contract import (
|
||||
subscription_added_report_key,
|
||||
)
|
||||
from app.domain.context import MediaInfo, MusicInfo
|
||||
from app.domain.torrent import normalize_filter_payload
|
||||
from app.schemas.common import JsonData
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.schemas.types import MUSIC_ENTITY_ALBUM, MediaSource, MediaType
|
||||
@@ -452,12 +453,14 @@ def _translate(
|
||||
season=raw_season if isinstance(raw_season, int) else None,
|
||||
episode_group=mediainfo.episode_group,
|
||||
)
|
||||
payload = cast(
|
||||
dict[str, JsonData],
|
||||
normalize_classification_reference_payload(
|
||||
kwargs,
|
||||
media_type=mediainfo.type,
|
||||
),
|
||||
payload = normalize_filter_payload(
|
||||
cast(
|
||||
dict[str, JsonData],
|
||||
normalize_classification_reference_payload(
|
||||
kwargs,
|
||||
media_type=mediainfo.type,
|
||||
),
|
||||
)
|
||||
)
|
||||
payload.update(
|
||||
{
|
||||
|
||||
@@ -244,16 +244,20 @@ def _cache_valid_torrent_content(
|
||||
def _text_filter_failure(torrent: TorrentInfo, params: Dict[str, Any], content: str) -> Optional[Tuple[str, str]]:
|
||||
"""
|
||||
按原有顺序检查包含、排除、质量等正则,并返回业务原因和运行诊断。
|
||||
|
||||
质量、分辨率、特效会先将界面短标签规范化为等价正则,兼容存量短标签与第三方调用。
|
||||
"""
|
||||
for key, label, subject, expected in (
|
||||
("include", "包含", content, True), ("exclude", "排除", content, False),
|
||||
("quality", "质量", torrent.title, True), ("resolution", "分辨率", torrent.title, True),
|
||||
("effect", "特效", torrent.title, True),
|
||||
):
|
||||
pattern = params.get(key)
|
||||
if isinstance(pattern, str) and pattern and _filter_pattern_search(pattern, subject or "") != expected:
|
||||
diagnostic = f"{subject} {'不匹配' if expected else '匹配'}{label}规则 {pattern}"
|
||||
return f"不符合{label}条件:{pattern}", diagnostic
|
||||
raw_pattern = params.get(key)
|
||||
if isinstance(raw_pattern, str) and raw_pattern:
|
||||
pattern = torrent_rules.resolve_runtime_filter_pattern(key, raw_pattern) or raw_pattern
|
||||
if _filter_pattern_search(pattern, subject or "") != expected:
|
||||
diagnostic = f"{subject} {'不匹配' if expected else '匹配'}{label}规则 {pattern}"
|
||||
return f"不符合{label}条件:{raw_pattern}", diagnostic
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ from app.domain.context import (
|
||||
)
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.domain.metainfo import MetaInfo
|
||||
from app.domain.torrent import normalize_filter_pattern
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.stop import runtime_stop_state
|
||||
from app.schemas.media import normalize_media_source
|
||||
@@ -322,7 +323,7 @@ class SubscribeQueryOwner(_SubscribeOwnerBase):
|
||||
@staticmethod
|
||||
def get_params(subscribe: SubscriptionSnapshot) -> dict[str, Any]:
|
||||
"""
|
||||
获取订阅默认参数
|
||||
获取订阅默认参数,并将存量或默认配置中的枚举短标签规范化为等价正则。
|
||||
"""
|
||||
default_rule = get_configured_system_config().get(SystemConfigKey.SubscribeDefaultParams) or {}
|
||||
return {
|
||||
@@ -330,9 +331,11 @@ class SubscribeQueryOwner(_SubscribeOwnerBase):
|
||||
for key, value in {
|
||||
"include": subscribe.include or default_rule.get("include"),
|
||||
"exclude": subscribe.exclude or default_rule.get("exclude"),
|
||||
"quality": subscribe.quality or default_rule.get("quality"),
|
||||
"resolution": subscribe.resolution or default_rule.get("resolution"),
|
||||
"effect": subscribe.effect or default_rule.get("effect"),
|
||||
"quality": normalize_filter_pattern("quality", subscribe.quality or default_rule.get("quality")),
|
||||
"resolution": normalize_filter_pattern(
|
||||
"resolution", subscribe.resolution or default_rule.get("resolution")
|
||||
),
|
||||
"effect": normalize_filter_pattern("effect", subscribe.effect or default_rule.get("effect")),
|
||||
"audio_quality": getattr(subscribe, "audio_quality", None),
|
||||
"audio_format": getattr(subscribe, "audio_format", None),
|
||||
"min_bitrate": getattr(subscribe, "min_bitrate", None),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
订阅执行状态的请求级异步 SQLAlchemy 适配器。
|
||||
"""
|
||||
|
||||
from collections import Counter
|
||||
from dataclasses import replace
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -22,15 +23,51 @@ def _download_counts(counts: dict[str, Any]) -> dict[str, int]:
|
||||
and isinstance(value, int)}
|
||||
|
||||
|
||||
def _rejection_summary(activity: Optional[SubscribeActivity]) -> tuple[int, dict[str, int]]:
|
||||
"""
|
||||
提取单任务活动中的过滤拒绝计数与原因分布,兼容仅含资源明细的历史活动记录。
|
||||
"""
|
||||
if activity is None:
|
||||
return 0, {}
|
||||
details = activity.details if isinstance(activity.details, dict) else {}
|
||||
stored_reasons = details.get("rejection_reasons")
|
||||
if isinstance(stored_reasons, dict):
|
||||
reasons = {
|
||||
str(reason): count
|
||||
for reason, count in stored_reasons.items()
|
||||
if reason and isinstance(count, int) and count > 0
|
||||
}
|
||||
else:
|
||||
resources = details.get("resources", [])
|
||||
counter = Counter(
|
||||
str(resource.get("reason") or "不符合订阅筛选条件")
|
||||
for resource in (resources if isinstance(resources, list) else [])
|
||||
if isinstance(resource, dict) and resource.get("decision") == "rejected"
|
||||
)
|
||||
reasons = dict(counter)
|
||||
ordered_reasons = {
|
||||
reason: count
|
||||
for reason, count in sorted(reasons.items(), key=lambda item: (-item[1], item[0]))
|
||||
}
|
||||
counts = activity.counts if isinstance(activity.counts, dict) else {}
|
||||
rejected_count = counts.get("rejected")
|
||||
if not isinstance(rejected_count, int) or rejected_count < 0:
|
||||
rejected_count = sum(ordered_reasons.values())
|
||||
return rejected_count, ordered_reasons
|
||||
|
||||
|
||||
def _task(record: SubscriptionSearchTask, activity: Optional[SubscribeActivity] = None) -> SearchTaskSnapshot:
|
||||
"""
|
||||
复制可脱离 AsyncSession 使用的搜索任务快照。
|
||||
"""
|
||||
rejected_count, rejection_reasons = _rejection_summary(activity)
|
||||
return SearchTaskSnapshot(
|
||||
download_counts=_download_counts(activity.counts if activity else {}),
|
||||
downloads=tuple({**resource, "subscription_id": record.subscription_id, "task_id": record.task_id}
|
||||
for resource in (activity.details.get("resources", []) if activity else [])
|
||||
if isinstance(resource, dict) and resource.get("decision") == "submitted"),
|
||||
rejected_count=rejected_count,
|
||||
rejection_reasons=rejection_reasons,
|
||||
task_id=record.task_id,
|
||||
batch_id=record.batch_id,
|
||||
subscription_id=record.subscription_id,
|
||||
|
||||
@@ -762,3 +762,109 @@ def rate_limit_cooldown(message: Optional[str]) -> Optional[int]:
|
||||
60 if unit.startswith(("分", "minute")) else 1
|
||||
)
|
||||
return max(3600, int(wait.group(1)) * multiplier)
|
||||
|
||||
|
||||
# 与前端 constants.ts 下拉选项一一对应的短标签展开映射,键统一使用小写去空白形式。
|
||||
_UI_FILTER_PATTERN_ALIASES: dict[str, dict[str, str]] = {
|
||||
"quality": {
|
||||
"蓝光原盘": "Blu-?Ray.+VC-?1|Blu-?Ray.+AVC|UHD.+blu-?ray.+HEVC|MiniBD",
|
||||
"藍光原盤": "Blu-?Ray.+VC-?1|Blu-?Ray.+AVC|UHD.+blu-?ray.+HEVC|MiniBD",
|
||||
"blu-ray original": "Blu-?Ray.+VC-?1|Blu-?Ray.+AVC|UHD.+blu-?ray.+HEVC|MiniBD",
|
||||
"bluray original": "Blu-?Ray.+VC-?1|Blu-?Ray.+AVC|UHD.+blu-?ray.+HEVC|MiniBD",
|
||||
"remux": "Remux",
|
||||
"bluray": "Blu-?Ray",
|
||||
"blu-ray": "Blu-?Ray",
|
||||
"uhd": "UHD|UltraHD",
|
||||
"web-dl": "WEB-?DL|WEB-?RIP",
|
||||
"webdl": "WEB-?DL|WEB-?RIP",
|
||||
"hdtv": "HDTV",
|
||||
"h265": "[Hx].?265|HEVC",
|
||||
"h.265": "[Hx].?265|HEVC",
|
||||
"hevc": "[Hx].?265|HEVC",
|
||||
"h264": "[Hx].?264|AVC",
|
||||
"h.264": "[Hx].?264|AVC",
|
||||
"avc": "[Hx].?264|AVC",
|
||||
},
|
||||
"resolution": {
|
||||
"4k": "4K|2160p|x2160",
|
||||
"1080p": "1080[pi]|x1080",
|
||||
"720p": "720[pi]|x720",
|
||||
},
|
||||
"effect": {
|
||||
"杜比视界": r"Dolby[\s.]+Vision|DOVI|[\s.]+DV[\s.]+",
|
||||
"杜比視界": r"Dolby[\s.]+Vision|DOVI|[\s.]+DV[\s.]+",
|
||||
"dolby vision": r"Dolby[\s.]+Vision|DOVI|[\s.]+DV[\s.]+",
|
||||
"dovi": r"Dolby[\s.]+Vision|DOVI|[\s.]+DV[\s.]+",
|
||||
"dv": r"Dolby[\s.]+Vision|DOVI|[\s.]+DV[\s.]+",
|
||||
"杜比全景声": r"Dolby[\s.]*\+?Atmos|Atmos",
|
||||
"杜比全景聲": r"Dolby[\s.]*\+?Atmos|Atmos",
|
||||
"dolby atmos": r"Dolby[\s.]*\+?Atmos|Atmos",
|
||||
"atmos": r"Dolby[\s.]*\+?Atmos|Atmos",
|
||||
"hdr": r"[\s.]+HDR[\s.]+|HDR10|HDR10\+",
|
||||
"sdr": r"[\s.]+SDR[\s.]+",
|
||||
},
|
||||
}
|
||||
|
||||
# 运行期标题匹配兼容行首/行尾/连字符等非字母数字边界,同时继续排除 HDRip、DVD 等误命中。
|
||||
_RUNTIME_EFFECT_PATTERN_OVERRIDES: dict[str, str] = {
|
||||
r"Dolby[\s.]+Vision|DOVI|[\s.]+DV[\s.]+": (
|
||||
r"Dolby[\s.]+Vision|DOVI|(?<![A-Za-z0-9])DV(?![A-Za-z0-9])"
|
||||
),
|
||||
r"[\s.]+HDR[\s.]+|HDR10|HDR10\+": (
|
||||
r"(?<![A-Za-z0-9])HDR(?![A-Za-z0-9])|HDR10|HDR10\+"
|
||||
),
|
||||
r"[\s.]+SDR[\s.]+": r"(?<![A-Za-z0-9])SDR(?![A-Za-z0-9])",
|
||||
}
|
||||
|
||||
|
||||
def normalize_filter_pattern(field: str, pattern: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
将质量、分辨率、特效的界面短标签展开为与 Web 端一致的等价正则表达式。
|
||||
|
||||
仅对精确匹配已知枚举短标签(忽略首尾空白与大小写)的值做展开;
|
||||
已展开表达式或用户自定义正则保持原样返回,不改变显式正则语义。
|
||||
|
||||
:param field: 过滤条件字段名,支持 quality、resolution、effect
|
||||
:param pattern: 订阅、默认规则或工作流传入的匹配表达式
|
||||
:return: 规范化后的正则表达式;输入为空或非字符串时原样返回
|
||||
"""
|
||||
if not isinstance(pattern, str) or not pattern:
|
||||
return pattern
|
||||
aliases = _UI_FILTER_PATTERN_ALIASES.get(field)
|
||||
if not aliases:
|
||||
return pattern
|
||||
return aliases.get(pattern.strip().casefold(), pattern)
|
||||
|
||||
|
||||
def resolve_runtime_filter_pattern(field: str, pattern: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
解析运行期种子标题匹配使用的正则表达式。
|
||||
|
||||
在短标签展开的基础上,将内置特效预设中的空白/点号边界放宽为非字母数字词边界,
|
||||
使标题首尾或括号/连字符分隔的 ``HDR``、``SDR``、``DV`` 能正常命中,同时排除 ``HDRip``、``DVD``。
|
||||
|
||||
:param field: 过滤条件字段名
|
||||
:param pattern: 原始或已规范化的过滤表达式
|
||||
:return: 供运行期标题搜索使用的正则表达式
|
||||
"""
|
||||
normalized = normalize_filter_pattern(field, pattern)
|
||||
if field == "effect" and isinstance(normalized, str):
|
||||
return _RUNTIME_EFFECT_PATTERN_OVERRIDES.get(normalized, normalized)
|
||||
return normalized
|
||||
|
||||
|
||||
def normalize_filter_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
复制并规范化字典中的质量、分辨率、特效枚举短标签。
|
||||
|
||||
未提供的字段与显式清空的 None 保持原样,不修改调用方传入的原字典。
|
||||
|
||||
:param payload: 待持久化或转换的订阅字段字典
|
||||
:return: 规范化过滤表达式后的新字典
|
||||
"""
|
||||
normalized = dict(payload)
|
||||
for field in ("quality", "resolution", "effect"):
|
||||
value = normalized.get(field)
|
||||
if isinstance(value, str) and value:
|
||||
normalized[field] = normalize_filter_pattern(field, value)
|
||||
return normalized
|
||||
|
||||
@@ -156,6 +156,8 @@ class SubscriptionBatchStatus(BaseModel):
|
||||
download_counts: Dict[str, int] = Field(default_factory=dict, description="成功下载任务分类计数:submitted 总数、initial_submitted 首次订阅、upgrade_submitted 洗版(含混合整包)、full_upgrade_submitted 全集洗版子集;旧活动不推断来源")
|
||||
downloads: List[Dict[str, JsonData]] = Field(default_factory=list, description="成功下载的安全摘要,含 subscription_download 提交类型与全集洗版模式;最多 100 条")
|
||||
downloads_omitted: int = Field(default=0, description="因活动或批次明细上限省略的成功下载数量,计数不受此上限影响")
|
||||
rejected_count: int = Field(default=0, description="匹配订阅作品但因质量、分辨率、特效、优先级或洗版规则被过滤拒绝的资源数量")
|
||||
rejection_reasons: Dict[str, int] = Field(default_factory=dict, description="批次内被过滤拒绝资源的按原因汇总计数,用于区分站点无资源与规则过滤")
|
||||
skipped_count: int = Field(default=0, description="已跳过的订阅任务数量")
|
||||
current_subscription_id: Optional[int] = Field(default=None, description="正在处理的订阅标识")
|
||||
current_site_id: Optional[int] = Field(default=None, description="正在处理的站点标识")
|
||||
|
||||
@@ -851,7 +851,7 @@ flowchart LR
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1200 |
|
||||
| 内部导入边 | 10,692 |
|
||||
| 内部导入边 | 10,696 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) |
|
||||
|
||||
@@ -210,8 +210,10 @@ Agent/MCP 网关要求更新对象非空,且拒绝把 `***` 等宿主脱敏占
|
||||
`submission_type`(`initial` / `upgrade`)、`best_version_full` 及两类集数。
|
||||
活动可从订阅历史继续查看,恢复重试按资源去重,不重复累计成功回执。
|
||||
- `GET /api/v1/subscribe/execution/batches` 及其 `/{batch_id}` 详情返回 `download_counts`、
|
||||
`downloads` 和 `downloads_omitted`。分类数量按成功下载任务计数,与搜索任务完成数量独立;
|
||||
明细最多 100 条,裁剪不影响总量,访问权限沿用整批订阅归属校验。
|
||||
`downloads` 和 `downloads_omitted`,并在各搜索任务快照中提供 `rejected_count` 与
|
||||
`rejection_reasons` 以区分“站点无相关资源”与“候选资源被分辨率/质量/规则过滤”。
|
||||
分类数量按成功下载任务计数,与搜索任务完成数量独立;明细最多 100 条,裁剪不影响总量,
|
||||
访问权限沿用整批订阅归属校验。
|
||||
- 下载历史的 `note.subscription_download` 保留同一来源,`note.source` 继续保留原入口信息。
|
||||
下载处理上下文在持久事件恢复后保留该来源,已冻结的通知保持模板渲染结果。
|
||||
|
||||
|
||||
@@ -237,3 +237,44 @@ def test_request_cancel_uses_injected_execution_boundary():
|
||||
|
||||
assert asyncio.run(service.request_cancel("batch-1")) is True
|
||||
assert requested == ["batch-1"]
|
||||
|
||||
|
||||
def test_batch_projection_aggregates_rejected_counts_and_reasons():
|
||||
"""
|
||||
批次零提交时仍须汇总各任务被过滤拒绝的资源数量与原因,避免表现为静默空成功。
|
||||
"""
|
||||
repository = _Repository()
|
||||
repository.batch = replace(
|
||||
repository.batch,
|
||||
state="completed",
|
||||
total_count=2,
|
||||
finished_count=2,
|
||||
)
|
||||
repository.tasks = {
|
||||
1: replace(
|
||||
_task(1, state="completed", phase="completed"),
|
||||
rejected_count=20,
|
||||
rejection_reasons={"不符合分辨率条件:4K|2160p|x2160": 18, "不符合优先级过滤规则": 2},
|
||||
),
|
||||
2: replace(
|
||||
_task(2, state="completed", phase="completed"),
|
||||
rejected_count=7,
|
||||
rejection_reasons={"不符合分辨率条件:4K|2160p|x2160": 7},
|
||||
),
|
||||
}
|
||||
|
||||
visible = asyncio.run(
|
||||
SubscriptionExecutionStatusService(repository).get_batch(
|
||||
"batch-1",
|
||||
accessible_subscription_ids={1, 2},
|
||||
)
|
||||
)
|
||||
|
||||
assert visible is not None
|
||||
assert visible.state == "completed"
|
||||
assert visible.download_counts["submitted"] == 0
|
||||
assert visible.rejected_count == 27
|
||||
assert visible.rejection_reasons == {
|
||||
"不符合分辨率条件:4K|2160p|x2160": 25,
|
||||
"不符合优先级过滤规则": 2,
|
||||
}
|
||||
|
||||
171
tests/domain/torrent/test_filter_patterns.py
Normal file
171
tests/domain/torrent/test_filter_patterns.py
Normal file
@@ -0,0 +1,171 @@
|
||||
"""
|
||||
订阅与工作流附加过滤枚举短标签的规范化与种子标题匹配回归测试。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.torrent.download import TorrentHelper
|
||||
from app.domain.context import TorrentInfo
|
||||
from app.domain.torrent import normalize_filter_pattern, normalize_filter_payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "raw", "expected"),
|
||||
[
|
||||
("resolution", "4K", "4K|2160p|x2160"),
|
||||
("resolution", " 4k ", "4K|2160p|x2160"),
|
||||
("resolution", "1080p", "1080[pi]|x1080"),
|
||||
("resolution", "720P", "720[pi]|x720"),
|
||||
("quality", "蓝光原盘", "Blu-?Ray.+VC-?1|Blu-?Ray.+AVC|UHD.+blu-?ray.+HEVC|MiniBD"),
|
||||
("quality", "BluRay", "Blu-?Ray"),
|
||||
("quality", "UHD", "UHD|UltraHD"),
|
||||
("quality", "WEB-DL", "WEB-?DL|WEB-?RIP"),
|
||||
("quality", "H265", "[Hx].?265|HEVC"),
|
||||
("quality", "H.264", "[Hx].?264|AVC"),
|
||||
("effect", "杜比视界", r"Dolby[\s.]+Vision|DOVI|[\s.]+DV[\s.]+"),
|
||||
("effect", "杜比全景声", r"Dolby[\s.]*\+?Atmos|Atmos"),
|
||||
("effect", "HDR", r"[\s.]+HDR[\s.]+|HDR10|HDR10\+"),
|
||||
("effect", "SDR", r"[\s.]+SDR[\s.]+"),
|
||||
],
|
||||
)
|
||||
def test_normalize_filter_pattern_expands_ui_short_labels(field: str, raw: str, expected: str) -> None:
|
||||
"""
|
||||
验证质量、分辨率、特效下拉短标签均展开为与前端一致的等价正则。
|
||||
|
||||
:param field: 筛选字段名
|
||||
:param raw: 界面或客户端提交的短标签
|
||||
:param expected: 规范化后的正则表达式
|
||||
"""
|
||||
assert normalize_filter_pattern(field, raw) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "custom_pattern"),
|
||||
[
|
||||
("resolution", "4K|2160p|x2160"),
|
||||
("resolution", "2160p"),
|
||||
("quality", "WEB-DL.*H265"),
|
||||
("effect", "HDR10\\+"),
|
||||
("include", "4K"),
|
||||
("exclude", "HDR"),
|
||||
],
|
||||
)
|
||||
def test_normalize_filter_pattern_preserves_custom_regex_and_other_fields(
|
||||
field: str, custom_pattern: str
|
||||
) -> None:
|
||||
"""
|
||||
验证已展开表达式、用户自定义正则以及非枚举字段保持原样。
|
||||
|
||||
:param field: 筛选字段名
|
||||
:param custom_pattern: 自定义正则表达式
|
||||
"""
|
||||
assert normalize_filter_pattern(field, custom_pattern) == custom_pattern
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("filter_params", "matching_title", "rejected_title", "expected_reason"),
|
||||
[
|
||||
(
|
||||
{"resolution": "4K"},
|
||||
"Fold.the.Moon.S01E12.2160p.WEB-DL.H265.AAC-Group",
|
||||
"Fold.the.Moon.S01E12.1080p.WEB-DL.H265.AAC-Group",
|
||||
"不符合分辨率条件:4K",
|
||||
),
|
||||
(
|
||||
{"resolution": "1080p"},
|
||||
"Show.S01E01.1080i.HDTV.H264-Group",
|
||||
"Show.S01E01.720p.HDTV.H264-Group",
|
||||
"不符合分辨率条件:1080p",
|
||||
),
|
||||
(
|
||||
{"quality": "WEB-DL"},
|
||||
"Show.S01E01.2160p.WEBRip.x265-Group",
|
||||
"Show.S01E01.2160p.HDTV.x265-Group",
|
||||
"不符合质量条件:WEB-DL",
|
||||
),
|
||||
(
|
||||
{"quality": "H265"},
|
||||
"Show.S01E01.2160p.WEB-DL.HEVC-Group",
|
||||
"Show.S01E01.2160p.WEB-DL.x264-Group",
|
||||
"不符合质量条件:H265",
|
||||
),
|
||||
(
|
||||
{"effect": "杜比视界"},
|
||||
"Fold.the.Moon.S01E01.2160p.WEB-DL.DV.Atmos.H265-Group",
|
||||
"Fold.the.Moon.S01E01.2160p.WEB-DL.SDR.H265-Group",
|
||||
"不符合特效条件:杜比视界",
|
||||
),
|
||||
(
|
||||
{"effect": "杜比全景声"},
|
||||
"Fold.the.Moon.S01E01.2160p.WEB-DL.Dolby.Atmos.H265-Group",
|
||||
"Fold.the.Moon.S01E01.2160p.WEB-DL.AAC2.0.H265-Group",
|
||||
"不符合特效条件:杜比全景声",
|
||||
),
|
||||
(
|
||||
{"effect": "HDR"},
|
||||
"Movie 1080p HDR",
|
||||
"Movie.1080p.HDRip.x264-Group",
|
||||
"不符合特效条件:HDR",
|
||||
),
|
||||
(
|
||||
{"effect": r"[\s.]+HDR[\s.]+|HDR10|HDR10\+"},
|
||||
"Movie 2160p HDR",
|
||||
"Movie.2160p.SDR.WEB-DL",
|
||||
r"不符合特效条件:[\s.]+HDR[\s.]+|HDR10|HDR10\+",
|
||||
),
|
||||
(
|
||||
{"effect": "杜比视界"},
|
||||
"Movie 2160p DV",
|
||||
"Movie.DVDRip.x264-Group",
|
||||
"不符合特效条件:杜比视界",
|
||||
),
|
||||
(
|
||||
{"effect": "SDR"},
|
||||
"Movie 1080p SDR",
|
||||
"Movie.1080p.HDR10.WEB-DL",
|
||||
"不符合特效条件:SDR",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_torrent_helper_matches_short_ui_labels_against_real_torrent_titles(
|
||||
filter_params: dict[str, str],
|
||||
matching_title: str,
|
||||
rejected_title: str,
|
||||
expected_reason: str,
|
||||
) -> None:
|
||||
"""
|
||||
验证存量或第三方传入的短标签可匹配常见种子命名,不满足时仍给出准确拒绝原因。
|
||||
|
||||
:param filter_params: 待测筛选条件
|
||||
:param matching_title: 应当通过筛选的种子标题
|
||||
:param rejected_title: 应当被拒绝的种子标题
|
||||
:param expected_reason: 预期返回的用户可见拒绝原因
|
||||
"""
|
||||
accepted = TorrentInfo(title=matching_title)
|
||||
rejected = TorrentInfo(title=rejected_title)
|
||||
|
||||
assert TorrentHelper.filter_torrent(accepted, filter_params) is True
|
||||
assert TorrentHelper.filter_torrent_reason(accepted, filter_params) is None
|
||||
assert TorrentHelper.filter_torrent(rejected, filter_params) is False
|
||||
assert TorrentHelper.filter_torrent_reason(rejected, filter_params) == expected_reason
|
||||
|
||||
|
||||
def test_normalize_filter_payload_expands_only_nonempty_enum_fields() -> None:
|
||||
"""
|
||||
验证写入载荷规范化仅展开非空枚举短标签,保留空值清空语义与自定义字段。
|
||||
"""
|
||||
original = {
|
||||
"quality": "蓝光原盘",
|
||||
"resolution": "4K",
|
||||
"effect": None,
|
||||
"include": "4K",
|
||||
}
|
||||
normalized = normalize_filter_payload(original)
|
||||
|
||||
assert original["resolution"] == "4K"
|
||||
assert normalized == {
|
||||
"quality": "Blu-?Ray.+VC-?1|Blu-?Ray.+AVC|UHD.+blu-?ray.+HEVC|MiniBD",
|
||||
"resolution": "4K|2160p|x2160",
|
||||
"effect": None,
|
||||
"include": "4K",
|
||||
}
|
||||
@@ -951,8 +951,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10692,
|
||||
"edge_sha256": "4ac61cea5b1d5db7de36af43c353141d3669cacff213dd1080067c6891421ea4",
|
||||
"edge_count": 10696,
|
||||
"edge_sha256": "03031aa6ebd0825acbb20b2fcc323a76aca62cf1c1dfaf662d36e265f6e10c25",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -4628,6 +4628,8 @@
|
||||
"app.application.subscription.mutation -> app.application.subscription.contract",
|
||||
"app.application.subscription.mutation -> app.application.subscription.delete",
|
||||
"app.application.subscription.mutation -> app.application.subscription.observability",
|
||||
"app.application.subscription.mutation -> app.domain",
|
||||
"app.application.subscription.mutation -> app.domain.torrent",
|
||||
"app.application.subscription.mutation -> app.runtime",
|
||||
"app.application.subscription.mutation -> app.runtime.log",
|
||||
"app.application.subscription.mutation -> app.schemas",
|
||||
@@ -4687,6 +4689,7 @@
|
||||
"app.application.subscription.write -> app.application.subscription.contract",
|
||||
"app.application.subscription.write -> app.domain",
|
||||
"app.application.subscription.write -> app.domain.context",
|
||||
"app.application.subscription.write -> app.domain.torrent",
|
||||
"app.application.subscription.write -> app.schemas",
|
||||
"app.application.subscription.write -> app.schemas.common",
|
||||
"app.application.subscription.write -> app.schemas.media",
|
||||
@@ -6166,6 +6169,7 @@
|
||||
"app.chain.subscribe.query -> app.domain.meta",
|
||||
"app.chain.subscribe.query -> app.domain.meta.metabase",
|
||||
"app.chain.subscribe.query -> app.domain.metainfo",
|
||||
"app.chain.subscribe.query -> app.domain.torrent",
|
||||
"app.chain.subscribe.query -> app.runtime",
|
||||
"app.chain.subscribe.query -> app.runtime.log",
|
||||
"app.chain.subscribe.query -> app.runtime.stop",
|
||||
|
||||
@@ -386,3 +386,43 @@ def test_resumed_site_request_keeps_the_original_planned_denominator():
|
||||
event = stored["resumed-sites"]
|
||||
assert event.counts["sites"] == event.counts["requested_sites"] == 8
|
||||
assert event.counts["discovered"] == 8 and event.counts["waiting_sites"] == 0
|
||||
|
||||
|
||||
def test_rejected_resources_preserve_counts_reasons_and_clear_on_qualification():
|
||||
"""
|
||||
过滤拒绝的资源即使超过明细上限也保留完整原因分布,后续晋级为合格资源时移除拒绝计数。
|
||||
"""
|
||||
saved = []
|
||||
service = SubscriptionActivityService(SimpleNamespace(save=saved.append, get=lambda *_args: saved[-1] if saved else None))
|
||||
with service.scope(replace(_snapshot(), resolution="4K|2160p|x2160"), "search", "manual", "rejected-run") as run:
|
||||
for index in range(110):
|
||||
run.resource(_resource(f"Show.S01E{index:02d}.1080p"), "rejected", "不符合分辨率条件:4K|2160p|x2160")
|
||||
for index in range(5):
|
||||
run.resource(_resource(f"Show.Special.{index}.2160p"), "rejected", "不符合特效条件:杜比视界")
|
||||
promoted = _resource("Show.S01E01.2160p.DV")
|
||||
run.resource(promoted, "rejected", "不符合洗版范围或升级优先级")
|
||||
run.resource(promoted, "qualified")
|
||||
run.resource(promoted, "submitted")
|
||||
completed = saved[-1]
|
||||
assert completed.status == "completed"
|
||||
assert completed.counts["related"] == 116
|
||||
assert completed.counts["rejected"] == 115
|
||||
assert completed.counts["submitted"] == 1
|
||||
assert completed.details["rejection_reasons"] == {
|
||||
"不符合分辨率条件:4K|2160p|x2160": 110,
|
||||
"不符合特效条件:杜比视界": 5,
|
||||
}
|
||||
|
||||
saved.clear()
|
||||
with pytest.raises(SubscriptionSearchDeferred):
|
||||
with service.scope(_snapshot(), "search", "manual", "all-rejected") as run:
|
||||
for index in range(3):
|
||||
run.resource(_resource(f"Only1080p.{index}"), "rejected", "不符合分辨率条件:4K|2160p|x2160")
|
||||
raise SubscriptionSearchDeferred(retry_at="2026-10-12T10:50:00Z", site_ids=(2,))
|
||||
with service.scope(_snapshot(), "search", "manual", "all-rejected") as run:
|
||||
run.resource(_resource("Only1080p.3"), "rejected", "不符合分辨率条件:4K|2160p|x2160")
|
||||
empty_event = saved[-1]
|
||||
assert empty_event.status == "empty"
|
||||
assert empty_event.counts["rejected"] == 4
|
||||
assert empty_event.details["rejection_reasons"] == {"不符合分辨率条件:4K|2160p|x2160": 4}
|
||||
assert "匹配到 4 个相关资源,均未通过过滤条件" in str(empty_event.details.get("reason"))
|
||||
|
||||
@@ -189,6 +189,9 @@ def test_batch_reads_persisted_activity_counts_and_safe_items(tmp_path):
|
||||
context = _context([1, 2])
|
||||
annotate_subscription_download(run.subscribe, context)
|
||||
run.resource(context, "submitted")
|
||||
rejected = _context([1])
|
||||
rejected.torrent_info.title = "Demo.S01E01.1080p"
|
||||
run.resource(rejected, "rejected", "不符合分辨率条件:4K|2160p|x2160")
|
||||
event = run.snapshot()
|
||||
session.add(SubscribeActivity(activity_key="activity", event_id=task_id, kind="search", source="manual",
|
||||
status="completed", started_at="now", counts=event.counts, details=event.details))
|
||||
@@ -203,6 +206,8 @@ def test_batch_reads_persisted_activity_counts_and_safe_items(tmp_path):
|
||||
assert details.download_counts["full_upgrade_submitted"] == 1
|
||||
assert details.downloads[0]["subscription_download"] == context.subscription_download
|
||||
assert details.downloads_omitted == 0
|
||||
assert details.rejected_count == 1
|
||||
assert details.rejection_reasons == {"不符合分辨率条件:4K|2160p|x2160": 1}
|
||||
assert "private" not in str(details)
|
||||
statuses = await service.for_subscriptions((17, 18))
|
||||
assert statuses[17].submitted_count == 1
|
||||
|
||||
Reference in New Issue
Block a user