feat(download): add ResourceSubmit event and expose torrent resource identity

This commit is contained in:
InfinityPacer
2026-11-25 10:47:24 +08:00
committed by InfinityPacer
parent e1578fae6d
commit 37308d0e5a
18 changed files with 477 additions and 29 deletions

View File

@@ -57,7 +57,7 @@ from app.schemas.download import (
ExistingTaskRejection,
is_unconfirmed_download_message,
)
from app.schemas.event import ResourceDownloadEventData
from app.schemas.event import ResourceDownloadEventData, ResourceSubmitEventData
from app.schemas.exception import RateLimitExceededException
from app.schemas.file import FileURI
from app.schemas.media import normalize_media_source, resolve_media_identity
@@ -991,6 +991,67 @@ class _DownloadResourceOwner(_DownloadOwnerBase):
logger.warn(str(err))
return save_path, str(err)
@staticmethod
def _apply_resource_submit_event(
*,
prepared: _PreparedDownload,
context: Context,
task_hashes: frozenset[str],
episodes: Optional[Set[int]],
channel: Optional[NotificationChannel],
source: Optional[str],
downloader: Optional[str],
userid: Union[str, int, None],
username: Optional[str],
label: Optional[str],
user_specified: bool,
) -> Optional[str]:
"""
在种子内容与真实哈希准备完成后、提交下载器之前触发链式取消检查。
:param prepared: 已解析出种子字节、文件清单与最终目录的本地提交事实
:param context: 本次下载的资源上下文
:param task_hashes: 从种子内容或磁力链接解析出的真实 info_hash 集合
:param episodes: 本次提交的目标集数
:param channel: 通知渠道
:param source: 下载来源标识
:param downloader: 调用方指定的下载器名称
:param userid: 触发下载的用户标识
:param username: 触发下载的用户名
:param label: 下载任务标签
:param user_specified: 是否为用户手动明确指定该种子
:return: 被事件取消时返回取消说明;允许提交时返回 None
"""
event_data = ResourceSubmitEventData(
context=context,
hashes=sorted(task_hashes),
episodes=set(episodes or (prepared.meta.episode_list if prepared.meta else [])),
channel=channel,
origin=source,
downloader=downloader or prepared.site_downloader,
save_path=prepared.download_uri,
folder_name=prepared.folder_name,
file_list=list(prepared.file_list),
user_specified=user_specified,
options={
"userid": userid,
"username": username,
"media_category": prepared.media.category if prepared.media else None,
"label": label,
},
)
event = eventmanager.send_event(ChainEventType.ResourceSubmit, event_data)
if event and event.event_data:
event_data = cast(ResourceSubmitEventData, event.event_data)
if event_data.cancel:
logger.debug(
"Resource submit canceled by event: %s, Reason: %s",
event_data.source,
event_data.reason,
)
return event_data.reason or "下载提交被事件取消"
return None
class DownloadSubmissionOwner(_DownloadResourceOwner):
"""
@@ -1095,6 +1156,24 @@ class DownloadSubmissionOwner(_DownloadResourceOwner):
if governance:
governance.report(context, "rejected", reason)
return (None, reason) if return_detail else None
task_hashes = torrent_rules.download_hashes(prepared.torrent_content)
submit_error = self._apply_resource_submit_event(
prepared=prepared,
context=context,
task_hashes=task_hashes,
episodes=episodes,
channel=channel,
source=source,
downloader=downloader,
userid=userid,
username=username,
label=label,
user_specified=user_specified,
)
if submit_error:
if governance:
governance.report(context, "rejected", submit_error)
return (None, "下载被事件取消") if return_detail else None
download_hash, error_msg = self._submit_prepared_download(
prepared=prepared,
context=context,
@@ -1108,6 +1187,7 @@ class DownloadSubmissionOwner(_DownloadResourceOwner):
custom_words=custom_words,
governance=governance,
user_specified=user_specified,
task_hashes=task_hashes,
)
if governance:
if download_hash:
@@ -1322,6 +1402,7 @@ class DownloadSubmissionOwner(_DownloadResourceOwner):
custom_words: Optional[str],
governance: Optional[SubscriptionDownloadGovernance],
user_specified: bool = False,
task_hashes: Optional[frozenset[str]] = None,
) -> tuple[Optional[str], Optional[str]]:
"""
在可取消边界后调用下载器,并分派成功或拒绝结算。
@@ -1346,13 +1427,17 @@ class DownloadSubmissionOwner(_DownloadResourceOwner):
# 音乐尚无目录分类时仍提供稳定的下载器分类,不回写媒体的目录或元数据分类。
if not category and prepared.media.type == MediaType.MUSIC:
category = MediaType.MUSIC.value
task_hashes = torrent_rules.download_hashes(prepared.torrent_content)
resolved_hashes = (
task_hashes
if task_hashes is not None
else torrent_rules.download_hashes(prepared.torrent_content)
)
# 读取确认记录 → 下载器受理 → 写入下载历史整段持有任务锁,见 downloader_task_locks:
# 已有任务上的追加与整理链回写、删除、暂停开始互斥,确认记录的读取、合并与写回也不会被并发提交打断。
result: Optional[Tuple[Optional[str], Optional[str], Optional[str], str]]
with downloader_task_locks.hold(task_hashes):
with downloader_task_locks.hold(resolved_hashes):
try:
previous_selection = self._existing_task_confirmed_selection(task_hashes)
previous_selection = self._existing_task_confirmed_selection(resolved_hashes)
except Exception as err:
# 读不到历史时不能当成"没有历史"继续:受理后写回的确认记录只会剩下本次的文件,之前被取消的
# 文件从此不再受保护。数据库读不了时写历史同样会失败,直接按瞬时失败稍后重试,不调用下载器。

