diff --git a/app/modules/indexer/__init__.py b/app/modules/indexer/__init__.py index 51caa87bd..8b5d00024 100644 --- a/app/modules/indexer/__init__.py +++ b/app/modules/indexer/__init__.py @@ -36,7 +36,7 @@ from app.modules.indexer.spider.hddolby import HddolbySpider from app.modules.indexer.spider.hdwing import HDWingPromotionMixin from app.modules.indexer.spider.milkie import MilkieSpider from app.modules.indexer.spider.mtorrent import MTorrentSpider -from app.modules.indexer.spider.piggo import PiggoSpider +from app.modules.indexer.spider.piggo import PiggoSpider, media_search_params from app.modules.indexer.spider.rousi import RousiSpider from app.modules.indexer.spider.sunnypt import SunnyPTSpider from app.modules.indexer.spider.tnode import TNodeSpider @@ -826,8 +826,10 @@ class IndexerModule(_ModuleBase): if not IndexerModule.__search_check(site, keyword): return None - search_word = IndexerModule.__clear_search_text(keyword) parser_name = str(site.get("parser") or "") + # 精确作品链接依赖原始标点,其他站点及猪猪普通关键词继续原有清洗。 + keep_keyword = parser_name == "Piggo" and search_type == "torrents" and media_search_params(keyword) + search_word = keyword if keep_keyword else IndexerModule.__clear_search_text(keyword) parser_class = SPIDER_PARSER_CLASSES.get(parser_name) if search_type == "subtitles": subtitle_argument_names = _SPECIALIZED_SUBTITLE_SEARCH_ARGUMENTS.get(parser_name) diff --git a/app/modules/indexer/spider/piggo.py b/app/modules/indexer/spider/piggo.py index e1d4b6e7c..008635232 100644 --- a/app/modules/indexer/spider/piggo.py +++ b/app/modules/indexer/spider/piggo.py @@ -10,6 +10,7 @@ from typing import Any, Optional, TypeAlias, cast from urllib.parse import urljoin, urlparse from app.adapters.network.http import AsyncRequestUtils, RequestUtils +from app.application.site.observation import report_site_search_page from app.application.site.throttle import async_wait_for_site_request, defer_site_request, wait_for_site_request from app.domain import site as site_rules from app.domain import torrent as torrent_rules @@ -40,6 +41,27 @@ def access_token(apikey: Optional[str], token: Optional[str]) -> str: return str(apikey or "").strip() or str(token or "").strip() +def media_search_params(keyword: Optional[str]) -> dict[str, str]: + """ + 将独立 IMDb 编号或官方作品链接解释为精确搜索,不猜测裸数字的来源。 + + :param keyword: 搜索输入,可为作品链接、普通标题或空值 + :return: 已识别的搜索字段;不是精确搜索时返回空字典 + """ + value = (keyword or "").strip().lower() + if re.fullmatch(r"tt[0-9]+", value): + return {"imdb_id": value} + if match := re.fullmatch(r"https?://(?:www\.)?imdb\.com/title/(tt[0-9]+)/?(?:[?#]\S*)?", value): + return {"imdb_id": match[1]} + if match := re.fullmatch(r"https?://movie\.douban\.com/subject/([1-9][0-9]*)/?(?:[?#]\S*)?", value): + return {"douban_id": match[1]} + if match := re.fullmatch( + r"https?://(?:www\.)?themoviedb\.org/(movie|tv)/([1-9][0-9]*)(?:-[^/?#\s]+)?/?(?:[?#]\S*)?", value, + ): + return {"tmdb_id": match[2], "tmdb_kind": match[1]} + return {} + + def response_data(status_code: int, payload: object, token: str = "") -> dict[str, Any]: """ 校验 HTTP 和业务状态,阻止外层成功码掩盖必读公告。 @@ -62,7 +84,7 @@ def response_data(status_code: int, payload: object, token: str = "") -> dict[st title = str(gate.get("title") or "") if isinstance(gate, dict) else "" message = f"有未读必读公告,请到猪猪网页端阅读后重试{f':{title}' if title else ''}" elif status_code == 401 or code == "401" or inner_code == "401": - message = "猪猪存取令牌已过期或无效,请重新生成长期存取令牌" + message = "猪猪存取令牌无效或实验室通道已关闭,请检查令牌及站点设置" elif status_code == 429 or code == "429" or inner_code == "429": message = f"站点限流:{message or 'HTTP 429,请稍后重试'}" elif not payload and status_code == 200: @@ -389,7 +411,7 @@ class PiggoSpider: 显式分类优先于媒体类型;不合并多路分区分页,也不把分类 ID 当作分区 ID。 - :param keyword: 标题关键词或完整 IMDb ID,空白时不添加搜索字段 + :param keyword: 标题关键词、完整 IMDb ID 或官方作品链接,空白时不添加搜索字段 :param mtype: 可按目录解释的媒体类型,未知类型不缩窄查询 :param cat: 显式分类 ID,可用逗号分隔 :param page: MoviePilot 从零开始的页码 @@ -400,10 +422,7 @@ class PiggoSpider: params: dict[str, Any] = {"page": int(page or 0) + 1, "per_page": self._size} value = str(keyword or "").strip() if value: - if re.fullmatch(r"tt[0-9]+", value, re.IGNORECASE): - params["imdb_id"] = value.lower() - else: - params["q"] = value + params.update(media_search_params(value) or {"q": value}) if cat: if not re.fullmatch(r"[1-9][0-9]*(\s*,\s*[1-9][0-9]*)*", cat.strip()): raise ValueError("猪猪分类须填写当前目录中的正整数 ID,以逗号分隔") @@ -514,6 +533,27 @@ class PiggoSpider: "labels": self._tag_labels(item, catalog[2]), } + @staticmethod + def _has_more_pages(data: dict[str, Any], requested_page: int) -> Optional[bool]: + """ + 解释已返回的页号与页数;截断计数的最后一页不等于实际末页。 + + :param data: 实验室搜索响应,旧响应可能没有页数 + :param requested_page: 实际请求的页码,从 1 开始 + :return: 服务端确认的续页状态;页数缺失或总数截断且已到计数边界时未知 + :raises ValueError: 返回页码与请求不一致或分页字段无效 + """ + if "page" in data and integer(data["page"], minimum=1) != requested_page: + raise ValueError("猪猪 API 返回了错误页码") + if "pages" not in data: + return None + capped = data.get("total_capped", False) + if not isinstance(capped, bool): + raise ValueError("猪猪 API 返回了无效分页状态") + if requested_page < integer(data["pages"]): + return True + return None if capped else False + def _parse_result(self, data: dict[str, Any], catalog: _Catalog) -> list[dict[str, Any]]: """ 校验整页种子后发布结果,坏条目不能形成半页成功或提前结束自动分页。 @@ -546,7 +586,7 @@ class PiggoSpider: """ 同步搜索或浏览最新种子,不执行网页登录或提前签发下载链接。 - :param keyword: 标题关键词或完整 IMDb ID;为空时浏览最新种子 + :param keyword: 标题关键词、完整 IMDb ID 或官方作品链接;为空时浏览最新种子 :param mtype: 用当前目录限定的媒体类型 :param cat: 显式分类 ID,可用逗号分隔 :param page: 从零开始的 MoviePilot 页码 @@ -558,12 +598,15 @@ class PiggoSpider: if not self._token: raise ValueError(TOKEN_REQUIRED) catalog = self._load_catalog() - data = self._request("torrents", self._params(keyword, mtype, cat, page, catalog)) + params = self._params(keyword, mtype, cat, page, catalog) + data = self._request("torrents", params) + has_more = self._has_more_pages(data, params["page"]) torrents = self._parse_result(data, catalog) for section_id in self._tag_sections(data, catalog): tags = self._request("catalog", {"section_id": section_id}) catalog[2][section_id] = self._parse_tags(tags.get("tags", [])) self._apply_tag_labels(torrents, data, catalog) + report_site_search_page(raw_count=len(torrents), has_more=has_more) return False, torrents except ValueError as err: self.error_detail = str(err) @@ -575,7 +618,7 @@ class PiggoSpider: """ 异步执行同一实验室搜索协议,取消时不在后台继续请求。 - :param keyword: 标题关键词或完整 IMDb ID;为空时浏览最新种子 + :param keyword: 标题关键词、完整 IMDb ID 或官方作品链接;为空时浏览最新种子 :param mtype: 用当前目录限定的媒体类型 :param cat: 显式分类 ID,可用逗号分隔 :param page: 从零开始的 MoviePilot 页码 @@ -587,12 +630,15 @@ class PiggoSpider: if not self._token: raise ValueError(TOKEN_REQUIRED) catalog = await self._async_load_catalog() - data = await self._async_request("torrents", self._params(keyword, mtype, cat, page, catalog)) + params = self._params(keyword, mtype, cat, page, catalog) + data = await self._async_request("torrents", params) + has_more = self._has_more_pages(data, params["page"]) torrents = self._parse_result(data, catalog) for section_id in self._tag_sections(data, catalog): tags = await self._async_request("catalog", {"section_id": section_id}) catalog[2][section_id] = self._parse_tags(tags.get("tags", [])) self._apply_tag_labels(torrents, data, catalog) + report_site_search_page(raw_count=len(torrents), has_more=has_more) return False, torrents except ValueError as err: self.error_detail = str(err) diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index 961d91a45..80361c53b 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -851,7 +851,7 @@ flowchart LR | 指标 | 当前值 | |---|---:| | Python 模块 | 1200 | -| 内部导入边 | 10,678 | +| 内部导入边 | 10,679 | | 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) | diff --git a/docs/site-api-integration.md b/docs/site-api-integration.md index 69708643b..51173eb95 100644 --- a/docs/site-api-integration.md +++ b/docs/site-api-integration.md @@ -423,12 +423,13 @@ MP 已有 API Key 搜索及临时下载地址的实现案例,但不会自动 猪猪改版后的正式接入使用[实验室 API](https://piggo.me/lab-api),基础地址为 `https://api.piggo.me/v1/api`。 需同时更新包含 `Piggo` 适配器的后端和 `3.0.30` 或更高的站点索引资源。 用户在网页「实验室」生成**长期存取令牌**并填入站点 API Key;API Key 为空时兼容 Token,Cookie 不参与 API 鉴权。 -搜索、最新种子、目录和用户资料均使用 POST JSON;完整 IMDb ID 通过 `imdb_id` 精确搜索,其他关键词通过 `q` 搜索。 +搜索、最新种子、目录和用户资料均使用 POST JSON。索引器收到完整 IMDb ID 或 IMDb、豆瓣、TMDB 作品链接时使用对应的精确查询字段;TMDB 链接的 `movie` 或 `tv` 与 ID 一起提交。普通关键词(包括未标明来源的纯数字)仍通过 `q` 搜索。 - 目录按 API 地址和凭据摘要隔离缓存一小时,最多 128 份。按当前分区/分类名称和作品类型映射媒体类型,未知分区保持未知。 - 分类 ID 可以在多个分区复用,按种子的实际分区解释分类成员关系,不把一个 ID 固定归属到单一分区。 - 上游新增的 `tag_ids` 按 `/catalog` 的 `tags` 映射为真实站点标签;有标签的分区按 `section_id` 查询各自字典,未配置分区标签时由站点返回全站字典。标签字典与分类目录共用凭据隔离的一小时有界缓存,未知 ID 不从标题、分类或 `taxonomy_ids` 猜造名称。 - 可见分区均能明确判型时,一个媒体类型涉及多个分区用完整分类并集保持全局分页;有未能判型的分区或所需分类不完整时不强行缩窄查询,避免漏掉纪录片、动漫、少儿等分区的资源。 +- 搜索请求每页 100 条,页码从 1 开始;向现有搜索调度报告可确认的续页状态。`total_capped` 为真时,不把计数边界当作实际末页。 - 用户资料从 `data.user` 读取,上传/下载容量文本转换为字节并计算分享率;下载量为零时分享率为零,注册时间未知。做种和下载的所有分页成功后才保存统计。 - 搜索、用户资料、连接检测、换票和种子请求共用站点配置的请求间隔与次数窗口,不按域名强制改写配置。按实验室最严格的每分钟 20 次接口限制,建议在站点设置中配置至少三秒访问间隔;远端限流仍使用既有共享冷却机制。 - 仅在执行下载时签发短时 URL;最终 GET 不携带 Bearer 或 Cookie,也不把站点返回的下载主机改为 API 主机。 diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 6a78f8ba0..50df6dfd9 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -980,8 +980,8 @@ "runtime_only": true } }, - "edge_count": 10678, - "edge_sha256": "faf9bdd85757d382b62b5b20e3148fc82cf9f95e75f1d215520eb487b26a7581", + "edge_count": 10679, + "edge_sha256": "8598166523cd5e82081a70228ab927eed7db280339941daf3c0090443bb150fc", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -8719,6 +8719,7 @@ "app.modules.indexer.spider.piggo -> app.adapters.network.http", "app.modules.indexer.spider.piggo -> app.application", "app.modules.indexer.spider.piggo -> app.application.site", + "app.modules.indexer.spider.piggo -> app.application.site.observation", "app.modules.indexer.spider.piggo -> app.application.site.throttle", "app.modules.indexer.spider.piggo -> app.domain", "app.modules.indexer.spider.piggo -> app.domain.site", diff --git a/tests/modules/indexer/test_piggo_download.py b/tests/modules/indexer/test_piggo_download.py index f65b96817..f4be759b0 100644 --- a/tests/modules/indexer/test_piggo_download.py +++ b/tests/modules/indexer/test_piggo_download.py @@ -115,7 +115,7 @@ def test_notice_gate_preserves_reason_and_never_fetches_torrent(boundary, status response.close.assert_called_once() -@pytest.mark.parametrize("status,code", [(401, 401), (200, 401), (500, 0), (302, 0)]) +@pytest.mark.parametrize("status,code", [(401, 401), (200, 401), (404, 404), (500, 0), (302, 0)]) def test_failed_ticket_never_uses_url_from_error_response(boundary, status, code): """ 错误状态即使附带看似有效的 URL,也不能向下载主机发出请求。 diff --git a/tests/modules/indexer/test_piggo_indexer.py b/tests/modules/indexer/test_piggo_indexer.py index 7096078ed..3ea2fd316 100644 --- a/tests/modules/indexer/test_piggo_indexer.py +++ b/tests/modules/indexer/test_piggo_indexer.py @@ -53,8 +53,12 @@ def _response(data, status=200, code=0): def _list(items=None, page=1): - return {"items": deepcopy([ITEM] if items is None else items), "page": page, "per_page": 100, - "pages": page, "total": 1, "total_capped": False} + """ + 构造总数未截断的最后一页;指定页号时包含之前满页的计数。 + """ + rows = deepcopy([ITEM] if items is None else items) + return {"items": rows, "page": page, "per_page": 100, "pages": page, + "total": (page - 1) * 100 + len(rows), "total_capped": False} def _recipe(enclosure): @@ -102,6 +106,9 @@ async def test_search_uses_post_json_and_official_fields(boundary, asynchronous) 同步和异步均使用当前目录、正式分类与 IMDb 参数,不访问 PHP 或前台接口。 """ spider = piggo.PiggoSpider(INDEXER) + boundary.responses[1] = _response(_list(page=3)) + request = boundary.async_request if asynchronous else boundary.request + request.post_res.side_effect = boundary.responses result = (await spider.async_search("tt33265527", MediaType.TV, page=2) if asynchronous else spider.search("tt33265527", MediaType.TV, page=2)) assert result[0] is False @@ -118,7 +125,6 @@ async def test_search_uses_post_json_and_official_fields(boundary, asynchronous) assert recipe["allow_redirects"] is False and recipe["proxy"] is True assert recipe["header"]["Authorization"] == "Bearer synthetic-piggo-key" assert recipe["header"]["User-Agent"] == "Piggo-Test" - request = boundary.async_request if asynchronous else boundary.request factory = boundary.async_factory if asynchronous else boundary.factory assert [call.kwargs for call in request.post_res.call_args_list] == [ {"url": "https://api.piggo.me/v1/api/catalog", "json": {}, "allow_redirects": False}, @@ -228,7 +234,7 @@ def test_multiple_sections_use_complete_category_union(boundary): catalog = deepcopy(CATALOG) catalog["sections"].append({"id": 44, "name": "儿童电影"}) catalog["categories"].append({"id": 404, "section_id": 44, "name": "海外"}) - boundary.request.post_res.side_effect = [_response(catalog), _response(_list())] + boundary.request.post_res.side_effect = [_response(catalog), _response(_list(page=2))] assert piggo.PiggoSpider(INDEXER).search("中文 2026", MediaType.MOVIE, page=1)[0] is False assert boundary.request.post_res.call_args.kwargs["json"] == { "page": 2, "per_page": 100, "q": "中文 2026", "category_id": [101, 404], @@ -287,25 +293,74 @@ async def test_missing_token_never_uses_cookie_or_network(boundary, asynchronous @pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("keyword,fields", [ + ("tt33265527", {"imdb_id": "tt33265527"}), + ("https://www.imdb.com/title/tt33265527/?ref_=test", {"imdb_id": "tt33265527"}), + ("https://movie.douban.com/subject/36457187/", {"douban_id": "36457187"}), + ("https://www.themoviedb.org/movie/278-title", {"tmdb_id": "278", "tmdb_kind": "movie"}), + ("https://www.themoviedb.org/tv/278", {"tmdb_id": "278", "tmdb_kind": "tv"}), + ("https://themoviedb.org.invalid/tv/278", {"q": "https themoviedb org invalid tv 278"}), + ("2026", {"q": "2026"}), +]) @pytest.mark.asyncio -async def test_indexer_module_dispatches_piggo_and_preserves_identity(boundary, monkeypatch, asynchronous): +async def test_indexer_module_dispatches_piggo_and_preserves_identity(boundary, monkeypatch, asynchronous, keyword, fields): """ - 真实索引模块可路由猪猪协议,并保留作品身份、标准种子字段和站点配置。 + 同步与异步索引入口保留精确查询、结果身份和已确认的末页状态。 + + :param boundary: 注入离线 HTTP 响应的测试夹具 + :param monkeypatch: 隔离站点健康服务和搜索预检查 + :param asynchronous: 是否走异步索引入口 + :param keyword: 搜索入口收到的原始输入 + :param fields: 应发送的作品字段或普通关键词,不包含分页及分类 """ health = Mock(async_success=AsyncMock(), async_fail=AsyncMock()) monkeypatch.setattr(indexer_module, "get_configured_site_health_service", lambda: health) helper = Mock(check=Mock(return_value=(False, ""))) monkeypatch.setattr(indexer_module, "SitesHelper", Mock(return_value=helper)) module = object.__new__(IndexerModule) - result = (await module.async_search_torrents(INDEXER, keyword="tt33265527", mtype=MediaType.TV) if asynchronous else - module.search_torrents(INDEXER, keyword="tt33265527", mtype=MediaType.TV)) + with capture_site_search_observation() as observation: + result = (await module.async_search_torrents(INDEXER, keyword=keyword, mtype=MediaType.TV) if asynchronous else + module.search_torrents(INDEXER, keyword=keyword, mtype=MediaType.TV)) assert len(result) == 1 assert (result[0].site, result[0].media_source, result[0].media_id) == (7274, MediaSource.IMDb, "tt33265527") assert _recipe(result[0].enclosure)[1].endswith("/56354/download-link") assert result[0].downloadvolumefactor is None + assert (observation.outcome, observation.has_more, observation.raw_count) == ("success", False, 1) + request = boundary.async_request if asynchronous else boundary.request + assert request.post_res.call_args.kwargs["json"] == { + "page": 1, "per_page": 100, "section_id": 22, **fields, + } (health.async_success if asynchronous else health.success).assert_called_once() +@pytest.mark.parametrize("data,expected", [ + ({"page": 100, "pages": 100, "total": 10000, "total_capped": True}, None), + ({"page": 100, "pages": 101, "total": 10000, "total_capped": True}, True), + ({"page": 100, "pages": 100, "total": 10000, "total_capped": False}, False), + ({}, None), +]) +def test_piggo_capped_total_does_not_claim_last_page(data, expected): + """ + total 到达 10000 上限时不把页数边界误判为真实末页。 + + :param data: 官方搜索分页响应 + :param expected: 应报告的续页状态 + """ + assert piggo.PiggoSpider._has_more_pages(data, 100) is expected + + +def test_piggo_rejects_wrong_response_page(boundary): + """ + 响应页号与请求不一致时拒绝整页,避免搜索重复或跳页。 + + :param boundary: 离线 HTTP 夹具 + """ + boundary.request.post_res.side_effect = [_response(CATALOG), _response(_list(page=1))] + spider = piggo.PiggoSpider(INDEXER) + assert spider.search("标题", page=1) == (True, []) + assert "错误页码" in spider.error_detail + + @pytest.mark.parametrize("domain,resource_key", [("piggo.me", "schema"), ("mirror.test", "schema"), ("mirror.test", "parser")]) @pytest.mark.parametrize("data,status,code,expected", [ ({"user": {"id": 42}}, 200, 0, "连接成功"), @@ -477,7 +532,7 @@ def test_checkpoint_restores_recipe_using_current_token(boundary): @pytest.mark.parametrize("status,payload,expected", [ (200, None, "结构无效"), (200, {"code": 0, "data": []}, "有效 data"), - (401, None, "令牌"), (429, None, "限流"), + (401, None, "通道已关闭"), (429, None, "限流"), (200, {"code": 0, "data": {"code": "notice_unread", "notice_gate": "invalid"}}, "网页端阅读"), (200, {"code": "notice_unread", "data": {}}, "网页端阅读"), (422, {"code": 422, "data": {"message": "synthetic-key 参数无效"}}, "失败"),