View File

@@ -4,13 +4,17 @@ TTG 详情与下载路径的稳定资源身份及短时票据规则。
沿用通用页面爬虫完成搜索;这里只解释专站路径,不持有配置、不执行 I/O。
"""
import base64
import binascii
import re
from typing import Optional
from urllib.parse import urlsplit
from urllib.parse import parse_qs, urlsplit
_HOST = "totheglory.im"
_DETAIL_PATH = re.compile(r"/t/(\d+)/?")
_DOWNLOAD_PATH = re.compile(r"/dl/(\d+)/[^/]+/?")
_RSS_DOWNLOAD_PATH = re.compile(r"/rssdd\.php")
_RSS_PAR_ID = re.compile(r"^vvv([1-9]\d*)(?:$|[^0-9])")
class TTGDownloadAdapter:
@@ -18,10 +22,32 @@ class TTGDownloadAdapter:
解释 TTG 路径,末段 auth 票据不能作为资源身份。
"""
@staticmethod
def _rss_torrent_id(query: str) -> Optional[str]:
"""
从 TTG RSS 直链的 base64 ``par`` 参数提取稳定种子 ID。
:param query: ``rssdd.php`` 请求的原始查询串
:return: 解码出 ``vvv{id}`` 前缀时的种子 ID;非法或缺失时返回 None
"""
values = parse_qs(query).get("par")
if not values or len(values) != 1:
return None
raw = values[0].strip()
if not raw:
return None
padded = raw + "=" * (-len(raw) % 4)
try:
decoded = base64.b64decode(padded.encode("ascii"), validate=True).decode("utf-8")
except (ValueError, binascii.Error, UnicodeDecodeError):
return None
match = _RSS_PAR_ID.match(decoded)
return match[1] if match else None
@staticmethod
def torrent_id_from_url(url: str) -> Optional[str]:
"""
从本站详情页或签名下载路径提取稳定种子 ID。
从本站详情页、签名下载路径或 RSS 直链提取稳定种子 ID。
:param url: 旧缓存、RSS 或搜索候选中的公开地址
:return: 稳定种子 ID;其他站点或不支持的路径返回 None
@@ -31,7 +57,11 @@ class TTGDownloadAdapter:
if host != _HOST and not host.endswith(f".{_HOST}"):
return None
match = _DETAIL_PATH.fullmatch(parsed.path) or _DOWNLOAD_PATH.fullmatch(parsed.path)
return match[1] if match else None
if match:
return match[1]
if _RSS_DOWNLOAD_PATH.fullmatch(parsed.path):
return TTGDownloadAdapter._rss_torrent_id(parsed.query)
return None
@staticmethod
def is_expiring_download_url(url: str) -> bool:

View File

@@ -158,6 +158,7 @@ _PAYLOAD_MODELS: dict[EventType | ChainEventType, type[BaseModel]] = {
ChainEventType.TransferOverwriteCheck: event_schemas.TransferOverwriteCheckEventData,
ChainEventType.ResourceSelection: event_schemas.ResourceSelectionContractData,
ChainEventType.ResourceDownload: event_schemas.ResourceDownloadContractData,
ChainEventType.ResourceSubmit: event_schemas.ResourceSubmitContractData,
ChainEventType.DiscoverSource: event_schemas.DiscoverSourceEventData,
ChainEventType.MediaRecognizeConvert: event_schemas.MediaRecognizeConvertEventData,
ChainEventType.RecommendSource: event_schemas.RecommendSourceEventData,
@@ -183,18 +184,21 @@ _SNAPSHOT_EVENTS = {
EventType.MetadataScrape,
ChainEventType.ResourceSelection,
ChainEventType.ResourceDownload,
ChainEventType.ResourceSubmit,
ChainEventType.SubscribeCompletionCheck,
}
_INPUT_MODELS: dict[EventType | ChainEventType, type[BaseModel]] = {
ChainEventType.ResourceSelection: event_schemas.ResourceSelectionInputContractData,
ChainEventType.ResourceDownload: event_schemas.ResourceDownloadInputContractData,
ChainEventType.ResourceSubmit: event_schemas.ResourceSubmitInputContractData,
ChainEventType.SubscribeCompletionCheck: event_schemas.SubscribeCompletionCheckInputContractData,
}
_OUTPUT_MODELS: dict[EventType | ChainEventType, type[BaseModel]] = {
ChainEventType.ResourceSelection: event_schemas.ResourceSelectionOutputContractData,
ChainEventType.ResourceDownload: event_schemas.ResourceDownloadOutputContractData,
ChainEventType.ResourceSubmit: event_schemas.ResourceSubmitOutputContractData,
ChainEventType.SubscribeCompletionCheck: event_schemas.SubscribeCompletionCheckOutputContractData,
}

View File

@@ -467,6 +467,55 @@ class ResourceDownloadOutputContractData(ChainEventData):
reason: str = Field(default="", description="拦截原因")
class ResourceSubmitContractData(ChainEventData):
"""
ResourceSubmit 的稳定输入/输出契约。
"""
context: Optional[ContextSnapshot] = Field(default=None, description="当前资源上下文")
hashes: List[str] = Field(default_factory=list, description="种子或磁力解析出的真实 info_hash 列表")
episodes: Optional[Set[int]] = Field(default=None, description="剧集信息")
channel: Optional[NotificationChannel] = Field(default=None, description="消息渠道标识")
origin: Optional[str] = Field(default=None, description="操作来源")
downloader: Optional[str] = Field(default=None, description="下载器")
save_path: Optional[str] = Field(default=None, description="最终下载保存路径")
folder_name: str = Field(default="", description="种子顶层目录名")
file_list: List[str] = Field(default_factory=list, description="种子内相对文件路径清单")
user_specified: bool = Field(default=False, description="是否为用户手动明确指定该种子")
options: Optional[Dict[str, EventJsonValue]] = Field(default=None, description="下载提交选项")
cancel: bool = Field(default=False, description="是否取消当前提交")
source: str = Field(default="未知拦截源", description="数据来源")
reason: str = Field(default="", description="拦截原因")
class ResourceSubmitInputContractData(ChainEventData):
"""
ResourceSubmit 事件输入字段。
"""
context: Optional[ContextSnapshot] = Field(default=None, description="当前资源上下文")
hashes: List[str] = Field(default_factory=list, description="种子或磁力解析出的真实 info_hash 列表")
episodes: Optional[Set[int]] = Field(default=None, description="剧集信息")
channel: Optional[NotificationChannel] = Field(default=None, description="消息渠道标识")
origin: Optional[str] = Field(default=None, description="操作来源")
downloader: Optional[str] = Field(default=None, description="下载器")
save_path: Optional[str] = Field(default=None, description="最终下载保存路径")
folder_name: str = Field(default="", description="种子顶层目录名")
file_list: List[str] = Field(default_factory=list, description="种子内相对文件路径清单")
user_specified: bool = Field(default=False, description="是否为用户手动明确指定该种子")
options: Optional[Dict[str, EventJsonValue]] = Field(default=None, description="下载提交选项")
class ResourceSubmitOutputContractData(ChainEventData):
"""
ResourceSubmit 事件插件回写字段。
"""
cancel: bool = Field(default=False, description="是否取消当前提交")
source: str = Field(default="未知拦截源", description="数据来源")
reason: str = Field(default="", description="拦截原因")
class DownloadAddedContractData(BaseEventData):
"""
DownloadAdded 的稳定下载上下文契约。
@@ -802,6 +851,30 @@ class ResourceDownloadEventData(ChainEventData):
reason: str = Field(default="", description="拦截原因,描述拦截的具体原因")
class ResourceSubmitEventData(ChainEventData):
"""
ResourceSubmit 事件的数据模型,在种子内容解析完成后、提交下载器之前触发。
"""
# 输入参数
context: Any = Field(None, description="当前资源上下文")
hashes: List[str] = Field(default_factory=list, description="种子或磁力解析出的真实 info_hash 列表")
episodes: Optional[Set[int]] = Field(None, description="需要下载的集数")
channel: Optional[NotificationChannel] = Field(None, description="通知渠道")
origin: Optional[str] = Field(None, description="来源(消息通知、Subscribe、Manual等)")
downloader: Optional[str] = Field(None, description="下载器")
save_path: Optional[str] = Field(None, description="最终下载保存路径")
folder_name: str = Field(default="", description="种子顶层目录名")
file_list: List[str] = Field(default_factory=list, description="种子内相对文件路径清单")
user_specified: bool = Field(default=False, description="是否为用户手动明确指定该种子")
options: Optional[dict[str, Any]] = Field(default_factory=dict, description="其他参数")
# 输出参数
cancel: bool = Field(default=False, description="是否取消提交下载器,默认值为 False")
source: str = Field(default="未知拦截源", description="拦截源,默认值为 \"未知拦截源\"")
reason: str = Field(default="", description="拦截原因,描述拦截的具体原因")
class TransferInterceptEventData(ChainEventData):
"""
TransferIntercept 事件的数据模型。

View File

@@ -444,6 +444,10 @@ SCHEMA_EXPORTS = {
'ResourceSelectionEventData': ('app.schemas.event', 'ResourceSelectionEventData'),
'ResourceSelectionInputContractData': ('app.schemas.event', 'ResourceSelectionInputContractData'),
'ResourceSelectionOutputContractData': ('app.schemas.event', 'ResourceSelectionOutputContractData'),
'ResourceSubmitContractData': ('app.schemas.event', 'ResourceSubmitContractData'),
'ResourceSubmitEventData': ('app.schemas.event', 'ResourceSubmitEventData'),
'ResourceSubmitInputContractData': ('app.schemas.event', 'ResourceSubmitInputContractData'),
'ResourceSubmitOutputContractData': ('app.schemas.event', 'ResourceSubmitOutputContractData'),
'Response': ('app.schemas.response', 'Response'),
'RootModel': ('app.schemas.mcp', 'RootModel'),
'RuleTestData': ('app.schemas.system', 'RuleTestData'),

View File

@@ -396,6 +396,8 @@ class ChainEventType(Enum):
ResourceSelection = "resource.selection"
# 资源下载
ResourceDownload = "resource.download"
# 资源提交下载器前
ResourceSubmit = "resource.submit"
# 探索数据源
DiscoverSource = "discover.source"
# 媒体识别转换

View File

@@ -17,6 +17,9 @@ from app.schemas.event import (
ResourceSelectionContractData,
ResourceSelectionInputContractData,
ResourceSelectionOutputContractData,
ResourceSubmitContractData,
ResourceSubmitInputContractData,
ResourceSubmitOutputContractData,
SubscribeCompletionCheckContractData,
SubscribeCompletionCheckInputContractData,
SubscribeCompletionCheckOutputContractData,
@@ -39,6 +42,9 @@ __all__ = [
"ResourceSelectionContractData",
"ResourceSelectionInputContractData",
"ResourceSelectionOutputContractData",
"ResourceSubmitContractData",
"ResourceSubmitInputContractData",
"ResourceSubmitOutputContractData",
"SubscribeCompletionCheckContractData",
"SubscribeCompletionCheckInputContractData",
"SubscribeCompletionCheckOutputContractData",

View File

@@ -2,6 +2,7 @@
插件使用的媒体上下文、歌词候选、标题解析、识别类型和媒体身份规则。
"""
from app.application.site.protocol import torrent_resource_identity
from app.domain.context import Context, MediaInfo, MusicInfo, MusicLyrics, TorrentInfo
from app.domain.media import (
MUSIC_MEDIA_SOURCE_ORDER,
@@ -77,4 +78,5 @@ __all__ = [
"parse_media_source_selection",
"resolve_media_identity",
"set_custom_separator",
"torrent_resource_identity",
]

View File

@@ -415,8 +415,8 @@ collector 只接受 canonical `eventmanager`、`EventManager()` 及其有限别
`register`/`add_event_listener`;当前宿主有 18 个静态注册点,另保留 1 个由工作流配置驱动的
真实动态注册。`app/plugins/**` 插件副本不进入宿主事实。
生产者与消费者共用 `scripts/architecture/event_facts.py` 这一份逐调用事实源。当前宿主有 76 个
生产调用,其中 74 个静态解析为 76 个事件引用,`Command.send_plugin_event` 的插件事件类型和
生产者与消费者共用 `scripts/architecture/event_facts.py` 这一份逐调用事实源。当前宿主有 77 个
生产调用,其中 75 个静态解析为 77 个事件引用,`Command.send_plugin_event` 的插件事件类型和
`dispatch_event_handler` 的持久事件恢复类型保持动态;后者只接受 `DURABLE_EVENT_TOPICS`
登记的事件。19 个消费注册中 18 个静态、1 个动态。生成的
`runtime-contract-baseline.json` 保存 line-free 事实、数量和枚举索引;人工维护的
@@ -851,7 +851,7 @@ flowchart LR
| 指标 | 当前值 |
|---|---:|
| Python 模块 | 1199 |
| 内部导入边 | 10,616 |
| 内部导入边 | 10,619 |
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
| Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) |

View File

@@ -978,8 +978,8 @@
"runtime_only": true
}
},
"edge_count": 10616,
"edge_sha256": "8c7011467ea900ddf272bd56e0a465b88c42202115fd1cf439f096e57fecf480",
"edge_count": 10619,
"edge_sha256": "841c123087d7ac4267342942dfb7629a3e889fe3214eb5b207f7f6a92046b950",
"edges": [
"app -> app.foundation",
"app -> app.foundation.environment",
@@ -10417,6 +10417,9 @@
"app.sdk.feishu -> app.adapters.network.feishu",
"app.sdk.logging -> app.runtime",
"app.sdk.logging -> app.runtime.log",
"app.sdk.media -> app.application",
"app.sdk.media -> app.application.site",
"app.sdk.media -> app.application.site.protocol",
"app.sdk.media -> app.domain",
"app.sdk.media -> app.domain.context",
"app.sdk.media -> app.domain.media",

View File

@@ -1680,7 +1680,7 @@
],
"dynamic_consumer_count": 1,
"dynamic_producer_count": 2,
"event_count": 53,
"event_count": 54,
"event_index": {
"ChainEventType.AgentLLMProvider": {
"consumer_fingerprints": [],
@@ -1776,6 +1776,12 @@
"8121a37b3badc8940c2f1c5bbc563845cf342bc073c20af63113c6989aa01255"
]
},
"ChainEventType.ResourceSubmit": {
"consumer_fingerprints": [],
"producer_fingerprints": [
"7d564f9e9178c7d4d8b10604b35ee34617b75c952f30aa03f6f2dcbce6c7923a"
]
},
"ChainEventType.StorageOperSelection": {
"consumer_fingerprints": [],
"producer_fingerprints": [
@@ -2049,11 +2055,11 @@
]
}
},
"fact_count": 95,
"fact_count": 96,
"invalid_consumer_count": 0,
"invalid_producer_count": 0,
"producer_call_count": 76,
"producer_event_reference_count": 76,
"producer_call_count": 77,
"producer_event_reference_count": 77,
"producers": [
{
"caller": "app.agent.orchestrator",
@@ -2333,6 +2339,18 @@
"qualname": "_DownloadResourceOwner._apply_resource_download_event",
"receiver_kind": "canonical_singleton"
},
{
"caller": "app.chain.download.submission",
"dynamic": false,
"events": [
"ChainEventType.ResourceSubmit"
],
"fingerprint": "7d564f9e9178c7d4d8b10604b35ee34617b75c952f30aa03f6f2dcbce6c7923a",
"invalid": false,
"method": "send_event",
"qualname": "_DownloadResourceOwner._apply_resource_submit_event",
"receiver_kind": "canonical_singleton"
},
{
"caller": "app.chain.download.tasks",
"dynamic": false,
@@ -2967,7 +2985,7 @@
}
],
"static_consumer_count": 18,
"static_producer_call_count": 74
"static_producer_call_count": 75
},
"event_specs": {
"ChainEventType.AgentLLMProvider": {
@@ -3188,6 +3206,21 @@
"validation_mode": "diagnostic",
"visibility": "plugin_public"
},
"ChainEventType.ResourceSubmit": {
"delivery": "ephemeral",
"error_behavior": "stop_chain",
"input_contract": "ResourceSubmitInputContractData",
"legacy_reason": null,
"mode": "chain",
"ordering": "priority_serial",
"output_contract": "ResourceSubmitOutputContractData",
"payload_contract": "ResourceSubmitContractData",
"payload_mode": "snapshot",
"schema_version": 1,
"sensitive_fields": [],
"validation_mode": "diagnostic",
"visibility": "plugin_public"
},
"ChainEventType.StorageOperSelection": {
"delivery": "ephemeral",
"error_behavior": "stop_chain",
@@ -10995,6 +11028,21 @@
"name": "ResourceSelectionOutputContractData",
"target": "app.schemas.event.ResourceSelectionOutputContractData"
},
{
"kind": "import",
"name": "ResourceSubmitContractData",
"target": "app.schemas.event.ResourceSubmitContractData"
},
{
"kind": "import",
"name": "ResourceSubmitInputContractData",
"target": "app.schemas.event.ResourceSubmitInputContractData"
},
{
"kind": "import",
"name": "ResourceSubmitOutputContractData",
"target": "app.schemas.event.ResourceSubmitOutputContractData"
},
{
"kind": "import",
"name": "SubscribeCompletionCheckContractData",
@@ -11230,6 +11278,11 @@
"kind": "import",
"name": "set_custom_separator",
"target": "app.domain.meta.customization.set_custom_separator"
},
{
"kind": "import",
"name": "torrent_resource_identity",
"target": "app.application.site.protocol.torrent_resource_identity"
}
],
"app.sdk.network": [

View File

@@ -452,17 +452,17 @@ def test_event_contract_baseline_covers_every_public_event_enum() -> None:
assert set(events["event_index"]) == expected
assert events["event_count"] == len(expected)
assert events["producer_call_count"] == 76
assert events["static_producer_call_count"] == 74
assert events["producer_call_count"] == 77
assert events["static_producer_call_count"] == 75
assert events["dynamic_producer_count"] == 2
assert events["invalid_producer_count"] == 0
assert events["producer_event_reference_count"] == 76
assert events["producer_event_reference_count"] == 77
assert events["consumer_registration_count"] == 19
assert events["static_consumer_count"] == 18
assert events["dynamic_consumer_count"] == 1
assert events["invalid_consumer_count"] == 0
assert events["consumer_event_reference_count"] == 18
assert events["fact_count"] == 95
assert events["fact_count"] == 96
assert len({fact["fingerprint"] for fact in events["consumers"]}) == 19
assert all(
not fact["caller"].startswith("app.plugins")

View File

@@ -1221,17 +1221,17 @@ def publish(kind):
def test_collect_event_facts_matches_current_host_inventory() -> None:
"""
统一事实覆盖当前 76 个 producer 调用与 19 个 consumer 调用。
统一事实覆盖当前 77 个 producer 调用与 19 个 consumer 调用。
"""
facts = current_event_facts()
producers = facts["producers"]
consumers = facts["consumers"]
assert len(producers) == 76
assert sum(not fact["dynamic"] and not fact["invalid"] for fact in producers) == 74
assert len(producers) == 77
assert sum(not fact["dynamic"] and not fact["invalid"] for fact in producers) == 75
assert sum(fact["dynamic"] for fact in producers) == 2
assert sum(fact["invalid"] for fact in producers) == 0
assert sum(len(fact["events"]) for fact in producers) == 76
assert sum(len(fact["events"]) for fact in producers) == 77
assert len(consumers) == 19
assert sum(not fact["dynamic"] and not fact["invalid"] for fact in consumers) == 18
assert sum(fact["dynamic"] for fact in consumers) == 1

View File

@@ -2250,3 +2250,135 @@ def test_settle_download_success_persists_origin_media_trace_and_snapshot_roundt
)
restored = restore_download_processing(payload)
assert restored.context.origin_media == origin_media
def test_execute_download_single_emits_resource_submit_with_hashes_and_cancels_before_downloader(
monkeypatch,
):
"""
ResourceSubmit 在拉取种子并解析出真实 info_hash 后触发;取消时不得进入下载器提交或标记副作用开始。
"""
from app.application.download.admission import SubscriptionDownloadGovernance
from app.schemas.types import ChainEventType
chain = DownloadChain.__new__(DownloadChain)
captured = []
submitted = MagicMock(return_value=("should-not-run", None))
mark_started = MagicMock()
decision_observer = MagicMock()
governance = SubscriptionDownloadGovernance(
mark_started=mark_started,
decision_observer=decision_observer,
)
def handle_event(event_type, event_data):
"""
记录链式事件并在 ResourceSubmit 阶段按真实哈希取消提交。
"""
captured.append((event_type, event_data))
if event_type == ChainEventType.ResourceSubmit:
event_data.cancel = True
event_data.source = "订阅助手(增强版)"
event_data.reason = "命中近期删除指纹"
return SimpleNamespace(event_data=event_data)
monkeypatch.setattr(eventmanager, "send_event", handle_event)
monkeypatch.setattr(download_submission, "TorrentHelper", _FakeTorrentHelper)
monkeypatch.setattr(chain, "_resolve_media_download_dir", lambda **_kw: ("local", Path("/downloads/movies"), None))
monkeypatch.setattr(chain, "_submit_prepared_download", submitted)
torrent_hash = "3db38150daf7c83acf17bb413d9e29c3c8a90efd"
context = Context(
meta_info=MetaInfo("Forgotten.Island.2026.2160p.mkv"),
media_info=MediaInfo(
media_source=MediaSource.TMDB,
media_id="1465063",
type=MediaType.MOVIE,
title="忘却之岛",
year="2026",
),
torrent_info=TorrentInfo(
title="Forgotten Island 2026 2160p-RiKKi",
site_downloader="qb-main",
),
)
download_id, error_msg = chain._execute_download_single(
context=context,
torrent_content=f"magnet:?xt=urn:btih:{torrent_hash}",
source='Subscribe|{"id": 9}',
username="tester",
label="movie",
return_detail=True,
governance=governance,
user_specified=False,
)
assert download_id is None
assert error_msg == "下载被事件取消"
submitted.assert_not_called()
mark_started.assert_not_called()
decision_observer.assert_called_once_with(context, "rejected", "命中近期删除指纹")
assert [et for et, _ in captured] == [ChainEventType.ResourceDownload, ChainEventType.ResourceSubmit]
submit_data = captured[1][1]
assert submit_data.hashes == [torrent_hash]
assert submit_data.downloader == "qb-main"
assert submit_data.save_path == "/downloads/movies"
assert submit_data.origin == 'Subscribe|{"id": 9}'
assert submit_data.user_specified is False
assert submit_data.options["label"] == "movie"
def test_execute_download_single_passes_parsed_hashes_through_resource_submit_when_allowed(
monkeypatch,
):
"""
ResourceSubmit 放行时应把已计算的真实哈希传给提交阶段并正常提交下载器。
"""
from app.schemas.types import ChainEventType
chain = DownloadChain.__new__(DownloadChain)
seen_submit = []
submitted = MagicMock(return_value=("3db38150daf7c83acf17bb413d9e29c3c8a90efd", "添加下载成功"))
def handle_event(event_type, event_data):
"""
放行全部链式事件并记录 ResourceSubmit 载荷。
"""
if event_type == ChainEventType.ResourceSubmit:
seen_submit.append(event_data)
return SimpleNamespace(event_data=event_data)
monkeypatch.setattr(eventmanager, "send_event", handle_event)
monkeypatch.setattr(download_submission, "TorrentHelper", _FakeTorrentHelper)
monkeypatch.setattr(chain, "_resolve_media_download_dir", lambda **_kw: ("local", Path("/downloads/movies"), None))
monkeypatch.setattr(chain, "_submit_prepared_download", submitted)
torrent_hash = "3db38150daf7c83acf17bb413d9e29c3c8a90efd"
context = Context(
meta_info=MetaInfo("Forgotten.Island.2026.2160p.mkv"),
media_info=MediaInfo(
media_source=MediaSource.TMDB,
media_id="1465063",
type=MediaType.MOVIE,
title="忘却之岛",
year="2026",
),
torrent_info=TorrentInfo(title="Forgotten Island 2026 2160p-RiKKi"),
)
download_id, error_msg = chain._execute_download_single(
context=context,
torrent_content=f"magnet:?xt=urn:btih:{torrent_hash}",
downloader="qb-explicit",
return_detail=True,
user_specified=True,
)
assert download_id == torrent_hash
assert error_msg == "添加下载成功"
assert len(seen_submit) == 1
assert seen_submit[0].hashes == [torrent_hash]
assert seen_submit[0].downloader == "qb-explicit"
assert seen_submit[0].user_specified is True
assert submitted.call_args.kwargs["task_hashes"] == frozenset({torrent_hash})

View File

@@ -26,6 +26,8 @@ from app.schemas.event import (
ResourceDownloadOutputContractData,
ResourceSelectionInputContractData,
ResourceSelectionOutputContractData,
ResourceSubmitInputContractData,
ResourceSubmitOutputContractData,
)
from app.schemas.file import FileItem
from app.schemas.transfer import TransferInfo
@@ -34,12 +36,12 @@ from app.schemas.types import ChainEventType, EventType, MediaType, SystemConfig
def test_every_event_enum_has_complete_contract() -> None:
"""
53 个广播/链式事件必须全部登记并绑定 typed payload。
54 个广播/链式事件必须全部登记并绑定 typed payload。
"""
expected = {*EventType, *ChainEventType}
assert set(EVENT_CONTRACTS) == expected
assert len(EVENT_CONTRACTS) == 53
assert len(EVENT_CONTRACTS) == 54
for contract in EVENT_CONTRACTS.values():
assert contract.mode in {"broadcast", "chain"}
assert contract.payload_contract
@@ -204,6 +206,7 @@ def test_snapshot_contract_metadata_declares_mutable_chain_boundaries() -> None:
"""
selection = get_event_contract(ChainEventType.ResourceSelection)
download = get_event_contract(ChainEventType.ResourceDownload)
submit = get_event_contract(ChainEventType.ResourceSubmit)
assert selection.schema_version == 1
assert selection.payload_mode.value == "snapshot"
@@ -211,6 +214,9 @@ def test_snapshot_contract_metadata_declares_mutable_chain_boundaries() -> None:
assert selection.output_model is ResourceSelectionOutputContractData
assert download.input_model is ResourceDownloadInputContractData
assert download.output_model is ResourceDownloadOutputContractData
assert submit.payload_mode.value == "snapshot"
assert submit.input_model is ResourceSubmitInputContractData
assert submit.output_model is ResourceSubmitOutputContractData
assert selection.validation_mode.value == "diagnostic"

View File

@@ -9,7 +9,7 @@ from app.runtime.event.snapshot import (
EventPayloadSnapshot as RuntimeEventPayloadSnapshot,
)
from app.runtime.event.snapshot import snapshot_event_data as runtime_snapshot_event_data
from app.schemas.event import ResourceSelectionEventData
from app.schemas.event import ResourceSelectionEventData, ResourceSubmitEventData
from app.schemas.types import ChainEventType, EventType, MediaType
from app.sdk.events import (
DownloadAddedContractData,
@@ -17,6 +17,9 @@ from app.sdk.events import (
EventPayloadSnapshot,
ResourceSelectionInputContractData,
ResourceSelectionOutputContractData,
ResourceSubmitContractData,
ResourceSubmitInputContractData,
ResourceSubmitOutputContractData,
snapshot_event_data,
)
@@ -80,6 +83,44 @@ def test_chain_snapshot_separates_plugin_input_and_output_models() -> None:
assert event.event_data is raw
def test_resource_submit_snapshot_exposes_hashes_and_cancel_boundary() -> None:
"""
ResourceSubmit 链式快照分离提交前只读事实和取消回写字段,不污染原事件对象。
"""
context = Context(
media_info=MediaInfo(type=MediaType.MOVIE, title="Movie", year="2026")
)
raw = ResourceSubmitEventData(
context=context,
hashes=["3db38150daf7c83acf17bb413d9e29c3c8a90efd"],
origin="Subscribe|{\"id\": 1}",
downloader="qb",
save_path="local:/downloads/movies",
folder_name="Movie.2026",
file_list=["Movie.2026.mkv"],
user_specified=False,
cancel=True,
source="plugin",
reason="命中近期删除指纹",
)
event = Event(ChainEventType.ResourceSubmit, raw)
snapshot = event.snapshot()
assert snapshot.valid is True
assert snapshot.raw is raw
assert isinstance(snapshot.payload, ResourceSubmitContractData)
assert isinstance(snapshot.input, ResourceSubmitInputContractData)
assert isinstance(snapshot.output, ResourceSubmitOutputContractData)
assert snapshot.input.hashes == ["3db38150daf7c83acf17bb413d9e29c3c8a90efd"]
assert snapshot.input.file_list == ["Movie.2026.mkv"]
assert snapshot.input.save_path == "local:/downloads/movies"
assert snapshot.output.cancel is True
assert snapshot.output.reason == "命中近期删除指纹"
snapshot.input.hashes.append("mutated")
assert raw.hashes == ["3db38150daf7c83acf17bb413d9e29c3c8a90efd"]
def test_unknown_plugin_event_returns_unregistered_snapshot_without_error() -> None:
"""
插件自定义字符串事件没有宿主契约时保留原 payload,不制造假模型。

View File

@@ -29,6 +29,7 @@ from app.application.site.protocol import (
from app.domain import site as site_rules
from app.domain import torrent as torrent_rules
from app.domain.context import TorrentInfo
from app.sdk.media import torrent_resource_identity as sdk_torrent_resource_identity
from app.sdk.security import nexusphp_encrypt
from app.sdk.string import StringUtils
from app.startup.composition import site as composition
@@ -130,6 +131,7 @@ async def test_site_api_mutation_keeps_u2_and_dmhy_keys_apart(protocol_boundary,
@pytest.mark.parametrize("page_url,enclosure,expected", [
("https://totheglory.im/t/17/", "https://totheglory.im/dl/17/old", ("7", "id=17")),
("https://totheglory.im/t/17/", "https://totheglory.im/download?id=23", ("7", "id=17")),
(None, f"https://totheglory.im/rssdd.php?par={base64.b64encode(b'vvv17').decode()}&ssl=yes", ("7", "id=17")),
("https://kp.m-team.cc/detail/17", "https://tracker.example/download?id=23", ("7", "id=17")),
("https://tracker.example/detail/17", "[old]https://tracker.example/api", ("7", "id=17")),
("https://tracker.example/torrents.php?id=12&torrentid=17", None, ("7", "id=17")),
@@ -142,6 +144,7 @@ def test_module_identity_preserves_url_precedence_and_legacy_paths(protocol_boun
"""
torrent = TorrentInfo(site=7, page_url=page_url, enclosure=enclosure)
assert torrent_resource_identity(torrent) == expected
assert sdk_torrent_resource_identity(torrent) == expected
assert torrent.page_url == page_url and torrent.enclosure == enclosure

View File

@@ -510,6 +510,7 @@ TTG_OLD_URL = "https://totheglory.im/dl/395931/3576"
TTG_NEW_URL = "https://totheglory.im/dl/395931/8067"
# TTG RSS 条目的下载链接是 rssdd.php?par=,par 为 base64 编码的 "vvv{id}...",不使用 /dl/ 路径签名
TTG_RSS_URL = "https://totheglory.im/rssdd.php?par=dnZ2Mzk1OTMx&ssl=yes"
TTG_RSS_URL_WITH_TAIL = f"https://totheglory.im/rssdd.php?par={base64.b64encode(b'vvv395931,passkey123').decode()}&ssl=yes"
@pytest.mark.parametrize("page_url,enclosure,expected", [
@@ -518,7 +519,10 @@ TTG_RSS_URL = "https://totheglory.im/rssdd.php?par=dnZ2Mzk1OTMx&ssl=yes"
("https://totheglory.im/t/395931", None, ("1", "id=395931")),
("https://www.totheglory.im/t/395931/", None, ("1", "id=395931")),
(TTG_PAGE_URL, TTG_RSS_URL, ("1", "id=395931")),
(None, TTG_RSS_URL, None),
(None, TTG_RSS_URL, ("1", "id=395931")),
(None, TTG_RSS_URL_WITH_TAIL, ("1", "id=395931")),
(None, "https://totheglory.im/rssdd.php?par=!!!invalid!!!", None),
(None, f"https://totheglory.im/rssdd.php?par={base64.b64encode(b'other395931').decode()}", None),
("https://tracker.example/t/395931/", "https://tracker.example/dl/395931/3576", None),
("https://totheglory.im/browse.php?c=M", "https://totheglory.im/dl/395931/", None),
("https://nottheglory.im/t/395931/", None, None),