mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-26 05:42:04 +08:00
Merge pull request #7371 from jxxghp/fix/issue-7274
fix(indexer): support Piggo laboratory API (#7274)
This commit is contained in:
@@ -58,8 +58,12 @@ def _request_delay(site: Mapping[str, object]) -> float:
|
||||
"""
|
||||
原子申请一次站点请求,远端冷却期间直接返回原始原因。
|
||||
"""
|
||||
interval = _positive_number(site.get("limit_seconds"))
|
||||
# 猪猪实验室最严格的换票接口每分钟 20 次,所有用途共用至少三秒间隔。
|
||||
if site_rules.extract_domain(str(site.get("domain") or site.get("url") or "")) == "piggo.me":
|
||||
interval = max(interval, 3.0)
|
||||
delay, reason = _site_requests.acquire(
|
||||
_site_key(site), interval=_positive_number(site.get("limit_seconds")),
|
||||
_site_key(site), interval=interval,
|
||||
window=_positive_number(site.get("limit_interval")), count=int(_positive_number(site.get("limit_count"))),
|
||||
)
|
||||
if reason:
|
||||
|
||||
@@ -84,6 +84,8 @@ class DownloadHttpPort(Protocol):
|
||||
proxies: Optional[dict[str, str]] = None,
|
||||
timeout: Optional[int] = None,
|
||||
params: Optional[dict[str, Any]] = None,
|
||||
json_body: Optional[dict[str, Any]] = None,
|
||||
allow_redirects: bool = True,
|
||||
) -> Optional[DownloadResponsePort]:
|
||||
"""
|
||||
发送 POST 请求并保留无响应、失败响应与成功响应三态。
|
||||
@@ -95,6 +97,8 @@ class DownloadHttpPort(Protocol):
|
||||
:param proxies: 协议到代理地址的映射,None 时沿用客户端默认策略
|
||||
:param timeout: 请求超时秒数,None 时沿用客户端默认值
|
||||
:param params: 附加到 URL 的查询参数,None 表示不附加
|
||||
:param json_body: JSON 请求体,None 表示不发送,空字典仍发送空 JSON 对象
|
||||
:param allow_redirects: 是否允许重定向;认证 API 可关闭以限制凭据用途
|
||||
:return: 原始 HTTP 响应,包括非成功状态;未取得响应时为 None,调用方负责关闭
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -31,6 +31,7 @@ from app.chain.download.ports import (
|
||||
)
|
||||
from app.chain.media import MediaChain
|
||||
from app.domain import episode as episode_rules
|
||||
from app.domain import site as site_rules
|
||||
from app.domain import torrent as torrent_rules
|
||||
from app.domain.context import (
|
||||
Context,
|
||||
@@ -39,6 +40,7 @@ from app.domain.context import (
|
||||
TorrentInfo,
|
||||
)
|
||||
from app.domain.meta.metabase import MetaBase
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.runtime.cache import FileCache
|
||||
from app.runtime.events import eventmanager
|
||||
from app.runtime.log import logger
|
||||
@@ -173,6 +175,7 @@ class _DownloadResourceOwner(_DownloadOwnerBase):
|
||||
:param site_id: 原始资源的站点 ID,用于共享流控额度
|
||||
:return: 临时下载地址;换票失败时返回 None
|
||||
:raises RateLimitExceededException: 站点限流,保留原始提示供通知和冷却记录使用
|
||||
:raises ValueError: 猪猪换票失败、公告未读或下载地址无效
|
||||
"""
|
||||
match = re.search(r"\[(.*)](.*)", url)
|
||||
if not match:
|
||||
@@ -214,6 +217,8 @@ class _DownloadResourceOwner(_DownloadOwnerBase):
|
||||
params=params,
|
||||
)
|
||||
else:
|
||||
post_options = {key: request_params[name] for name, key in
|
||||
(("json", "json_body"), ("allow_redirects", "allow_redirects")) if name in request_params}
|
||||
response = http.post(
|
||||
request_url,
|
||||
ua=ua,
|
||||
@@ -221,19 +226,70 @@ class _DownloadResourceOwner(_DownloadOwnerBase):
|
||||
headers=headers,
|
||||
proxies=proxies,
|
||||
params=params,
|
||||
**post_options,
|
||||
)
|
||||
if response is None:
|
||||
if request_params.get("protocol") == "Piggo":
|
||||
raise ValueError("无法连接猪猪实验室 API")
|
||||
return None
|
||||
try:
|
||||
if error := torrent_rate_limit_error(response):
|
||||
defer_site_request(site, error)
|
||||
raise RateLimitExceededException(error)
|
||||
if not response:
|
||||
return None
|
||||
return self._indirect_download_result(response, request_params)
|
||||
return self._indirect_download_response(response, request_params, site)
|
||||
finally:
|
||||
_close_download_response(response)
|
||||
|
||||
def _indirect_download_response(self, response: DownloadResponsePort, request_params: Dict[str, Any],
|
||||
site: dict[str, object]) -> Optional[str]:
|
||||
"""
|
||||
在响应关闭前处理换票失败,猪猪公告错误保留原意,限流交给共享冷却。
|
||||
|
||||
:param response: 尚未关闭的原始换票响应
|
||||
:param request_params: 索引器编码的换票协议及结果字段
|
||||
:param site: 原始站点的不含凭据流控配置
|
||||
:return: 已校验的下载地址;其他协议沿用空结果语义
|
||||
:raises ValueError: 猪猪公告、鉴权、响应或地址失败
|
||||
:raises RateLimitExceededException: 任一协议返回明确限流
|
||||
"""
|
||||
if request_params.get("protocol") == "Piggo":
|
||||
try:
|
||||
return self._piggo_download_result(response, request_params)
|
||||
except ValueError as err:
|
||||
if torrent_rules.rate_limit_cooldown(str(err)) is not None:
|
||||
defer_site_request(site, str(err))
|
||||
raise RateLimitExceededException(str(err)) from err
|
||||
raise
|
||||
if error := torrent_rate_limit_error(response):
|
||||
defer_site_request(site, error)
|
||||
raise RateLimitExceededException(error)
|
||||
if not response:
|
||||
return None
|
||||
return self._indirect_download_result(response, request_params)
|
||||
|
||||
@staticmethod
|
||||
def _piggo_download_result(response: DownloadResponsePort, request_params: Dict[str, Any]) -> str:
|
||||
"""
|
||||
校验猪猪签发结果,不把前端下载主机替换为 API 主机。
|
||||
|
||||
:param response: 原始换票响应,包含 HTTP 403 公告等错误
|
||||
:param request_params: 仅在 API 请求中使用的认证配方
|
||||
:return: 站点返回的完整 HTTP 下载地址
|
||||
:raises ValueError: 公告、鉴权、业务失败或下载地址无效
|
||||
"""
|
||||
headers = request_params.get("header") or {}
|
||||
access_token = str(headers.get("Authorization") or "").removeprefix("Bearer ")
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
payload = None
|
||||
data = site_rules.piggo_response_data(response.status_code, payload, access_token)
|
||||
url = UrlUtils.normalize_http_url(data.get("url"))
|
||||
if url is None or len(url) > 2048:
|
||||
raise ValueError("猪猪 API 未返回有效种子下载地址")
|
||||
parts = urlparse(url)
|
||||
if parts.username is not None or parts.password is not None:
|
||||
raise ValueError("猪猪 API 返回的下载地址含无效认证信息")
|
||||
logger.info("已获取到站点临时下载地址")
|
||||
return url
|
||||
|
||||
def _indirect_download_result(self, response: DownloadResponsePort,
|
||||
request_params: Dict[str, Any]) -> Optional[str]:
|
||||
"""
|
||||
@@ -363,7 +419,7 @@ class _DownloadResourceOwner(_DownloadOwnerBase):
|
||||
cookie=site_cookie,
|
||||
site_id=torrent.site,
|
||||
)
|
||||
except RateLimitExceededException as err:
|
||||
except (RateLimitExceededException, ValueError) as err:
|
||||
return None, "", [], str(err)
|
||||
# 涉及解析地址的不使用Cookie下载种子,否则MT会出错
|
||||
site_cookie = None
|
||||
|
||||
@@ -164,11 +164,14 @@ def _wait_for_site_request(site: SiteIndexer) -> Optional[str]:
|
||||
"""
|
||||
等待站点共享额度;远端冷却不发出请求,并交回订阅调度处理。
|
||||
|
||||
猪猪适配器在每次目录和列表 HTTP 请求前自行申请额度,此处不能再预占一次。
|
||||
|
||||
:param site: 搜索站点的流控配置
|
||||
:return: 远端冷却原因,已获准请求时为 None
|
||||
"""
|
||||
try:
|
||||
wait_for_site_request(site)
|
||||
if site.get("parser") != "Piggo":
|
||||
wait_for_site_request(site)
|
||||
except RateLimitExceededException as error:
|
||||
report_site_search_outcome(attempted=False, outcome="deferred", error=str(error))
|
||||
return str(error)
|
||||
@@ -179,11 +182,14 @@ async def _async_wait_for_site_request(site: SiteIndexer) -> Optional[str]:
|
||||
"""
|
||||
异步等待同一站点额度;冷却期间保留原因,其他站点继续运行。
|
||||
|
||||
猪猪由适配器在实际 HTTP 请求前等待,不让编排层与请求层重复计费。
|
||||
|
||||
:param site: 搜索站点的流控配置
|
||||
:return: 远端冷却原因,已获准请求时为 None
|
||||
"""
|
||||
try:
|
||||
await async_wait_for_site_request(site)
|
||||
if site.get("parser") != "Piggo":
|
||||
await async_wait_for_site_request(site)
|
||||
except RateLimitExceededException as error:
|
||||
report_site_search_outcome(attempted=False, outcome="deferred", error=str(error))
|
||||
return str(error)
|
||||
|
||||
@@ -27,9 +27,11 @@ from app.application.site.contract import (
|
||||
|
||||
# 站点资源包在启动时加载,静态检查环境可能无法解析其实现。
|
||||
from app.application.site.sites import SitesHelper # pylint: disable=import-error,no-name-in-module
|
||||
from app.application.site.throttle import defer_site_request, site_request_config, wait_for_site_request
|
||||
from app.chain._interaction import InteractionChainMixin
|
||||
from app.chain.base import ChainBase
|
||||
from app.domain import site as site_rules
|
||||
from app.domain import torrent as torrent_rules
|
||||
from app.domain.site import SiteUtils
|
||||
from app.foundation import size as size_tools
|
||||
from app.foundation import url as url_tools
|
||||
@@ -37,6 +39,7 @@ from app.foundation.dom import DomUtils
|
||||
from app.runtime.events import Event, eventmanager
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.stop import runtime_stop_state
|
||||
from app.schemas.exception import RateLimitExceededException
|
||||
from app.schemas.message import Message
|
||||
from app.schemas.site import SiteUserData
|
||||
from app.schemas.types import EventType, MessageType, NotificationChannel
|
||||
@@ -298,6 +301,7 @@ class SiteChain(InteractionChainMixin, ChainBase):
|
||||
"hddolby.com": self.__hddolby_test,
|
||||
"rousi.pro": self.__rousi_test,
|
||||
"sunnypt.top": self.__sunnypt_test,
|
||||
"piggo.me": self.__piggo_test,
|
||||
"milkie.cc": self.__milkie_test,
|
||||
}
|
||||
# 资源的 schema 描述资料协议,parser 描述搜索协议;二者均可识别 API 站点。
|
||||
@@ -307,6 +311,7 @@ class SiteChain(InteractionChainMixin, ChainBase):
|
||||
"HDDolby": self.__hddolby_test,
|
||||
"RousiPro": self.__rousi_test,
|
||||
"SunnyPT": self.__sunnypt_test,
|
||||
"Piggo": self.__piggo_test,
|
||||
"Yema": self.__yema_api_test,
|
||||
"Milkie": self.__milkie_test,
|
||||
"TNode": self.__zhuque_test,
|
||||
@@ -593,6 +598,52 @@ class SiteChain(InteractionChainMixin, ChainBase):
|
||||
return False, "当前账号没有下载权限"
|
||||
return True, "连接成功"
|
||||
|
||||
def __piggo_test(self, site: SiteSnapshot) -> Tuple[bool, str]:
|
||||
"""
|
||||
用长期存取令牌检测猪猪实验室,不使用旧 PHP 首页、Cookie 或网页登录。
|
||||
|
||||
:param site: 猪猪站点配置及 API Key 或 Token
|
||||
:return: 鉴权和下载权限是否有效,以及可展示的失败说明
|
||||
"""
|
||||
access_token = site_rules.piggo_access_token(site.apikey, site.token)
|
||||
if not access_token:
|
||||
return False, site_rules.PIGGO_TOKEN_REQUIRED
|
||||
domain = site.domain or site_rules.extract_domain(site.url)
|
||||
indexer = SitesHelper().get_indexer(domain) or {}
|
||||
api_url = str(indexer.get("api_url") or site_rules.PIGGO_API_URL).rstrip("/")
|
||||
rate_site = site_request_config(site.url, site.id)
|
||||
try:
|
||||
wait_for_site_request(rate_site)
|
||||
except RateLimitExceededException as err:
|
||||
return False, str(err)
|
||||
with _open_site_response(
|
||||
method="POST", url=f"{api_url}/me", json_body={},
|
||||
headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json",
|
||||
"Content-Type": "application/json", "User-Agent": site.ua or self.runtime_config.user_agent},
|
||||
proxies=(self.runtime_config.proxy or {}) if site.proxy else {}, timeout=site.timeout or 15,
|
||||
) as response:
|
||||
if response is None:
|
||||
return False, "无法连接猪猪实验室 API"
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
payload = None
|
||||
try:
|
||||
data = site_rules.piggo_response_data(response.status_code, payload, access_token)
|
||||
user = data.get("user")
|
||||
if not isinstance(user, dict):
|
||||
return False, "猪猪 API 未返回有效用户资料"
|
||||
site_rules.piggo_integer(user.get("id"), minimum=1)
|
||||
except ValueError as err:
|
||||
if torrent_rules.rate_limit_cooldown(str(err)) is not None:
|
||||
defer_site_request(rate_site, str(err))
|
||||
return False, str(err)
|
||||
if user.get("enabled") is False:
|
||||
return False, "猪猪账号已被禁用"
|
||||
if user.get("download_allowed") is False:
|
||||
return False, "当前猪猪账号没有下载权限"
|
||||
return True, "连接成功"
|
||||
|
||||
def __yema_test(self, site: SiteSnapshot) -> Tuple[bool, str]:
|
||||
"""
|
||||
优先验证 Yema AuthKey,未配置时保留旧版 Cookie 会话探测。
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
站点地址匹配、页面登录状态与用户资料提取的纯规则。
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from lxml import etree
|
||||
@@ -17,6 +20,112 @@ _SPECIAL_SITE_DOMAINS = (
|
||||
"pt.gtk.pw",
|
||||
)
|
||||
|
||||
# 猪猪实验室公开文档指定的独立 API,不使用网页会话接口。
|
||||
PIGGO_API_URL = "https://api.piggo.me/v1/api"
|
||||
PIGGO_TOKEN_REQUIRED = "请在猪猪网页端「实验室」生成长期存取令牌,并填入站点 API Key 或 Token"
|
||||
|
||||
|
||||
def piggo_access_token(apikey: Optional[str], token: Optional[str]) -> str:
|
||||
"""
|
||||
选择猪猪长期存取令牌,优先使用非空 API Key,兼容 Token 配置。
|
||||
|
||||
:param apikey: API Key 输入框中的实验室存取令牌
|
||||
:param token: 未填写 API Key 时使用的实验室存取令牌
|
||||
:return: 去掉首尾空白的令牌;两者都未配置时为空字符串
|
||||
"""
|
||||
return str(apikey or "").strip() or str(token or "").strip()
|
||||
|
||||
|
||||
def piggo_response_data(status_code: int, payload: object, access_token: str = "") -> dict[str, Any]:
|
||||
"""
|
||||
校验猪猪实验室的 HTTP 和业务状态,阻止外层成功码掩盖必读公告。
|
||||
|
||||
:param status_code: 原始 HTTP 响应状态码,非 200 不视为读取成功
|
||||
:param payload: 已解析的 JSON 响应
|
||||
:param access_token: 本次凭据,仅用于从站点错误文本中移除可能的回显
|
||||
:return: 成功响应的 data 对象
|
||||
:raises ValueError: 鉴权、必读公告、限流、其他业务失败或响应结构无效
|
||||
"""
|
||||
# WAF 可能返回非 JSON 的鉴权或限流页,仍需保留 HTTP 失败语义。
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
data = payload.get("data")
|
||||
details = data if isinstance(data, dict) else {}
|
||||
code = str(payload.get("code"))
|
||||
inner_code = str(details.get("code", "0"))
|
||||
message = str(details.get("message") or payload.get("msg") or payload.get("message") or "").strip()
|
||||
if code == "notice_unread" or inner_code == "notice_unread":
|
||||
gate = details.get("notice_gate") or {}
|
||||
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 = "猪猪存取令牌已过期或无效,请重新生成长期存取令牌"
|
||||
elif status_code == 429 or code == "429" or inner_code == "429":
|
||||
message = f"站点限流:{message or 'HTTP 429,请稍后重试'}"
|
||||
elif not payload and status_code == 200:
|
||||
message = "猪猪 API 响应结构无效"
|
||||
elif status_code != 200 or code != "0" or inner_code != "0":
|
||||
failure_code = inner_code if inner_code != "0" else code
|
||||
message = f"猪猪 API 请求失败,HTTP {status_code},业务码 {failure_code}{f':{message}' if message else ''}"
|
||||
elif isinstance(data, dict):
|
||||
return data
|
||||
else:
|
||||
message = "猪猪 API 响应缺少有效 data"
|
||||
if access_token:
|
||||
message = message.replace(access_token, "[已隐藏]")
|
||||
raise ValueError(" ".join(message.split())[:300])
|
||||
|
||||
|
||||
def piggo_integer(value: object, minimum: int = 0) -> int:
|
||||
"""
|
||||
校验实验室的整数 ID、计数和字节字段,不截断浮点数或接受布尔值。
|
||||
|
||||
:param value: API 返回的整数或十进制整数字符串
|
||||
:param minimum: 字段下限,ID 和页码使用 1,计数及字节使用 0
|
||||
:return: 已校验的整数
|
||||
:raises ValueError: 字段缺失、格式错误或小于下限;错误不回显原值
|
||||
"""
|
||||
if not isinstance(value, (str, int)) or isinstance(value, bool) or not re.fullmatch(r"0|[1-9][0-9]*", str(value)):
|
||||
raise ValueError("猪猪 API 整数字段无效")
|
||||
number = int(value)
|
||||
if number < minimum:
|
||||
raise ValueError("猪猪 API 整数字段无效")
|
||||
return number
|
||||
|
||||
|
||||
def piggo_download_enclosure(api_url: str, torrent_id: object, access_token: str, proxy: bool = False,
|
||||
ua: Optional[str] = None) -> str:
|
||||
"""
|
||||
构造猪猪取种子时才签发 URL 的两段式配方,不预先消耗下载次数。
|
||||
|
||||
:param api_url: 实验室 API 基础地址
|
||||
:param torrent_id: 正整数站内种子 ID
|
||||
:param access_token: 当前长期存取令牌,缺失时不生成配方
|
||||
:param proxy: 换票是否使用系统代理
|
||||
:param ua: 换票请求的浏览器 User-Agent,避免被站点前置 WAF 当作默认 Python 客户端
|
||||
:return: Base64 请求配置和 download-link 地址;ID 或凭据缺失时为空字符串
|
||||
"""
|
||||
if not access_token or not re.fullmatch(r"[1-9][0-9]*", str(torrent_id or "")):
|
||||
return ""
|
||||
headers = {
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if ua:
|
||||
headers["User-Agent"] = ua
|
||||
config = {
|
||||
"method": "post",
|
||||
"cookie": False,
|
||||
"header": headers,
|
||||
"json": {},
|
||||
"allow_redirects": False,
|
||||
"proxy": proxy,
|
||||
"protocol": "Piggo",
|
||||
"result": "data.url",
|
||||
}
|
||||
encoded = base64.b64encode(json.dumps(config).encode("utf-8")).decode("ascii")
|
||||
return f"[{encoded}]{api_url.rstrip('/')}/torrents/{torrent_id}/download-link"
|
||||
|
||||
|
||||
def urls_match(first: str, second: str) -> bool:
|
||||
"""
|
||||
|
||||
@@ -28,6 +28,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.rousi import RousiSpider
|
||||
from app.modules.indexer.spider.sunnypt import SunnyPTSpider
|
||||
from app.modules.indexer.spider.tnode import TNodeSpider
|
||||
@@ -35,6 +36,7 @@ from app.modules.indexer.spider.torrentleech import TorrentLeech
|
||||
from app.modules.indexer.spider.yema import YemaSpider
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.exception import RateLimitExceededException
|
||||
from app.schemas.media import resolve_media_identity
|
||||
from app.schemas.site import SiteUserData
|
||||
from app.schemas.types import MediaSource, MediaType, ModuleType, OtherModulesType
|
||||
@@ -195,6 +197,7 @@ SPIDER_PARSER_CLASSES: dict[str, type[_PagedSpider]] = {
|
||||
"HDWing": HDWingSpider,
|
||||
"RousiPro": RousiSpider,
|
||||
"SunnyPT": SunnyPTSpider,
|
||||
"Piggo": PiggoSpider,
|
||||
"Milkie": MilkieSpider,
|
||||
"FluxTorrent": FluxTorrentSpider,
|
||||
}
|
||||
@@ -205,6 +208,7 @@ _SPECIALIZED_SEARCH_ARGUMENTS = {
|
||||
"TorrentLeech": ("keyword", "mtype", "page"),
|
||||
"mTorrent": ("keyword", "mtype", "cat", "page"),
|
||||
"SunnyPT": ("keyword", "mtype", "cat", "page"),
|
||||
"Piggo": ("keyword", "mtype", "cat", "page"),
|
||||
"Yema": ("keyword", "mtype", "cat", "page"),
|
||||
"Haidan": ("keyword", "mtype"),
|
||||
"HDDolby": ("keyword", "mtype", "cat", "page"),
|
||||
@@ -270,7 +274,7 @@ def _classify_search_failure(error: Optional[Exception]) -> str:
|
||||
return "error"
|
||||
status_code = getattr(error, "status_code", None)
|
||||
text = f"{type(error).__name__}: {error}".lower()
|
||||
if status_code == 429 or "429" in text or "rate limit" in text:
|
||||
if isinstance(error, RateLimitExceededException) or status_code == 429 or "429" in text or "rate limit" in text:
|
||||
return "rate_limited"
|
||||
if status_code == 403 or "403" in text or "forbidden" in text:
|
||||
return "forbidden"
|
||||
@@ -532,7 +536,7 @@ class IndexerModule(_ModuleBase):
|
||||
"""
|
||||
用当前站点凭据恢复候选下载信息。
|
||||
|
||||
M-Team 可从详情页中的站内 ID 重建下载配方;其他无法重建的临时票据需重新查询。
|
||||
M-Team 和猪猪可从详情页中的站内 ID 重建下载配方;其他临时票据需重新查询。
|
||||
|
||||
:param site: 当前站点配置及有效凭据
|
||||
:param record: 检查点保存的种子记录
|
||||
@@ -545,6 +549,8 @@ class IndexerModule(_ModuleBase):
|
||||
identity = torrent_rules.resource_identity(torrent)
|
||||
if site.get("parser") == "mTorrent" and identity and identity[1].startswith("id="):
|
||||
torrent.enclosure = MTorrentSpider(site).get_download_url(identity[1][3:])
|
||||
elif site.get("parser") == "Piggo" and identity and identity[1].startswith("id="):
|
||||
torrent.enclosure = PiggoSpider(site).get_download_url(identity[1][3:])
|
||||
if not torrent.enclosure and not allow_missing:
|
||||
return None
|
||||
torrent.site_cookie = site.get("cookie") or ""
|
||||
@@ -669,9 +675,11 @@ class IndexerModule(_ModuleBase):
|
||||
) -> _IndexerSearchOutcome:
|
||||
"""
|
||||
把同步、异步 I/O 结果整理为共用的搜索完成状态。
|
||||
|
||||
捕获的异常同样代表失败,不能把空结果计为一次成功搜索。
|
||||
"""
|
||||
return _IndexerSearchOutcome(
|
||||
error_flag=error_flag,
|
||||
error_flag=error_flag or error is not None,
|
||||
result=result,
|
||||
seconds=(datetime.now() - start_time).seconds,
|
||||
failure_detail=failure_detail,
|
||||
@@ -1079,7 +1087,7 @@ class IndexerModule(_ModuleBase):
|
||||
logger.debug(f"站点 {site.get('name')} 数据解析完成")
|
||||
# 站点声明的 schema 解析失败(userid 为空)时, 自动尝试其他解析器,
|
||||
# 兼容资源文件 schema 标注错误/变种站点的场景
|
||||
if not site_obj.userid and not site.get("public"):
|
||||
if not site_obj.userid and not site.get("public") and getattr(site_obj, "allow_schema_fallback", True):
|
||||
tried = {site.get("schema")}
|
||||
for site_schema in self._site_schemas:
|
||||
if (
|
||||
|
||||
@@ -67,6 +67,8 @@ class SiteSchema(Enum):
|
||||
RousiPro = "RousiPro"
|
||||
# SunnyPT 的 MoviePilot API。
|
||||
SunnyPT = "SunnyPT"
|
||||
# 猪猪的实验室长期存取令牌 API。
|
||||
Piggo = "Piggo"
|
||||
# FluxTorrent 兼容层站点。
|
||||
FluxTorrent = "FluxTorrent"
|
||||
|
||||
@@ -80,6 +82,8 @@ class SiteParserBase(metaclass=ABCMeta):
|
||||
schema: ClassVar[Optional[SiteSchema]] = None
|
||||
# 请求模式 cookie/apikey
|
||||
request_mode = "cookie"
|
||||
# 专用 API 可关闭页面模型探测,避免鉴权或公告失败后访问已移除的旧页面。
|
||||
allow_schema_fallback = True
|
||||
# 详情页默认依赖用户 ID;当前会话接口可在配置页面时关闭此前置校验。
|
||||
_user_detail_requires_userid = True
|
||||
|
||||
|
||||
293
app/modules/indexer/parser/piggo.py
Normal file
293
app/modules/indexer/parser/piggo.py
Normal file
@@ -0,0 +1,293 @@
|
||||
"""
|
||||
读取猪猪实验室用户资料及完整做种、下载分页,失败时不提交半份统计。
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.application.site.throttle import defer_site_request, site_request_config, wait_for_site_request
|
||||
from app.domain import site as site_rules
|
||||
from app.domain import torrent as torrent_rules
|
||||
from app.modules.indexer.parser import SitePage, SiteParserBase, SiteSchema
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.exception import RateLimitExceededException
|
||||
|
||||
|
||||
class PiggoSiteUserInfo(SiteParserBase):
|
||||
"""
|
||||
猪猪长期存取令牌用户数据解析器,不回退到已移除的 NexusPHP 页面。
|
||||
"""
|
||||
|
||||
schema = SiteSchema.Piggo
|
||||
request_mode = "apikey"
|
||||
allow_schema_fallback = False
|
||||
# 用户种子接口与搜索列表均允许每页最多 100 条。
|
||||
_size = 100
|
||||
|
||||
def __init__(self, site_name: Optional[str], url: str, site_cookie: Optional[str], apikey: Optional[str],
|
||||
token: Optional[str], request_utils: Optional[RequestUtils] = None, ua: Optional[str] = None,
|
||||
emulate: bool = False, proxy: Optional[bool] = None, api_url: Optional[str] = None) -> None:
|
||||
"""
|
||||
使用无网页会话的客户端读取资料,避免自动复用 Cookie。
|
||||
|
||||
:param site_name: 站点展示名称
|
||||
:param url: 网页地址,只用于归属站点流控
|
||||
:param site_cookie: 保留基类签名,不用于实验室鉴权
|
||||
:param apikey: 首选长期存取令牌
|
||||
:param token: API Key 为空时使用的长期存取令牌
|
||||
:param request_utils: 可注入的无网页会话传输客户端
|
||||
:param ua: 请求 User-Agent
|
||||
:param emulate: 保留基类签名,不启动浏览器
|
||||
:param proxy: 是否使用系统代理
|
||||
:param api_url: 资源声明的独立 API 地址
|
||||
"""
|
||||
super().__init__(site_name=site_name, url=url, site_cookie=None, apikey=apikey, token=token,
|
||||
request_utils=request_utils or RequestUtils(), ua=ua, emulate=False, proxy=proxy, api_url=api_url)
|
||||
|
||||
def parse(self) -> None:
|
||||
"""
|
||||
仅在资料和两类种子的所有分页成功后发布用户 ID,使持久化保持完整性。
|
||||
"""
|
||||
self.userid = None
|
||||
self.err_msg = None
|
||||
try:
|
||||
self._parse_site_page({})
|
||||
if not self._access_token:
|
||||
raise ValueError(site_rules.PIGGO_TOKEN_REQUIRED)
|
||||
self._parse_user_base_info(self._get_page_content(f"{self._base_url}/me"))
|
||||
self._parse_seeding_pages()
|
||||
except (ValueError, RateLimitExceededException) as err:
|
||||
self.err_msg = str(err)
|
||||
logger.warning(f"{self._site_name} 用户数据刷新失败:{self.err_msg}")
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
def _parse_site_page(self, html_text: SitePage) -> None:
|
||||
"""
|
||||
配置独立 API 和共享流控,Cookie、浏览器仿真及旧页面参数不参与请求。
|
||||
|
||||
:param html_text: 保留基类签名,不读取 HTML
|
||||
"""
|
||||
self._base_url = str(self._api_url or site_rules.PIGGO_API_URL).rstrip("/")
|
||||
self._access_token = site_rules.piggo_access_token(self.apikey, self.token)
|
||||
self._rate_site = site_request_config(self._site_url)
|
||||
self._profile: dict[str, Any] = {}
|
||||
|
||||
def _get_page_content(self, url: str, params: Optional[dict[str, object]] = None,
|
||||
headers: Optional[dict[str, Optional[str]]] = None,
|
||||
method: Optional[str] = None) -> str:
|
||||
"""
|
||||
强制 POST JSON,先校验 HTTP 和内层业务码再交给解析流程,并关闭响应。
|
||||
|
||||
:param url: 当前实验室接口的完整地址
|
||||
:param params: JSON 参数对象,未提供时发送空对象
|
||||
:param headers: 保留基类签名,认证头只由长期令牌构造
|
||||
:param method: 保留基类签名,始终使用 POST
|
||||
:return: 已校验业务对象的 JSON 文本,响应在返回或失败前关闭
|
||||
:raises ValueError: 连接、鉴权、公告或信封无效
|
||||
:raises RateLimitExceededException: 远端限流,已建立共享冷却
|
||||
"""
|
||||
wait_for_site_request(self._rate_site)
|
||||
response = self._request_utils.post_res(
|
||||
url=url, json=params or {}, cookies=None, timeout=60, allow_redirects=False,
|
||||
proxies=get_runtime_setting("PROXY") if self._proxy else None,
|
||||
headers={"Authorization": f"Bearer {self._access_token}", "Accept": "application/json",
|
||||
"Content-Type": "application/json", "User-Agent": self._ua},
|
||||
)
|
||||
try:
|
||||
if response is None:
|
||||
raise ValueError("无法连接猪猪实验室 API")
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
payload = None
|
||||
try:
|
||||
data = site_rules.piggo_response_data(response.status_code, payload, self._access_token)
|
||||
except ValueError as err:
|
||||
if torrent_rules.rate_limit_cooldown(str(err)) is not None:
|
||||
defer_site_request(self._rate_site, str(err))
|
||||
raise RateLimitExceededException(str(err)) from err
|
||||
raise
|
||||
return json.dumps(data)
|
||||
finally:
|
||||
if response is not None:
|
||||
response.close()
|
||||
|
||||
def _parse_user_base_info(self, html_text: SitePage) -> None:
|
||||
"""
|
||||
暂存已校验的用户资料,官方缺少的注册时间不编造,分享率按流量计算。
|
||||
|
||||
:param html_text: 已通过实验室信封校验的资料 JSON 文本
|
||||
:raises ValueError: 身份、流量、等级或魔力值无效;不公开半份资料
|
||||
"""
|
||||
if not isinstance(html_text, str):
|
||||
raise ValueError("猪猪用户资料响应结构无效")
|
||||
data = json.loads(html_text)
|
||||
user = data.get("user") if isinstance(data, dict) else None
|
||||
if not isinstance(user, dict) or not user.get("id") or not user.get("username"):
|
||||
raise ValueError("猪猪 API 未返回有效用户资料")
|
||||
if user.get("enabled") is False:
|
||||
raise ValueError("猪猪账号已被禁用")
|
||||
stats = user.get("stats")
|
||||
level = user.get("class")
|
||||
if not isinstance(stats, dict) or not isinstance(level, dict):
|
||||
raise ValueError("猪猪用户资料缺少流量或等级信息")
|
||||
if not isinstance(user["username"], str) or not user["username"].strip():
|
||||
raise ValueError("猪猪 API 未返回有效用户名")
|
||||
user_id = site_rules.piggo_integer(user["id"], minimum=1)
|
||||
upload = self._traffic_size(stats.get("uploaded"))
|
||||
download = self._traffic_size(stats.get("downloaded"))
|
||||
try:
|
||||
bonus = float(stats.get("bonus", 0))
|
||||
except (TypeError, ValueError, OverflowError) as err:
|
||||
raise ValueError("猪猪用户魔力值无效") from err
|
||||
if not math.isfinite(bonus) or bonus < 0 or not isinstance(level.get("name"), str):
|
||||
raise ValueError("猪猪用户魔力值或等级信息无效")
|
||||
self._profile = {"userid": user_id, "username": user["username"], "user_level": level["name"],
|
||||
"upload": upload, "download": download, "bonus": bonus}
|
||||
|
||||
def _traffic_size(self, value: object) -> int:
|
||||
"""
|
||||
校验流量容量文本后复用字节转换,缺失或无效值不能被默认为零。
|
||||
|
||||
:param value: 整数、有限小数或带 KB 至 PB 单位的容量文本
|
||||
:return: 非负整数字节数
|
||||
:raises ValueError: 容量缺失或格式无效;不回显账户原始值
|
||||
"""
|
||||
text = str(value).strip()
|
||||
if not re.fullmatch(r"\d+(?:,\d{3})*(?:\.\d+)?\s*(?:[KMGTP]I?B|B)?", text, re.IGNORECASE):
|
||||
raise ValueError("猪猪用户资料缺少有效上传或下载流量")
|
||||
try:
|
||||
return self.num_filesize(text)
|
||||
except (ValueError, OverflowError) as err:
|
||||
raise ValueError("猪猪用户流量容量无效") from err
|
||||
|
||||
@classmethod
|
||||
def _torrent_page(cls, data: object, kind: str, page: int) -> tuple[list[dict[str, Any]], tuple[int, int, int]]:
|
||||
"""
|
||||
校验单页元数据和必要条目,空列表也必须有完整的分页信息。
|
||||
|
||||
:param data: 已通过信封校验的本人种子响应
|
||||
:param kind: 本次请求的 seeding 或 leeching 类型
|
||||
:param page: 本次请求的页码,从 1 开始
|
||||
:return: 当前页规范化的条目及页数、总条数、分页容量
|
||||
:raises ValueError: 错页、缺条目、无效容量或必要字段无效
|
||||
"""
|
||||
if not isinstance(data, dict) or data.get("kind") != kind:
|
||||
raise ValueError("猪猪种子分页类型无效")
|
||||
pages = site_rules.piggo_integer(data.get("pages"))
|
||||
total = site_rules.piggo_integer(data.get("total"))
|
||||
per_page = site_rules.piggo_integer(data.get("per_page"), minimum=1)
|
||||
if per_page > cls._size or site_rules.piggo_integer(data.get("page"), minimum=1) != page:
|
||||
raise ValueError("猪猪种子分页容量或页码无效")
|
||||
expected_pages = max(1, (total + per_page - 1) // per_page)
|
||||
if pages != expected_pages and not (total == 0 and pages == 0):
|
||||
raise ValueError("猪猪种子页数无效")
|
||||
page_items = data.get("items")
|
||||
if not isinstance(page_items, list) or len(page_items) != min(per_page, max(0, total - (page - 1) * per_page)):
|
||||
raise ValueError("猪猪种子分页不完整")
|
||||
items = []
|
||||
for item in page_items:
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError("猪猪种子分页条目无效")
|
||||
items.append({"id": site_rules.piggo_integer(item.get("id"), minimum=1),
|
||||
"size": site_rules.piggo_integer(item.get("size")),
|
||||
"seeders": site_rules.piggo_integer(item.get("seeders", 0))})
|
||||
return items, (pages, total, per_page)
|
||||
|
||||
def _read_torrents(self, kind: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
严格读取全部分页,拒绝错页、重复条目、变化的总数和缺失分页元数据。
|
||||
|
||||
:param kind: seeding 或 leeching 类型
|
||||
:return: 所有已校验的条目,只保留统计需要的 ID、大小和做种人数
|
||||
:raises ValueError: 任一页无效或总条数、页数、分页容量发生变化
|
||||
"""
|
||||
items: list[dict[str, Any]] = []
|
||||
page, expected = 1, None
|
||||
ids = set()
|
||||
while True:
|
||||
data = json.loads(self._get_page_content(
|
||||
f"{self._base_url}/me/torrents", {"kind": kind, "page": page, "per_page": self._size},
|
||||
))
|
||||
try:
|
||||
page_items, metadata = self._torrent_page(data, kind, page)
|
||||
if expected is not None and expected != metadata:
|
||||
raise ValueError("猪猪种子分页发生变化")
|
||||
expected = metadata
|
||||
for item in page_items:
|
||||
torrent_id = item["id"]
|
||||
if torrent_id in ids:
|
||||
raise ValueError("猪猪种子分页数据无效")
|
||||
ids.add(torrent_id)
|
||||
items.extend(page_items)
|
||||
except (KeyError, TypeError, ValueError) as err:
|
||||
raise ValueError("猪猪用户种子分页不完整或发生变化,请稍后重试") from err
|
||||
if page >= metadata[0]:
|
||||
return items
|
||||
page += 1
|
||||
|
||||
def _parse_seeding_pages(self) -> None:
|
||||
"""
|
||||
两类种子全部读取成功后一次更新统计,用户 ID 最后赋值作为保存准入事实。
|
||||
"""
|
||||
seeding = self._read_torrents("seeding")
|
||||
leeching = self._read_torrents("leeching")
|
||||
seeding_info = [[int(item.get("seeders") or 0), int(item["size"])] for item in seeding]
|
||||
self.username = self._profile["username"]
|
||||
self.user_level = self._profile["user_level"]
|
||||
self.upload = self._profile["upload"]
|
||||
self.download = self._profile["download"]
|
||||
self.bonus = self._profile["bonus"]
|
||||
self.ratio = self.upload / self.download if self.download else 0.0
|
||||
self.seeding, self.seeding_info = len(seeding), seeding_info
|
||||
self.seeding_size = sum(item[1] for item in seeding_info)
|
||||
self.leeching, self.leeching_size = len(leeching), sum(int(item["size"]) for item in leeching)
|
||||
self.userid = self._profile["userid"]
|
||||
|
||||
def _parse_user_traffic_info(self, html_text: str) -> None:
|
||||
"""
|
||||
不访问独立流量页面,流量已由实验室用户资料提供。
|
||||
|
||||
:param html_text: 保留基类签名,不读取 HTML
|
||||
"""
|
||||
|
||||
def _parse_user_detail_info(self, html_text: str) -> None:
|
||||
"""
|
||||
不访问旧用户详情页,实验室未提供的注册时间保持为空。
|
||||
|
||||
:param html_text: 保留基类签名,不读取 HTML
|
||||
"""
|
||||
|
||||
def _parse_user_torrent_seeding_info(self, html_text: str, multi_page: bool = False) -> Optional[str]:
|
||||
"""
|
||||
不使用 HTML 翻页,全部做种及下载分页由专用流程读取。
|
||||
|
||||
:param html_text: 保留基类签名,不读取 HTML
|
||||
:param multi_page: 保留基类签名,不采用页面翻页
|
||||
:return: 没有 HTML 后续页面
|
||||
"""
|
||||
return None
|
||||
|
||||
def _parse_message_unread_links(self, html_text: str, msg_links: list[str]) -> Optional[str]:
|
||||
"""
|
||||
实验室没有站内信列表接口,不访问旧消息页面,也不自动阅读公告。
|
||||
|
||||
:param html_text: 保留基类签名,不读取 HTML
|
||||
:param msg_links: 不追加不存在的站内信链接
|
||||
:return: 没有站内信后续页面
|
||||
"""
|
||||
return None
|
||||
|
||||
def _parse_message_content(self, html_text: str) -> tuple[Optional[str], Optional[str], Optional[str]]:
|
||||
"""
|
||||
没有站内信详情接口,保持空消息,不绕过站点必读公告。
|
||||
|
||||
:param html_text: 保留基类签名,不读取 HTML
|
||||
:return: 空标题、时间和正文
|
||||
"""
|
||||
return None, None, None
|
||||
422
app/modules/indexer/spider/piggo.py
Normal file
422
app/modules/indexer/spider/piggo.py
Normal file
@@ -0,0 +1,422 @@
|
||||
"""
|
||||
通过猪猪实验室 API 搜索和浏览种子,使用账号可见目录解释分类。
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from typing import Any, Optional, TypeAlias, cast
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from app.adapters.network.http import AsyncRequestUtils, RequestUtils
|
||||
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
|
||||
from app.foundation import temporal as time_tools
|
||||
from app.runtime.cache import MemoryBackend
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.exception import RateLimitExceededException
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
# 分类 ID 可在不同分区复用,以(分区 ID、分类 ID)保存成员关系;不保存账号或令牌。
|
||||
_Catalog: TypeAlias = tuple[dict[int, MediaType], dict[tuple[int, int], MediaType]]
|
||||
|
||||
|
||||
class PiggoSpider:
|
||||
"""
|
||||
猪猪长期存取令牌索引器;搜索结果不宣称 API 未提供的促销信息。
|
||||
"""
|
||||
|
||||
# 官方列表上限为每页 100 条;目录缓存最多保留 128 份,每份一小时。
|
||||
_size = 100
|
||||
_catalog_cache = MemoryBackend(maxsize=128, ttl=3600)
|
||||
_catalog_region = "piggo-catalog"
|
||||
|
||||
def __init__(self, indexer: dict[str, Any]) -> None:
|
||||
"""
|
||||
保存认证和请求配置,目录缓存按 API 地址及凭据摘要隔离。
|
||||
|
||||
:param indexer: 合并用户凭据的站点资源配置
|
||||
"""
|
||||
self._name = indexer.get("name") or "猪猪"
|
||||
self._site_url = str(indexer.get("domain") or "https://piggo.me/")
|
||||
self._api_url = str(indexer.get("api_url") or site_rules.PIGGO_API_URL).rstrip("/")
|
||||
self._token = site_rules.piggo_access_token(indexer.get("apikey"), indexer.get("token"))
|
||||
self._proxy = get_runtime_setting("PROXY") if indexer.get("proxy") else None
|
||||
self._use_proxy = bool(indexer.get("proxy"))
|
||||
self._ua = indexer.get("ua") or get_runtime_setting("USER_AGENT")
|
||||
self._timeout = indexer.get("timeout") or 15
|
||||
self._rate_site = {key: indexer.get(key) for key in
|
||||
("id", "domain", "limit_seconds", "limit_interval", "limit_count")}
|
||||
self._rate_site["domain"] = site_rules.extract_domain(self._site_url)
|
||||
self._cache_key = hashlib.sha256(f"{self._api_url}\n{self._token}".encode("utf-8")).hexdigest()
|
||||
self.error_detail: Optional[str] = None
|
||||
|
||||
@classmethod
|
||||
def get_search_page_size(cls, keyword: Optional[str] = None) -> Optional[int]:
|
||||
"""
|
||||
返回搜索与最新种子列表共用的分页容量。
|
||||
|
||||
:param keyword: 保留统一入口签名,不改变猪猪分页容量
|
||||
:return: 每页最多 100 条
|
||||
"""
|
||||
return cls._size
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
"""
|
||||
为实验室请求构造 Bearer 和 JSON 头,不包含 Cookie 或前台签名。
|
||||
|
||||
:return: 本次请求的独立头部字典
|
||||
"""
|
||||
return {"Authorization": f"Bearer {self._token}", "Accept": "application/json",
|
||||
"Content-Type": "application/json", "User-Agent": self._ua}
|
||||
|
||||
def _response_data(self, response: Any) -> dict[str, Any]:
|
||||
"""
|
||||
读取有效业务数据,限流同步到搜索、用户数据和下载共用的站点额度。
|
||||
|
||||
:param response: 同步或异步传输返回的响应,None 表示连接失败
|
||||
:return: 成功信封中的 data 对象
|
||||
:raises ValueError: API 或响应结构失败,同时删除当前凭据的目录缓存
|
||||
:raises RateLimitExceededException: 远端限流已经交给共享冷却
|
||||
"""
|
||||
if response is None:
|
||||
raise ValueError("无法连接猪猪实验室 API")
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
payload = None
|
||||
try:
|
||||
data = site_rules.piggo_response_data(response.status_code, payload, self._token)
|
||||
except ValueError as err:
|
||||
self._catalog_cache.delete(self._cache_key, region=self._catalog_region)
|
||||
if torrent_rules.rate_limit_cooldown(str(err)) is not None:
|
||||
defer_site_request(self._rate_site, str(err))
|
||||
raise RateLimitExceededException(str(err)) from err
|
||||
raise
|
||||
return data
|
||||
|
||||
def _request(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
发起一次同步 POST JSON,不携带 Cookie、不跟随认证请求重定向。
|
||||
|
||||
:param path: 实验室根地址下的相对接口路径
|
||||
:param body: JSON 参数对象;空对象仍发送 JSON 正文
|
||||
:return: 已校验的业务数据,响应在返回或失败前关闭
|
||||
"""
|
||||
wait_for_site_request(self._rate_site)
|
||||
response = RequestUtils(headers=self._headers(), proxies=self._proxy, timeout=self._timeout).post_res(
|
||||
url=f"{self._api_url}/{path}", json=body, allow_redirects=False,
|
||||
)
|
||||
try:
|
||||
return self._response_data(response)
|
||||
finally:
|
||||
if response is not None:
|
||||
response.close()
|
||||
|
||||
async def _async_request(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
使用异步传输和共享流控发送 POST JSON,并在结束时释放响应。
|
||||
|
||||
:param path: 实验室根地址下的相对接口路径
|
||||
:param body: JSON 参数对象;空对象仍发送 JSON 正文
|
||||
:return: 已校验的业务数据,取消或失败时沿用同一响应释放流程
|
||||
"""
|
||||
await async_wait_for_site_request(self._rate_site)
|
||||
response = await AsyncRequestUtils(
|
||||
headers=self._headers(), proxies=self._proxy, timeout=self._timeout,
|
||||
).post_res(url=f"{self._api_url}/{path}", json=body, allow_redirects=False)
|
||||
try:
|
||||
return self._response_data(response)
|
||||
finally:
|
||||
if response is not None:
|
||||
await response.aclose()
|
||||
|
||||
@staticmethod
|
||||
def _name_media_type(name: str) -> MediaType:
|
||||
"""
|
||||
根据当前目录名称识别媒体类型,动漫和纪录片等歧义名称不强行归类。
|
||||
|
||||
:param name: 当前可见的分区或分类名称
|
||||
:return: 可明确识别的媒体类型,歧义或陌生名称返回未知
|
||||
"""
|
||||
name = name.casefold()
|
||||
for media_type, labels in (
|
||||
(MediaType.MOVIE, ("电影", "電影", "movie", "cinema")),
|
||||
(MediaType.TV, ("剧", "劇", "综艺", "綜藝", "series", "television", "tv")),
|
||||
(MediaType.MUSIC, ("音乐", "音樂", "music", "演唱会", "演唱會", "concert")),
|
||||
):
|
||||
if any(label in name for label in labels):
|
||||
return media_type
|
||||
return MediaType.UNKNOWN
|
||||
|
||||
@classmethod
|
||||
def _parse_catalog(cls, data: dict[str, Any]) -> _Catalog:
|
||||
"""
|
||||
校验并转换当前账号可见目录,不使用旧版固定分类 ID。
|
||||
|
||||
:param data: 正式 catalog 响应的 sections 和 categories
|
||||
:return: 分区类型映射,以及分区与分类成员关系的类型映射
|
||||
:raises ValueError: 目录缺字段、整数无效、重复成员关系或分类引用未知分区
|
||||
"""
|
||||
sections, categories = data.get("sections"), data.get("categories")
|
||||
if not isinstance(sections, list) or not isinstance(categories, list):
|
||||
raise ValueError("猪猪目录响应结构无效")
|
||||
section_map: dict[int, MediaType] = {}
|
||||
category_map: dict[tuple[int, int], MediaType] = {}
|
||||
try:
|
||||
for section in sections:
|
||||
section_id = site_rules.piggo_integer(section["id"], minimum=1)
|
||||
if section_id in section_map or not isinstance(section["name"], str):
|
||||
raise ValueError("猪猪分区数据无效")
|
||||
section_map[section_id] = cls._name_media_type(section["name"])
|
||||
for category in categories:
|
||||
category_id = site_rules.piggo_integer(category["id"], minimum=1)
|
||||
section_id = site_rules.piggo_integer(category["section_id"], minimum=1)
|
||||
membership = section_id, category_id
|
||||
if membership in category_map or section_id not in section_map or not isinstance(category["name"], str):
|
||||
raise ValueError("猪猪分类数据无效")
|
||||
media_type = cls._name_media_type(category["name"])
|
||||
category_map[membership] = media_type if media_type != MediaType.UNKNOWN else section_map[section_id]
|
||||
except (KeyError, TypeError, ValueError) as err:
|
||||
raise ValueError("猪猪目录响应结构无效") from err
|
||||
return section_map, category_map
|
||||
|
||||
def _load_catalog(self) -> _Catalog:
|
||||
"""
|
||||
读取有界内存缓存;失败目录不缓存,也不回退到旧分类。
|
||||
|
||||
:return: 当前 API 地址和凭据对应的可见目录
|
||||
"""
|
||||
catalog = cast(Optional[_Catalog], self._catalog_cache.get(self._cache_key, region=self._catalog_region))
|
||||
if catalog is None:
|
||||
catalog = self._parse_catalog(self._request("catalog", {}))
|
||||
self._catalog_cache.set(self._cache_key, catalog, region=self._catalog_region)
|
||||
return catalog
|
||||
|
||||
async def _async_load_catalog(self) -> _Catalog:
|
||||
"""
|
||||
异步获取目录,缓存仅在短临界区访问内存,不阻塞执行网络操作。
|
||||
|
||||
:return: 当前 API 地址和凭据对应的可见目录
|
||||
"""
|
||||
catalog = cast(Optional[_Catalog], self._catalog_cache.get(self._cache_key, region=self._catalog_region))
|
||||
if catalog is None:
|
||||
catalog = self._parse_catalog(await self._async_request("catalog", {}))
|
||||
self._catalog_cache.set(self._cache_key, catalog, region=self._catalog_region)
|
||||
return catalog
|
||||
|
||||
def _params(self, keyword: Optional[str], mtype: Optional[MediaType], cat: Optional[str],
|
||||
page: Optional[int], catalog: _Catalog) -> dict[str, Any]:
|
||||
"""
|
||||
构造正式搜索字段,多个分区用分类并集保持全局分页,无法完整限定时不过滤。
|
||||
|
||||
显式分类优先于媒体类型;不合并多路分区分页,也不把分类 ID 当作分区 ID。
|
||||
|
||||
:param keyword: 标题关键词或完整 IMDb ID,空白时不添加搜索字段
|
||||
:param mtype: 可按目录解释的媒体类型,未知类型不缩窄查询
|
||||
:param cat: 显式分类 ID,可用逗号分隔
|
||||
:param page: MoviePilot 从零开始的页码
|
||||
:param catalog: 当前账号可见目录
|
||||
:return: 使用正式字段的 POST JSON 参数
|
||||
:raises ValueError: 显式分类 ID 格式无效
|
||||
"""
|
||||
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
|
||||
if cat:
|
||||
if not re.fullmatch(r"[1-9][0-9]*(\s*,\s*[1-9][0-9]*)*", cat.strip()):
|
||||
raise ValueError("猪猪分类须填写当前目录中的正整数 ID,以逗号分隔")
|
||||
params["category_id"] = list(dict.fromkeys(int(value) for value in cat.split(",")))
|
||||
return params
|
||||
if mtype is None or mtype == MediaType.UNKNOWN:
|
||||
return params
|
||||
sections, categories = catalog
|
||||
# 纪录片、动漫、少儿等分区可同时含电影和剧集,未能判型时不排除这些可见资源。
|
||||
if MediaType.UNKNOWN in sections.values():
|
||||
return params
|
||||
matched = {section_id for section_id, media_type in sections.items() if media_type == mtype}
|
||||
if len(matched) == 1:
|
||||
params["section_id"] = next(iter(matched))
|
||||
elif matched and all(any(section_id == membership[0] for membership in categories) for section_id in matched):
|
||||
params["category_id"] = list(dict.fromkeys(category_id for section_id, category_id in categories
|
||||
if section_id in matched))
|
||||
elif mtype and not matched:
|
||||
category_ids = list(dict.fromkeys(membership[1] for membership, media_type in categories.items()
|
||||
if media_type == mtype))
|
||||
if category_ids:
|
||||
params["category_id"] = category_ids
|
||||
return params
|
||||
|
||||
@staticmethod
|
||||
def _torrent_media_type(item: dict[str, Any], media: dict[str, Any], catalog: _Catalog) -> MediaType:
|
||||
"""
|
||||
优先使用作品类型,再解释当前目录;未知或相互冲突的分类不强行归类。
|
||||
|
||||
:param item: 实验室返回的种子条目
|
||||
:param media: 条目中的作品标识对象
|
||||
:param catalog: 当前账号可见的分区和分类映射
|
||||
:return: 作品或目录可确认的媒体类型,否则为未知
|
||||
"""
|
||||
media_type = {"movie": MediaType.MOVIE, "tv": MediaType.TV}.get(str(media.get("tmdb_kind") or ""))
|
||||
if media_type is not None:
|
||||
return media_type
|
||||
sections, categories = catalog
|
||||
category_ids = item.get("category_ids", [])
|
||||
if not isinstance(category_ids, list):
|
||||
raise ValueError("猪猪种子分类数据无效")
|
||||
section_id = site_rules.piggo_integer(item.get("section_id", 0))
|
||||
known = set()
|
||||
for cid in category_ids:
|
||||
category = categories.get((section_id, site_rules.piggo_integer(cid, minimum=1)))
|
||||
if category is not None and category != MediaType.UNKNOWN:
|
||||
known.add(category)
|
||||
if len(known) == 1:
|
||||
return next(iter(known))
|
||||
if known:
|
||||
return MediaType.UNKNOWN
|
||||
return sections.get(section_id, MediaType.UNKNOWN)
|
||||
|
||||
@staticmethod
|
||||
def _media_identity(media: dict[str, Any]) -> tuple[Optional[MediaSource], Optional[str]]:
|
||||
"""
|
||||
读取正式作品 ID,拒绝把对象、布尔值或任意文本作为精确识别身份。
|
||||
|
||||
:param media: 实验室条目中的作品对象
|
||||
:return: 按 IMDb、豆瓣、TMDB 顺序选定的身份,全部缺失时返回空值
|
||||
:raises ValueError: 被选中的来源 ID 格式无效;错误不回显原值
|
||||
"""
|
||||
for key, source in (("imdb", MediaSource.IMDb), ("douban", MediaSource.Douban), ("tmdb", MediaSource.TMDB)):
|
||||
value = media.get(key)
|
||||
if value in (None, ""):
|
||||
continue
|
||||
if not isinstance(value, (str, int)) or isinstance(value, bool):
|
||||
raise ValueError("猪猪作品标识数据无效")
|
||||
media_id = str(value).strip()
|
||||
pattern = r"tt[0-9]+" if source == MediaSource.IMDb else r"[1-9][0-9]*"
|
||||
if not re.fullmatch(pattern, media_id, re.IGNORECASE):
|
||||
raise ValueError("猪猪作品标识数据无效")
|
||||
return source, media_id.lower() if source == MediaSource.IMDb else media_id
|
||||
return None, None
|
||||
|
||||
def _parse_item(self, item: dict[str, Any], catalog: _Catalog) -> dict[str, Any]:
|
||||
"""
|
||||
转换正式种子字段,不编造实验室未提供的海报或促销倍率。
|
||||
|
||||
:param item: 当前页的一条种子记录
|
||||
:param catalog: 当前账号可见目录
|
||||
:return: 可直接构造 TorrentInfo 的字段
|
||||
:raises ValueError: 必要字段、整数或媒体对象无效
|
||||
"""
|
||||
torrent_id = site_rules.piggo_integer(item["id"], minimum=1)
|
||||
if not isinstance(item["name"], str) or not item["name"].strip():
|
||||
raise ValueError("猪猪种子名称无效")
|
||||
for field in ("small_descr", "page_url", "added_at"):
|
||||
if item.get(field) is not None and not isinstance(item[field], str):
|
||||
raise ValueError("猪猪种子文本字段无效")
|
||||
media = item.get("media")
|
||||
if media is None:
|
||||
media = {}
|
||||
if not isinstance(media, dict):
|
||||
raise ValueError("猪猪作品标识数据无效")
|
||||
media_type = self._torrent_media_type(item, media, catalog)
|
||||
media_source, media_id = self._media_identity(media)
|
||||
return {
|
||||
"title": item["name"], "description": item.get("small_descr"),
|
||||
"enclosure": self.get_download_url(torrent_id),
|
||||
"page_url": item.get("page_url") or urljoin(self._site_url, f"detail/{torrent_id}"),
|
||||
"pubdate": time_tools.normalize_datetime(item.get("added_at")),
|
||||
"size": site_rules.piggo_integer(item["size"]),
|
||||
"seeders": site_rules.piggo_integer(item.get("seeders", 0)),
|
||||
"peers": site_rules.piggo_integer(item.get("leechers", 0)),
|
||||
"grabs": site_rules.piggo_integer(item.get("times_completed", 0)),
|
||||
"media_source": media_source, "media_id": media_id, "category": media_type.value,
|
||||
}
|
||||
|
||||
def _parse_result(self, data: dict[str, Any], catalog: _Catalog) -> list[dict[str, Any]]:
|
||||
"""
|
||||
校验整页种子后发布结果,坏条目不能形成半页成功或提前结束自动分页。
|
||||
|
||||
:param data: 已通过信封校验的列表响应
|
||||
:param catalog: 当前账号可见目录
|
||||
:return: 当前页的标准种子字段列表
|
||||
:raises ValueError: 列表结构、重复 ID 或条目字段无效
|
||||
"""
|
||||
items = data.get("items")
|
||||
if not isinstance(items, list) or len(items) > self._size:
|
||||
raise ValueError("猪猪种子列表响应缺少有效 items")
|
||||
torrents: list[dict[str, Any]] = []
|
||||
ids: set[int] = set()
|
||||
try:
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError("猪猪种子条目无效")
|
||||
torrent_id = site_rules.piggo_integer(item["id"], minimum=1)
|
||||
if torrent_id in ids:
|
||||
raise ValueError("猪猪种子 ID 重复")
|
||||
ids.add(torrent_id)
|
||||
torrents.append(self._parse_item(item, catalog))
|
||||
except (KeyError, TypeError, ValueError, AttributeError) as err:
|
||||
raise ValueError("猪猪种子列表响应结构无效") from err
|
||||
return torrents
|
||||
|
||||
def search(self, keyword: Optional[str], mtype: Optional[MediaType] = None, cat: Optional[str] = None,
|
||||
page: Optional[int] = 0) -> tuple[bool, list[dict[str, Any]]]:
|
||||
"""
|
||||
同步搜索或浏览最新种子,不执行网页登录或提前签发下载链接。
|
||||
|
||||
:param keyword: 标题关键词或完整 IMDb ID;为空时浏览最新种子
|
||||
:param mtype: 用当前目录限定的媒体类型
|
||||
:param cat: 显式分类 ID,可用逗号分隔
|
||||
:param page: 从零开始的 MoviePilot 页码
|
||||
:return: 是否失败及当前页标准种子列表
|
||||
:raises RateLimitExceededException: 限流交给索引模块分类和订阅调度,保留原始原因
|
||||
"""
|
||||
self.error_detail = None
|
||||
try:
|
||||
if not self._token:
|
||||
raise ValueError(site_rules.PIGGO_TOKEN_REQUIRED)
|
||||
catalog = self._load_catalog()
|
||||
data = self._request("torrents", self._params(keyword, mtype, cat, page, catalog))
|
||||
return False, self._parse_result(data, catalog)
|
||||
except ValueError as err:
|
||||
self.error_detail = str(err)
|
||||
logger.warning(f"{self._name} 搜索失败:{self.error_detail}")
|
||||
return True, []
|
||||
|
||||
async def async_search(self, keyword: Optional[str], mtype: Optional[MediaType] = None,
|
||||
cat: Optional[str] = None, page: Optional[int] = 0) -> tuple[bool, list[dict[str, Any]]]:
|
||||
"""
|
||||
异步执行同一实验室搜索协议,取消时不在后台继续请求。
|
||||
|
||||
:param keyword: 标题关键词或完整 IMDb ID;为空时浏览最新种子
|
||||
:param mtype: 用当前目录限定的媒体类型
|
||||
:param cat: 显式分类 ID,可用逗号分隔
|
||||
:param page: 从零开始的 MoviePilot 页码
|
||||
:return: 是否失败及当前页标准种子列表
|
||||
:raises RateLimitExceededException: 限流交给索引模块分类和订阅调度,保留原始原因
|
||||
"""
|
||||
self.error_detail = None
|
||||
try:
|
||||
if not self._token:
|
||||
raise ValueError(site_rules.PIGGO_TOKEN_REQUIRED)
|
||||
catalog = await self._async_load_catalog()
|
||||
data = await self._async_request("torrents", self._params(keyword, mtype, cat, page, catalog))
|
||||
return False, self._parse_result(data, catalog)
|
||||
except ValueError as err:
|
||||
self.error_detail = str(err)
|
||||
logger.warning(f"{self._name} 搜索失败:{self.error_detail}")
|
||||
return True, []
|
||||
|
||||
def get_download_url(self, torrent_id: object) -> str:
|
||||
"""
|
||||
用当前凭据生成两段式下载配方,最终 GET 不携带 Bearer。
|
||||
|
||||
:param torrent_id: 正整数站内种子 ID
|
||||
:return: 编码的 download-link 请求;ID 或令牌缺失时为空字符串
|
||||
"""
|
||||
return site_rules.piggo_download_enclosure(self._api_url, torrent_id, self._token, self._use_proxy, ua=self._ua)
|
||||
@@ -383,11 +383,16 @@ class _DownloadHttpAdapter:
|
||||
) -> RequestUtils:
|
||||
"""
|
||||
按下载链传入的代理、认证与超时参数构造一次请求。
|
||||
|
||||
自定义头部不能让 RequestUtils 忽略独立传入的 UA;显式 User-Agent 头仍优先。
|
||||
"""
|
||||
request_headers = dict(headers) if headers is not None else None
|
||||
if request_headers is not None and ua and not any(key.lower() == "user-agent" for key in request_headers):
|
||||
request_headers["User-Agent"] = ua
|
||||
options: dict[str, Any] = {
|
||||
"cookies": cookies,
|
||||
"ua": ua,
|
||||
"headers": headers,
|
||||
"headers": request_headers,
|
||||
"proxies": proxies,
|
||||
"timeout": timeout,
|
||||
}
|
||||
@@ -470,14 +475,20 @@ class _DownloadHttpAdapter:
|
||||
proxies: Optional[dict[str, str]] = None,
|
||||
timeout: Optional[int] = None,
|
||||
params: Optional[dict[str, Any]] = None,
|
||||
json_body: Optional[dict[str, Any]] = None,
|
||||
allow_redirects: bool = True,
|
||||
) -> Optional[DownloadResponsePort]:
|
||||
"""
|
||||
发送下载链 POST 请求并原样保留响应三态。
|
||||
发送下载链 POST,区分 URL 查询和 JSON 正文,并保留响应三态。
|
||||
"""
|
||||
request = self._request(cookies=cookies, ua=ua, headers=headers, proxies=proxies, timeout=timeout)
|
||||
kwargs: dict[str, Any] = {}
|
||||
if params is not None:
|
||||
kwargs["params"] = params
|
||||
if json_body is not None:
|
||||
kwargs["json"] = json_body
|
||||
if not allow_redirects:
|
||||
kwargs["allow_redirects"] = False
|
||||
response = request.post_res(url, **kwargs)
|
||||
return cast(Optional[DownloadResponsePort], response)
|
||||
|
||||
|
||||
@@ -824,8 +824,8 @@ flowchart LR
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1154 |
|
||||
| 内部导入边 | 9,998 |
|
||||
| Python 模块 | 1156 |
|
||||
| 内部导入边 | 10,041 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) |
|
||||
|
||||
@@ -417,3 +417,18 @@ MP 已有 API Key 搜索及临时下载地址的实现案例,但不会自动
|
||||
- [MTorrent 适配示例](https://github.com/jxxghp/MoviePilot/blob/52203041f7be117ddb3ec0ce8fcb7862ade26bda/app/modules/indexer/spider/mtorrent.py):搜索结果转换与下载凭据生成。
|
||||
|
||||
实现参考核对日期为 2026 年 11 月 4 日。本文的接口路径、字段设计和验收建议是供双方协商的接入需求,不代表每个现有站点都已实现全部能力。
|
||||
|
||||
### 猪猪实验室适配
|
||||
|
||||
猪猪改版后的正式接入使用[实验室 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` 搜索。
|
||||
|
||||
- 目录按 API 地址和凭据摘要隔离缓存一小时,最多 128 份。按当前分区/分类名称和作品类型映射媒体类型,未知分区保持未知。
|
||||
- 分类 ID 可以在多个分区复用,按种子的实际分区解释分类成员关系,不把一个 ID 固定归属到单一分区。
|
||||
- 可见分区均能明确判型时,一个媒体类型涉及多个分区用完整分类并集保持全局分页;有未能判型的分区或所需分类不完整时不强行缩窄查询,避免漏掉纪录片、动漫、少儿等分区的资源。
|
||||
- 用户资料从 `data.user` 读取,上传/下载容量文本转换为字节并计算分享率;下载量为零时分享率为零,注册时间未知。做种和下载的所有分页成功后才保存统计。
|
||||
- 搜索、用户资料、换票和种子请求共用至少三秒访问间隔;更严格的用户流控仍生效,远端限流使用既有冷却机制。
|
||||
- 仅在执行下载时签发短时 URL;最终 GET 不携带 Bearer 或 Cookie,也不把站点返回的下载主机改为 API 主机。
|
||||
- 必读公告必须由用户在网页端阅读,不自动确认公告或回退访问旧 PHP 页面。实验室未提供的促销、字幕、站内信接口不作推断。
|
||||
|
||||
@@ -962,8 +962,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 9998,
|
||||
"edge_sha256": "8cb8153efde498e93ea98858b9e7d15b5606dab4bd1341dee73c1b62c5baea22",
|
||||
"edge_count": 10041,
|
||||
"edge_sha256": "af042e41b67199773775728be43fe76e202277ffbaad1b256bbb46ce8784c468",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -4892,7 +4892,10 @@
|
||||
"app.chain.download.submission -> app.domain.episode",
|
||||
"app.chain.download.submission -> app.domain.meta",
|
||||
"app.chain.download.submission -> app.domain.meta.metabase",
|
||||
"app.chain.download.submission -> app.domain.site",
|
||||
"app.chain.download.submission -> app.domain.torrent",
|
||||
"app.chain.download.submission -> app.foundation",
|
||||
"app.chain.download.submission -> app.foundation.url",
|
||||
"app.chain.download.submission -> app.runtime",
|
||||
"app.chain.download.submission -> app.runtime.cache",
|
||||
"app.chain.download.submission -> app.runtime.events",
|
||||
@@ -5557,11 +5560,13 @@
|
||||
"app.chain.site -> app.application.security.cookie",
|
||||
"app.chain.site -> app.application.site",
|
||||
"app.chain.site -> app.application.site.contract",
|
||||
"app.chain.site -> app.application.site.throttle",
|
||||
"app.chain.site -> app.chain",
|
||||
"app.chain.site -> app.chain._interaction",
|
||||
"app.chain.site -> app.chain.base",
|
||||
"app.chain.site -> app.domain",
|
||||
"app.chain.site -> app.domain.site",
|
||||
"app.chain.site -> app.domain.torrent",
|
||||
"app.chain.site -> app.foundation",
|
||||
"app.chain.site -> app.foundation.dom",
|
||||
"app.chain.site -> app.foundation.size",
|
||||
@@ -5571,6 +5576,7 @@
|
||||
"app.chain.site -> app.runtime.log",
|
||||
"app.chain.site -> app.runtime.stop",
|
||||
"app.chain.site -> app.schemas",
|
||||
"app.chain.site -> app.schemas.exception",
|
||||
"app.chain.site -> app.schemas.message",
|
||||
"app.chain.site -> app.schemas.site",
|
||||
"app.chain.site -> app.schemas.types",
|
||||
@@ -7845,6 +7851,7 @@
|
||||
"app.modules.indexer -> app.modules.indexer.spider.hdwing",
|
||||
"app.modules.indexer -> app.modules.indexer.spider.milkie",
|
||||
"app.modules.indexer -> app.modules.indexer.spider.mtorrent",
|
||||
"app.modules.indexer -> app.modules.indexer.spider.piggo",
|
||||
"app.modules.indexer -> app.modules.indexer.spider.rousi",
|
||||
"app.modules.indexer -> app.modules.indexer.spider.sunnypt",
|
||||
"app.modules.indexer -> app.modules.indexer.spider.tnode",
|
||||
@@ -7854,6 +7861,7 @@
|
||||
"app.modules.indexer -> app.runtime.log",
|
||||
"app.modules.indexer -> app.runtime.settings",
|
||||
"app.modules.indexer -> app.schemas",
|
||||
"app.modules.indexer -> app.schemas.exception",
|
||||
"app.modules.indexer -> app.schemas.media",
|
||||
"app.modules.indexer -> app.schemas.site",
|
||||
"app.modules.indexer -> app.schemas.types",
|
||||
@@ -7971,6 +7979,23 @@
|
||||
"app.modules.indexer.parser.nexus_rabbit -> app.modules.indexer.parser",
|
||||
"app.modules.indexer.parser.nexus_rabbit -> app.runtime",
|
||||
"app.modules.indexer.parser.nexus_rabbit -> app.runtime.log",
|
||||
"app.modules.indexer.parser.piggo -> app.adapters",
|
||||
"app.modules.indexer.parser.piggo -> app.adapters.network",
|
||||
"app.modules.indexer.parser.piggo -> app.adapters.network.http",
|
||||
"app.modules.indexer.parser.piggo -> app.application",
|
||||
"app.modules.indexer.parser.piggo -> app.application.site",
|
||||
"app.modules.indexer.parser.piggo -> app.application.site.throttle",
|
||||
"app.modules.indexer.parser.piggo -> app.domain",
|
||||
"app.modules.indexer.parser.piggo -> app.domain.site",
|
||||
"app.modules.indexer.parser.piggo -> app.domain.torrent",
|
||||
"app.modules.indexer.parser.piggo -> app.modules",
|
||||
"app.modules.indexer.parser.piggo -> app.modules.indexer",
|
||||
"app.modules.indexer.parser.piggo -> app.modules.indexer.parser",
|
||||
"app.modules.indexer.parser.piggo -> app.runtime",
|
||||
"app.modules.indexer.parser.piggo -> app.runtime.log",
|
||||
"app.modules.indexer.parser.piggo -> app.runtime.settings",
|
||||
"app.modules.indexer.parser.piggo -> app.schemas",
|
||||
"app.modules.indexer.parser.piggo -> app.schemas.exception",
|
||||
"app.modules.indexer.parser.rousi -> app.adapters",
|
||||
"app.modules.indexer.parser.rousi -> app.adapters.network",
|
||||
"app.modules.indexer.parser.rousi -> app.adapters.network.http",
|
||||
@@ -8119,6 +8144,24 @@
|
||||
"app.modules.indexer.spider.mtorrent -> app.runtime.settings",
|
||||
"app.modules.indexer.spider.mtorrent -> app.schemas",
|
||||
"app.modules.indexer.spider.mtorrent -> app.schemas.types",
|
||||
"app.modules.indexer.spider.piggo -> app.adapters",
|
||||
"app.modules.indexer.spider.piggo -> app.adapters.network",
|
||||
"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.throttle",
|
||||
"app.modules.indexer.spider.piggo -> app.domain",
|
||||
"app.modules.indexer.spider.piggo -> app.domain.site",
|
||||
"app.modules.indexer.spider.piggo -> app.domain.torrent",
|
||||
"app.modules.indexer.spider.piggo -> app.foundation",
|
||||
"app.modules.indexer.spider.piggo -> app.foundation.temporal",
|
||||
"app.modules.indexer.spider.piggo -> app.runtime",
|
||||
"app.modules.indexer.spider.piggo -> app.runtime.cache",
|
||||
"app.modules.indexer.spider.piggo -> app.runtime.log",
|
||||
"app.modules.indexer.spider.piggo -> app.runtime.settings",
|
||||
"app.modules.indexer.spider.piggo -> app.schemas",
|
||||
"app.modules.indexer.spider.piggo -> app.schemas.exception",
|
||||
"app.modules.indexer.spider.piggo -> app.schemas.types",
|
||||
"app.modules.indexer.spider.rousi -> app.adapters",
|
||||
"app.modules.indexer.spider.rousi -> app.adapters.network",
|
||||
"app.modules.indexer.spider.rousi -> app.adapters.network.http",
|
||||
@@ -10964,7 +11007,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1154,
|
||||
"module_count": 1156,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -11758,6 +11801,7 @@
|
||||
"app.modules.indexer.parser.nexus_php",
|
||||
"app.modules.indexer.parser.nexus_project",
|
||||
"app.modules.indexer.parser.nexus_rabbit",
|
||||
"app.modules.indexer.parser.piggo",
|
||||
"app.modules.indexer.parser.rousi",
|
||||
"app.modules.indexer.parser.small_horse",
|
||||
"app.modules.indexer.parser.sunnypt",
|
||||
@@ -11773,6 +11817,7 @@
|
||||
"app.modules.indexer.spider.hdwing",
|
||||
"app.modules.indexer.spider.milkie",
|
||||
"app.modules.indexer.spider.mtorrent",
|
||||
"app.modules.indexer.spider.piggo",
|
||||
"app.modules.indexer.spider.rousi",
|
||||
"app.modules.indexer.spider.sunnypt",
|
||||
"app.modules.indexer.spider.tnode",
|
||||
|
||||
@@ -251,7 +251,7 @@ def test_torrent_search_preserves_result_and_status_parity(
|
||||
|
||||
def test_torrent_search_preserves_exception_fallback_parity(monkeypatch):
|
||||
"""
|
||||
解析器抛错后两种入口都沿用空结果与非解析错误统计语义
|
||||
解析器抛错后两种入口均返回空结果并记录失败,不能把捕获的异常计为搜索成功。
|
||||
"""
|
||||
events = []
|
||||
_install_search_observers(monkeypatch, events)
|
||||
@@ -289,7 +289,7 @@ def test_torrent_search_preserves_exception_fallback_parity(monkeypatch):
|
||||
|
||||
assert sync_result == async_result == []
|
||||
assert sync_events == events
|
||||
assert events[-2][0:3] == ("statistic", "Parity", False)
|
||||
assert events[-2][0:3] == ("statistic", "Parity", True)
|
||||
assert events[-1][0:3] == ("parse", "Parity", ())
|
||||
|
||||
|
||||
|
||||
323
tests/test_piggo_download.py
Normal file
323
tests/test_piggo_download.py
Normal file
@@ -0,0 +1,323 @@
|
||||
"""
|
||||
猪猪换票、最终种子 GET、公告错误和最小共享访问间隔的离线回归。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import contextmanager
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
from requests import Response
|
||||
|
||||
import app.application.site.throttle as throttle
|
||||
import app.application.torrent.download as torrent_download
|
||||
import app.chain.download.submission as submission
|
||||
import app.chain.search.provider as provider
|
||||
import app.chain.site as site_chain
|
||||
import app.modules.indexer.spider.piggo as piggo_spider
|
||||
import app.startup.composition.network as network
|
||||
from app.adapters.cache.backends import FileBackend
|
||||
from app.application.site.contract import SiteSnapshot
|
||||
from app.chain.download import DownloadChain
|
||||
from app.chain.site import SiteChain
|
||||
from app.domain import site as site_rules
|
||||
from app.domain.context import TorrentInfo
|
||||
from app.modules.indexer.parser.piggo import PiggoSiteUserInfo
|
||||
from app.runtime.cache import MemoryBackend
|
||||
from app.runtime.rate import RequestRateLimiter
|
||||
from app.schemas.site import Site
|
||||
|
||||
# 合成临时下载 URL 与合法单文件种子,不对应真实站点下载或配额。
|
||||
DOWNLOAD_URL = "https://piggo.me/v1/web/torrents/56354/dl/synthetic-ticket"
|
||||
CONTENT = b"d4:infod4:name10:Series.mkv6:lengthi1eee"
|
||||
|
||||
|
||||
def _response(content, status=200):
|
||||
response = Response()
|
||||
response.status_code = status
|
||||
response._content = json.dumps(content).encode() if isinstance(content, dict) else content
|
||||
response.encoding = "utf-8"
|
||||
response.close = Mock()
|
||||
return response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def boundary(monkeypatch, tmp_path):
|
||||
"""
|
||||
私有缓存和虚拟时钟保留真实下载链、种子解析器与站点流控。
|
||||
"""
|
||||
clock = SimpleNamespace(now=100.0, waits=[])
|
||||
|
||||
def advance(delay):
|
||||
clock.waits.append(delay)
|
||||
clock.now += delay
|
||||
|
||||
monkeypatch.setattr(throttle.time, "monotonic", lambda: clock.now)
|
||||
monkeypatch.setattr(throttle.time, "sleep", advance)
|
||||
monkeypatch.setattr(throttle, "_site_requests", RequestRateLimiter())
|
||||
query = Mock()
|
||||
query.get_sync.return_value = Site(id=7274, domain="piggo.me")
|
||||
query.get_by_domain_sync.return_value = query.get_sync.return_value
|
||||
monkeypatch.setattr(throttle, "get_configured_site_query_service", lambda: query)
|
||||
cache = FileBackend(tmp_path)
|
||||
monkeypatch.setattr(torrent_download, "FileCache", lambda **_kwargs: cache)
|
||||
monkeypatch.setattr(submission, "FileCache", lambda **_kwargs: cache)
|
||||
ticket_response = _response({"code": 0, "data": {"url": DOWNLOAD_URL}, "msg": "ok"})
|
||||
ticket = Mock(post=Mock(return_value=ticket_response))
|
||||
monkeypatch.setattr(submission, "_download_ports_snapshot", lambda: (ticket, Mock()))
|
||||
content_response = _response(CONTENT)
|
||||
port = Mock(request=Mock(return_value=content_response))
|
||||
monkeypatch.setattr(torrent_download, "_require_torrent_port", lambda: port)
|
||||
chain = object.__new__(DownloadChain)
|
||||
chain.post_message = Mock()
|
||||
torrent = TorrentInfo(site=7274, site_name="猪猪", title="Series", site_cookie="unused-cookie", site_ua="Piggo-Test",
|
||||
page_url="https://piggo.me/detail/56354",
|
||||
enclosure=site_rules.piggo_download_enclosure(site_rules.PIGGO_API_URL, 56354, "synthetic-key"))
|
||||
return SimpleNamespace(chain=chain, torrent=torrent, ticket=ticket, ticket_response=ticket_response,
|
||||
port=port, content_response=content_response, clock=clock, cache=cache)
|
||||
|
||||
|
||||
def test_recipe_posts_json_and_final_get_has_no_credentials(boundary):
|
||||
"""
|
||||
换票只发送 Bearer 和空 JSON,最终 GET 使用返回的网页主机且不携带 Cookie 或令牌。
|
||||
"""
|
||||
assert boundary.chain.download_torrent(boundary.torrent)[0] == CONTENT
|
||||
request = boundary.ticket.post.call_args.kwargs
|
||||
assert request["json_body"] == {} and request["allow_redirects"] is False
|
||||
assert request["headers"]["Authorization"] == "Bearer synthetic-key"
|
||||
assert request["cookies"] is None and request["params"] is None
|
||||
final = boundary.port.request.call_args.kwargs
|
||||
assert final["method"] == "GET" and final["url"] == DOWNLOAD_URL
|
||||
assert final["cookie"] is None and "headers" not in final
|
||||
assert boundary.clock.waits == [3]
|
||||
boundary.ticket_response.close.assert_called_once()
|
||||
assert boundary.chain.download_torrent(boundary.torrent)[0] == CONTENT
|
||||
boundary.ticket.post.assert_called_once()
|
||||
boundary.port.request.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [200, 403])
|
||||
def test_notice_gate_preserves_reason_and_never_fetches_torrent(boundary, status):
|
||||
"""
|
||||
外层 code 为零不能掩盖必读公告,不自动确认或请求种子文件。
|
||||
"""
|
||||
response = _response({"code": 0, "data": {"code": "notice_unread", "notice_gate": {"title": "公告标题"}}, "msg": "请先阅读公告"}, status)
|
||||
boundary.ticket.post.return_value = response
|
||||
errors = []
|
||||
assert boundary.chain.download_torrent(boundary.torrent, on_failure=errors.append) == (None, "", [])
|
||||
assert len(errors) == 1 and "网页端阅读" in errors[0] and "公告标题" in errors[0]
|
||||
assert errors[0] in boundary.chain.post_message.call_args.args[0].text
|
||||
boundary.port.request.assert_not_called()
|
||||
response.close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status,code", [(401, 401), (200, 401), (500, 0), (302, 0)])
|
||||
def test_failed_ticket_never_uses_url_from_error_response(boundary, status, code):
|
||||
"""
|
||||
错误状态即使附带看似有效的 URL,也不能向下载主机发出请求。
|
||||
"""
|
||||
response = _response({"code": code, "data": {"url": DOWNLOAD_URL}}, status)
|
||||
boundary.ticket.post.return_value = response
|
||||
errors = []
|
||||
assert boundary.chain.download_torrent(boundary.torrent, on_failure=errors.append) == (None, "", [])
|
||||
assert errors
|
||||
boundary.port.request.assert_not_called()
|
||||
response.close.assert_called_once()
|
||||
|
||||
|
||||
def test_rate_limit_cools_down_search_and_download(boundary):
|
||||
"""
|
||||
猪猪换票返回 429 时保存原始原因,整个站点进入既有冷却而不是立即重试。
|
||||
"""
|
||||
boundary.ticket.post.return_value = _response({"code": 429, "data": {"message": "请在 60 秒后重试"}}, 429)
|
||||
errors = []
|
||||
boundary.chain.download_torrent(boundary.torrent, on_failure=errors.append)
|
||||
boundary.chain.download_torrent(boundary.torrent, on_failure=errors.append)
|
||||
assert len(errors) == 2 and errors[0] == errors[1]
|
||||
assert "限流" in errors[0] and "60 秒" in errors[0]
|
||||
boundary.ticket.post.assert_called_once()
|
||||
boundary.port.request.assert_not_called()
|
||||
assert throttle.site_request_cooldown({"id": 7274}) == 3600
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", ["/relative", "magnet:?xt=invalid", "javascript:alert(1)", "https://user:password@piggo.me/file", "https://piggo.me:bad/file"])
|
||||
def test_invalid_download_url_is_rejected(boundary, url):
|
||||
"""
|
||||
下载链接必须是合法绝对 HTTP 地址,不接受脚本、磁力、内嵌认证或坏端口。
|
||||
"""
|
||||
boundary.ticket.post.return_value = _response({"code": 0, "data": {"url": url}})
|
||||
errors = []
|
||||
boundary.chain.download_torrent(boundary.torrent, on_failure=errors.append)
|
||||
assert errors and "地址" in errors[0]
|
||||
boundary.port.request.assert_not_called()
|
||||
|
||||
|
||||
def test_post_adapter_preserves_empty_json_and_disables_redirects(monkeypatch):
|
||||
"""
|
||||
真实下载传输适配器必须透传空 JSON,而不是把它当作缺失请求体。
|
||||
"""
|
||||
adapter = network._DownloadHttpAdapter()
|
||||
request = Mock()
|
||||
constructor = Mock(return_value=request)
|
||||
monkeypatch.setattr(adapter, "_request", constructor)
|
||||
response = adapter.post("https://api.piggo.me/v1/api/me", headers={"Authorization": "Bearer synthetic-key"},
|
||||
json_body={}, allow_redirects=False)
|
||||
assert response is request.post_res.return_value
|
||||
request.post_res.assert_called_once_with("https://api.piggo.me/v1/api/me", json={}, allow_redirects=False)
|
||||
assert constructor.call_args.kwargs["cookies"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [200, 401, 429])
|
||||
def test_non_json_ticket_keeps_http_failure_semantics(boundary, status):
|
||||
"""
|
||||
WAF 的非 JSON 响应不能被误解析为下载地址,401 与 429 仍保留鉴权和限流含义。
|
||||
"""
|
||||
boundary.ticket.post.return_value = _response(b"<html>WAF</html>", status)
|
||||
errors = []
|
||||
boundary.chain.download_torrent(boundary.torrent, on_failure=errors.append)
|
||||
assert errors
|
||||
assert {200: "结构无效", 401: "令牌", 429: "限流"}[status] in errors[0]
|
||||
boundary.port.request.assert_not_called()
|
||||
|
||||
|
||||
def test_missing_ticket_response_reports_failure(boundary):
|
||||
"""
|
||||
无响应也必须交回下载失败原因,不静默返回空结果。
|
||||
"""
|
||||
boundary.ticket.post.return_value = None
|
||||
errors = []
|
||||
boundary.chain.download_torrent(boundary.torrent, on_failure=errors.append)
|
||||
assert errors == ["无法连接猪猪实验室 API"]
|
||||
boundary.port.request.assert_not_called()
|
||||
|
||||
|
||||
def _isolate_catalog(monkeypatch):
|
||||
"""
|
||||
只替换猪猪缓存实例的区域字典,不清除其他用例或运行时的缓存。
|
||||
"""
|
||||
cache = MemoryBackend(maxsize=128, ttl=3600)
|
||||
monkeypatch.setattr(cache, "_region_caches", {})
|
||||
monkeypatch.setattr(piggo_spider.PiggoSpider, "_catalog_cache", cache)
|
||||
|
||||
|
||||
def test_every_actual_piggo_request_shares_one_slot(boundary, monkeypatch):
|
||||
"""
|
||||
搜索、资料、连接检测、换票和最终 GET 每次只计费一次,编排层不重复占额。
|
||||
"""
|
||||
_isolate_catalog(monkeypatch)
|
||||
starts = []
|
||||
responses = iter([
|
||||
_response({"code": 0, "data": {"sections": [], "categories": []}}),
|
||||
_response({"code": 0, "data": {"items": []}}),
|
||||
])
|
||||
|
||||
def search_request(**_kwargs):
|
||||
starts.append(boundary.clock.now)
|
||||
return next(responses)
|
||||
|
||||
request = Mock(post_res=Mock(side_effect=search_request))
|
||||
monkeypatch.setattr(piggo_spider, "RequestUtils", Mock(return_value=request))
|
||||
indexer = {"id": 7274, "domain": "https://piggo.me/", "parser": "Piggo", "apikey": "synthetic-key", "ua": "Piggo-Test"}
|
||||
spider = piggo_spider.PiggoSpider(indexer)
|
||||
owner = Mock(search_site_torrents=Mock(side_effect=lambda **kwargs: spider.search(kwargs["keyword"])[1]))
|
||||
assert provider._search_site_page(owner, site=indexer, keyword="Series", media_type=None, page=0) == []
|
||||
|
||||
pages = iter([
|
||||
_response({"code": 0, "data": {"user": {"id": 42, "username": "synthetic-user", "class": {"name": "主管"},
|
||||
"stats": {"uploaded": 0, "downloaded": 0}}}}),
|
||||
_response({"code": 0, "data": {"kind": "seeding", "items": [], "page": 1, "pages": 1, "per_page": 100, "total": 0}}),
|
||||
_response({"code": 0, "data": {"kind": "leeching", "items": [], "page": 1, "pages": 1, "per_page": 100, "total": 0}}),
|
||||
])
|
||||
|
||||
def profile_request(**_kwargs):
|
||||
starts.append(boundary.clock.now)
|
||||
return next(pages)
|
||||
|
||||
parser = PiggoSiteUserInfo("猪猪", "https://piggo.me/", "unused-cookie", "synthetic-key", None,
|
||||
request_utils=Mock(post_res=Mock(side_effect=profile_request)), ua="Piggo-Test")
|
||||
parser.parse()
|
||||
assert parser.userid == 42
|
||||
|
||||
@contextmanager
|
||||
def probe(**_kwargs):
|
||||
starts.append(boundary.clock.now)
|
||||
yield _response({"code": 0, "data": {"user": {"id": 42}}})
|
||||
|
||||
monkeypatch.setattr(site_chain, "_open_site_response", probe)
|
||||
monkeypatch.setattr(site_chain, "SitesHelper", Mock(return_value=Mock(get_indexer=Mock(return_value={}))))
|
||||
chain = SiteChain()
|
||||
site = SiteSnapshot(id=7274, name="猪猪", domain="piggo.me", url="https://piggo.me/", apikey="synthetic-key")
|
||||
assert chain._SiteChain__piggo_test(site) == (True, "连接成功")
|
||||
boundary.ticket.post.side_effect = lambda *_args, **_kwargs: starts.append(boundary.clock.now) or boundary.ticket_response
|
||||
boundary.port.request.side_effect = lambda **_kwargs: starts.append(boundary.clock.now) or boundary.content_response
|
||||
assert boundary.chain.download_torrent(boundary.torrent)[0] == CONTENT
|
||||
assert starts == [100, 103, 106, 109, 112, 115, 118, 121]
|
||||
assert boundary.clock.waits == [3] * 7
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_search_cancellation_does_not_send_next_request(boundary, monkeypatch):
|
||||
"""
|
||||
异步搜索在列表请求前取消时只完成已发出的目录请求,不留下后台 HTTP 请求。
|
||||
"""
|
||||
_isolate_catalog(monkeypatch)
|
||||
response = _response({"code": 0, "data": {"sections": [], "categories": []}})
|
||||
response.aclose = AsyncMock()
|
||||
request = Mock(post_res=AsyncMock(return_value=response))
|
||||
monkeypatch.setattr(piggo_spider, "AsyncRequestUtils", Mock(return_value=request))
|
||||
sleeping = asyncio.Event()
|
||||
|
||||
async def blocked_sleep(_delay):
|
||||
sleeping.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
monkeypatch.setattr(throttle.asyncio, "sleep", blocked_sleep)
|
||||
indexer = {"id": 7274, "domain": "https://piggo.me/", "parser": "Piggo", "apikey": "synthetic-key", "ua": "Piggo-Test"}
|
||||
assert await provider._async_wait_for_site_request(indexer) is None
|
||||
task = asyncio.create_task(piggo_spider.PiggoSpider(indexer).async_search(None))
|
||||
try:
|
||||
await sleeping.wait()
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
request.post_res.assert_awaited_once()
|
||||
assert request.post_res.call_args.kwargs["url"].endswith("/catalog")
|
||||
response.aclose.assert_awaited_once()
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header_ua", [None, "custom-UA"])
|
||||
def test_post_adapter_preserves_ua_with_custom_headers(monkeypatch, header_ua):
|
||||
"""
|
||||
认证请求的自定义头部不能丢弃 UA;显式 UA 头优先且不修改调用方字典。
|
||||
"""
|
||||
request = Mock()
|
||||
constructor = Mock(return_value=request)
|
||||
monkeypatch.setattr(network, "RequestUtils", constructor)
|
||||
headers = {"Authorization": "Bearer synthetic-key"}
|
||||
if header_ua:
|
||||
headers["user-agent"] = header_ua
|
||||
before = headers.copy()
|
||||
network._DownloadHttpAdapter().post("https://api.piggo.me/v1/api/me", ua="browser-UA", headers=headers,
|
||||
json_body={}, allow_redirects=False)
|
||||
actual = constructor.call_args.kwargs["headers"]
|
||||
assert actual == (before if header_ua else dict(before, **{"User-Agent": "browser-UA"}))
|
||||
assert headers == before
|
||||
request.post_res.assert_called_once_with("https://api.piggo.me/v1/api/me", json={}, allow_redirects=False)
|
||||
|
||||
|
||||
def test_feed_balance_error_is_preserved_without_downloading(boundary):
|
||||
"""
|
||||
收费种签发被站点余额规则拒绝时保留原因,不绕过规则,也不拉取文件。
|
||||
"""
|
||||
reason = "饲料不足,需要 100"
|
||||
boundary.ticket.post.return_value = _response({"code": 422, "data": {"message": reason}, "msg": reason}, 422)
|
||||
errors = []
|
||||
boundary.chain.download_torrent(boundary.torrent, on_failure=errors.append)
|
||||
assert len(errors) == 1 and reason in errors[0]
|
||||
boundary.port.request.assert_not_called()
|
||||
496
tests/test_piggo_indexer.py
Normal file
496
tests/test_piggo_indexer.py
Normal file
@@ -0,0 +1,496 @@
|
||||
"""
|
||||
验证猪猪实验室接口的搜索、用户统计、连接检测与两段式下载。
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, Mock
|
||||
|
||||
import pytest
|
||||
from requests import Response
|
||||
|
||||
import app.chain.site as site_chain
|
||||
import app.modules.indexer as indexer_module
|
||||
import app.modules.indexer.spider.piggo as piggo
|
||||
from app.application.site.contract import SiteSnapshot
|
||||
from app.application.site.observation import capture_site_search_observation
|
||||
from app.chain.site import SiteChain
|
||||
from app.domain import site as site_rules
|
||||
from app.domain.context import TorrentInfo
|
||||
from app.modules.indexer import _SPECIALIZED_SEARCH_ARGUMENTS, SPIDER_PARSER_CLASSES, IndexerModule
|
||||
from app.modules.indexer.parser import SiteSchema
|
||||
from app.runtime.cache import MemoryBackend
|
||||
from app.schemas.exception import RateLimitExceededException
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
# 合成的测试凭据不对应任何真实账号。
|
||||
INDEXER = {"id": 7274, "name": "猪猪", "domain": "https://piggo.me/", "url": "https://piggo.me/",
|
||||
"parser": "Piggo", "schema": "Piggo", "apikey": "synthetic-piggo-key", "cookie": "unused-cookie",
|
||||
"ua": "Piggo-Test", "proxy": True, "timeout": 25}
|
||||
CATALOG = {"sections": [{"id": 11, "name": "电影"}, {"id": 22, "name": "剧集"}, {"id": 33, "name": "音乐"}],
|
||||
"categories": [{"id": 101, "section_id": 11, "name": "华语"},
|
||||
{"id": 202, "section_id": 22, "name": "海外"},
|
||||
{"id": 303, "section_id": 33, "name": "无损"}], "taxonomies": []}
|
||||
ITEM = {"id": 56354, "name": "The Silent Rift 2026 S01 Complete 2160p", "small_descr": "全16集",
|
||||
"cover": "https://image.test/poster.jpg", "size": 78726120572, "section_id": 22,
|
||||
"category_ids": [202], "media": {"douban": "36457187", "imdb": "tt33265527", "tmdb": "", "tmdb_kind": ""},
|
||||
"seeders": 3, "leechers": 0, "times_completed": 9, "added_at": "2026-04-21 10:26:30",
|
||||
"page_url": "https://piggo.me/detail/56354"}
|
||||
|
||||
|
||||
def _response(data, status=200, code=0):
|
||||
"""
|
||||
回放实验室信封,保留 HTTP 错误的真实布尔语义。
|
||||
"""
|
||||
response = Response()
|
||||
response.status_code = status
|
||||
response._content = json.dumps({"code": code, "data": data, "msg": "ok"}).encode()
|
||||
response.encoding = "utf-8"
|
||||
response.close = Mock()
|
||||
response.aclose = AsyncMock()
|
||||
return response
|
||||
|
||||
|
||||
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}
|
||||
|
||||
|
||||
def _recipe(enclosure):
|
||||
encoded, url = enclosure[1:].split("]", 1)
|
||||
return json.loads(base64.b64decode(encoded)), url
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def boundary(monkeypatch):
|
||||
"""
|
||||
隔离网络、目录缓存和等待,保留真实协议构造与响应解析。
|
||||
"""
|
||||
cache = MemoryBackend(maxsize=128, ttl=3600)
|
||||
monkeypatch.setattr(cache, "_region_caches", {})
|
||||
monkeypatch.setattr(piggo.PiggoSpider, "_catalog_cache", cache)
|
||||
monkeypatch.setattr(piggo, "get_runtime_setting", lambda key: {"USER_AGENT": "Default-UA", "PROXY": {"https": "proxy"}}[key])
|
||||
wait = Mock()
|
||||
async_wait = AsyncMock()
|
||||
monkeypatch.setattr(piggo, "wait_for_site_request", wait)
|
||||
monkeypatch.setattr(piggo, "async_wait_for_site_request", async_wait)
|
||||
responses = [_response(CATALOG), _response(_list())]
|
||||
request = Mock(post_res=Mock(side_effect=responses))
|
||||
factory = Mock(return_value=request)
|
||||
monkeypatch.setattr(piggo, "RequestUtils", factory)
|
||||
async_request = Mock(post_res=AsyncMock(side_effect=responses))
|
||||
async_factory = Mock(return_value=async_request)
|
||||
monkeypatch.setattr(piggo, "AsyncRequestUtils", async_factory)
|
||||
return SimpleNamespace(request=request, factory=factory, async_request=async_request,
|
||||
async_factory=async_factory, responses=responses, wait=wait, async_wait=async_wait)
|
||||
|
||||
|
||||
def test_piggo_is_registered_for_search_and_user_data() -> None:
|
||||
"""
|
||||
猪猪改版后的站点资源必须能选择专用搜索与用户资料协议。
|
||||
"""
|
||||
assert "Piggo" in SPIDER_PARSER_CLASSES
|
||||
assert _SPECIALIZED_SEARCH_ARGUMENTS["Piggo"] == ("keyword", "mtype", "cat", "page")
|
||||
assert SiteSchema.Piggo.value == "Piggo"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_uses_post_json_and_official_fields(boundary, asynchronous):
|
||||
"""
|
||||
同步和异步均使用当前目录、正式分类与 IMDb 参数,不访问 PHP 或前台接口。
|
||||
"""
|
||||
spider = piggo.PiggoSpider(INDEXER)
|
||||
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
|
||||
assert len(result[1]) == 1
|
||||
torrent = TorrentInfo(**result[1][0])
|
||||
assert (torrent.title, torrent.description, torrent.size) == (ITEM["name"], "全16集", ITEM["size"])
|
||||
assert (torrent.seeders, torrent.peers, torrent.grabs) == (3, 0, 9)
|
||||
assert (torrent.media_source, torrent.media_id, torrent.category) == (MediaSource.IMDb, "tt33265527", MediaType.TV.value)
|
||||
assert torrent.uploadvolumefactor is None and torrent.downloadvolumefactor is None
|
||||
assert "poster" not in result[1][0]
|
||||
recipe, url = _recipe(torrent.enclosure)
|
||||
assert url == "https://api.piggo.me/v1/api/torrents/56354/download-link"
|
||||
assert recipe["json"] == {} and recipe["cookie"] is False
|
||||
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},
|
||||
{"url": "https://api.piggo.me/v1/api/torrents",
|
||||
"json": {"page": 3, "per_page": 100, "imdb_id": "tt33265527", "section_id": 22}, "allow_redirects": False},
|
||||
]
|
||||
assert all(call.kwargs["headers"]["Authorization"] == "Bearer synthetic-piggo-key" for call in factory.call_args_list)
|
||||
assert all("cookies" not in call.kwargs and call.kwargs["timeout"] == 25 for call in factory.call_args_list)
|
||||
for response in boundary.responses:
|
||||
(response.aclose if asynchronous else response.close).assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keyword", [None, "", " "])
|
||||
def test_latest_torrents_omit_search_terms(boundary, keyword):
|
||||
"""
|
||||
空关键词按同一列表接口从新到旧浏览,不构造不存在的最新或 RSS PHP 地址。
|
||||
"""
|
||||
assert piggo.PiggoSpider(INDEXER).search(keyword)[0] is False
|
||||
assert boundary.request.post_res.call_args.kwargs["json"] == {"page": 1, "per_page": 100}
|
||||
assert piggo.PiggoSpider.get_search_page_size(keyword) == 100
|
||||
|
||||
|
||||
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())]
|
||||
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],
|
||||
}
|
||||
assert boundary.request.post_res.call_count == 2
|
||||
|
||||
|
||||
def test_incomplete_section_categories_do_not_narrow_query(boundary):
|
||||
"""
|
||||
多分区中一处分区未列分类时不缩窄查询,避免丢掉可见种子。
|
||||
"""
|
||||
catalog = deepcopy(CATALOG)
|
||||
catalog["sections"].append({"id": 44, "name": "儿童电影"})
|
||||
boundary.request.post_res.side_effect = [_response(catalog), _response(_list())]
|
||||
assert piggo.PiggoSpider(INDEXER).search(None, MediaType.MOVIE)[0] is False
|
||||
assert boundary.request.post_res.call_args.kwargs["json"] == {"page": 1, "per_page": 100}
|
||||
|
||||
|
||||
def test_explicit_category_precedes_media_type(boundary):
|
||||
"""
|
||||
显式分类按正式 category_id 字段传递,去重且不混入 section_id。
|
||||
"""
|
||||
assert piggo.PiggoSpider(INDEXER).search("name", MediaType.MOVIE, cat="202, 303,202")[0] is False
|
||||
assert boundary.request.post_res.call_args.kwargs["json"] == {
|
||||
"page": 1, "per_page": 100, "q": "name", "category_id": [202, 303],
|
||||
}
|
||||
|
||||
|
||||
def test_catalog_cache_isolates_api_and_credentials(boundary):
|
||||
"""
|
||||
同 API 同令牌复用目录,令牌或 API 地址变化后必须重新读取可见范围。
|
||||
"""
|
||||
boundary.request.post_res.side_effect = [_response(CATALOG)] * 8
|
||||
first = piggo.PiggoSpider(INDEXER)
|
||||
assert first._load_catalog() == piggo.PiggoSpider(dict(INDEXER, cookie="changed-cookie"))._load_catalog()
|
||||
assert boundary.request.post_res.call_count == 1
|
||||
piggo.PiggoSpider(dict(INDEXER, apikey="another-synthetic-key"))._load_catalog()
|
||||
piggo.PiggoSpider(dict(INDEXER, api_url="https://api.custom.test/v1/api/"))._load_catalog()
|
||||
assert boundary.request.post_res.call_count == 3
|
||||
assert INDEXER["apikey"] not in first._cache_key
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_token_never_uses_cookie_or_network(boundary, asynchronous):
|
||||
"""
|
||||
只有 Cookie 时明确要求长期存取令牌,不自动登录、不生成令牌。
|
||||
"""
|
||||
spider = piggo.PiggoSpider(dict(INDEXER, apikey=" ", token=None))
|
||||
result = await spider.async_search(None) if asynchronous else spider.search(None)
|
||||
assert result == (True, [])
|
||||
assert spider.error_detail == site_rules.PIGGO_TOKEN_REQUIRED
|
||||
boundary.request.post_res.assert_not_called()
|
||||
boundary.async_request.post_res.assert_not_called()
|
||||
assert spider.get_download_url(56354) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_indexer_module_dispatches_piggo_and_preserves_identity(boundary, monkeypatch, asynchronous):
|
||||
"""
|
||||
真实索引模块可路由猪猪协议,并保留作品身份、标准种子字段和站点配置。
|
||||
"""
|
||||
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))
|
||||
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
|
||||
(health.async_success if asynchronous else health.success).assert_called_once()
|
||||
|
||||
|
||||
@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, "连接成功"),
|
||||
({"user": {"id": 42, "enabled": False}}, 200, 0, "禁用"),
|
||||
({"user": {"id": 42, "download_allowed": False}}, 200, 0, "下载权限"),
|
||||
({"user": {"id": 0}}, 200, 0, "无效"),
|
||||
({"user": []}, 200, 0, "有效用户资料"),
|
||||
({}, 401, 401, "令牌"),
|
||||
({"code": "notice_unread", "notice_gate": {"title": "必读公告"}}, 403, 0, "网页端阅读"),
|
||||
({"message": "请稍后重试"}, 429, 429, "限流"),
|
||||
({}, 200, 422, "失败"),
|
||||
])
|
||||
def test_connectivity_routes_by_domain_or_resource_protocol(monkeypatch, domain, resource_key, data, status, code, expected):
|
||||
"""
|
||||
域名路由与资源协议路由都只验证实验室,Token 兼容、下载权限及公告语义一致。
|
||||
"""
|
||||
chain = SiteChain()
|
||||
site = SiteSnapshot(id=7274, name="猪猪", domain=domain, url=f"https://{domain}/", apikey=" ",
|
||||
token=" synthetic-token ", cookie="unused-cookie", render=1, ua="Piggo-Test", timeout=25, proxy=1)
|
||||
chain.site_repository = Mock(get_by_domain=Mock(return_value=site))
|
||||
monkeypatch.setattr(site_chain, "SitesHelper", Mock(return_value=Mock(get_indexer=Mock(return_value={
|
||||
resource_key: "Piggo", "api_url": "https://api.custom.test/v1/api/",
|
||||
}))))
|
||||
monkeypatch.setattr(site_chain, "site_request_config", lambda _url, _id: {"id": 7274, "domain": domain})
|
||||
wait = Mock()
|
||||
defer = Mock()
|
||||
monkeypatch.setattr(site_chain, "wait_for_site_request", wait)
|
||||
monkeypatch.setattr(site_chain, "defer_site_request", defer)
|
||||
response = _response(data, status, code)
|
||||
context = MagicMock()
|
||||
context.__enter__.return_value = response
|
||||
open_response = Mock(return_value=context)
|
||||
monkeypatch.setattr(site_chain, "_open_site_response", open_response)
|
||||
generic = Mock(side_effect=AssertionError("猪猪不应请求首页或浏览器"))
|
||||
monkeypatch.setattr(SiteChain, "_SiteChain__test", generic)
|
||||
state, message = chain.test(site.url)
|
||||
assert state is (expected == "连接成功")
|
||||
assert expected in message
|
||||
request = open_response.call_args.kwargs
|
||||
assert request["method"] == "POST" and request["json_body"] == {}
|
||||
assert request["url"] == "https://api.custom.test/v1/api/me"
|
||||
assert request["headers"]["Authorization"] == "Bearer synthetic-token"
|
||||
assert "cookie" not in request and request["timeout"] == 25
|
||||
assert request["proxies"] == (chain.runtime_config.proxy or {})
|
||||
generic.assert_not_called()
|
||||
wait.assert_called_once()
|
||||
context.__exit__.assert_called_once_with(None, None, None)
|
||||
assert defer.called is (status == 429)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("stage", ["catalog", "torrents"])
|
||||
@pytest.mark.parametrize("status,code,data", [
|
||||
(401, 401, {}), (429, 429, {"message": "一分钟请求过多"}),
|
||||
(403, 0, {"code": "notice_unread", "notice_gate": {"title": "公告"}}),
|
||||
(200, 422, {"message": "无效参数"}),
|
||||
])
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_errors_stop_search_and_invalidate_catalog(boundary, monkeypatch, asynchronous, stage, status, code, data):
|
||||
"""
|
||||
目录或列表的 HTTP、业务、公告与限流失败都不发布结果,失效目录不再复用。
|
||||
"""
|
||||
error = _response(data, status, code)
|
||||
responses = [error] if stage == "catalog" else [_response(CATALOG), error]
|
||||
request = boundary.async_request if asynchronous else boundary.request
|
||||
request.post_res.side_effect = responses
|
||||
defer = Mock()
|
||||
monkeypatch.setattr(piggo, "defer_site_request", defer)
|
||||
spider = piggo.PiggoSpider(INDEXER)
|
||||
if status == 429:
|
||||
with pytest.raises(RateLimitExceededException, match="限流"):
|
||||
if asynchronous:
|
||||
await spider.async_search("title")
|
||||
else:
|
||||
spider.search("title")
|
||||
else:
|
||||
result = await spider.async_search("title") if asynchronous else spider.search("title")
|
||||
assert result == (True, []) and spider.error_detail
|
||||
assert request.post_res.call_count == len(responses)
|
||||
assert spider._catalog_cache.get(spider._cache_key, region=spider._catalog_region) is None
|
||||
assert defer.called is (status == 429)
|
||||
for response in responses:
|
||||
(response.aclose if asynchronous else response.close).assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("media,section,categories,source,identity,mtype", [
|
||||
({"douban": "36457187"}, 22, [202], MediaSource.Douban, "36457187", MediaType.TV),
|
||||
({"tmdb": "42", "tmdb_kind": "movie"}, 22, [202], MediaSource.TMDB, "42", MediaType.MOVIE),
|
||||
({}, 999, [999], None, None, MediaType.UNKNOWN),
|
||||
({}, 33, [303], None, None, MediaType.MUSIC),
|
||||
({}, 11, [101, 202], None, None, MediaType.MOVIE),
|
||||
])
|
||||
def test_media_identity_and_unknown_category_mapping(boundary, media, section, categories, source, identity, mtype):
|
||||
"""
|
||||
正式作品字段决定身份,未知或冲突目录不伪造电影、电视剧和促销信息。
|
||||
"""
|
||||
item = deepcopy(ITEM)
|
||||
item.update(media=media, section_id=section, category_ids=categories, page_url=None)
|
||||
boundary.request.post_res.side_effect = [_response(CATALOG), _response(_list([item]))]
|
||||
error, result = piggo.PiggoSpider(INDEXER).search(None)
|
||||
assert not error
|
||||
assert (result[0]["media_source"], result[0]["media_id"], result[0]["category"]) == (source, identity, mtype.value)
|
||||
assert result[0]["page_url"] == ITEM["page_url"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [{"id": 0}, {"id": 1.5}, {"id": True}, {"name": ""}, {"size": -1},
|
||||
{"seeders": "invalid"}, {"media": []}, {"category_ids": "202"},
|
||||
{"small_descr": {}}, {"page_url": []}, {"added_at": {}},
|
||||
{"media": {"imdb": {}}}, {"media": {"imdb": "not-an-imdb-id"}},
|
||||
{"media": {"douban": True}}, {"media": {"tmdb": "not-an-id"}}])
|
||||
def test_bad_torrent_record_does_not_publish_partial_page(boundary, change):
|
||||
"""
|
||||
第二条种子无效时整页失败,不悄悄跳过坏记录或把浮点 ID 截断。
|
||||
"""
|
||||
item = dict(ITEM, id=56355)
|
||||
item.update(change)
|
||||
boundary.request.post_res.side_effect = [_response(CATALOG), _response(_list([ITEM, item]))]
|
||||
assert piggo.PiggoSpider(INDEXER).search(None) == (True, [])
|
||||
|
||||
|
||||
def test_catalog_cache_expires_and_remains_bounded(boundary, monkeypatch):
|
||||
"""
|
||||
目录一小时后重新读取,轮换大量令牌也不突破 128 份内存容量。
|
||||
"""
|
||||
boundary.request.post_res.side_effect = [_response(CATALOG)] * 132
|
||||
first = piggo.PiggoSpider(INDEXER)
|
||||
first._load_catalog()
|
||||
region_cache = first._catalog_cache._region_caches["region:piggo-catalog"]
|
||||
clock = SimpleNamespace(now=region_cache.timer())
|
||||
monkeypatch.setattr(region_cache.timer, "_Timer__timer", lambda: clock.now)
|
||||
clock.now += 3599
|
||||
first._load_catalog()
|
||||
assert boundary.request.post_res.call_count == 1
|
||||
clock.now += 2
|
||||
first._load_catalog()
|
||||
assert boundary.request.post_res.call_count == 2
|
||||
for number in range(129):
|
||||
piggo.PiggoSpider(dict(INDEXER, apikey=f"synthetic-key-{number}"))._load_catalog()
|
||||
assert len(region_cache) == region_cache.maxsize == 128
|
||||
assert region_cache.ttl == 3600
|
||||
assert first._catalog_cache.get(first._cache_key, region=first._catalog_region) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("apikey,token,expected", [(" key ", "other", "key"), (" ", " token ", "token"),
|
||||
(None, " token ", "token"), (None, None, "")])
|
||||
def test_token_selection(apikey, token, expected):
|
||||
"""
|
||||
非空 API Key 优先,只有空白时兼容 Token。
|
||||
"""
|
||||
assert site_rules.piggo_access_token(apikey, token) == expected
|
||||
|
||||
|
||||
def test_checkpoint_restores_recipe_using_current_token(boundary):
|
||||
"""
|
||||
检查点不保存换票凭据,恢复时按稳定种子 ID 使用当前令牌重建。
|
||||
"""
|
||||
record = {"site": 7274, "site_name": "猪猪", "title": ITEM["name"], "page_url": ITEM["page_url"]}
|
||||
restored = IndexerModule.restore_search_torrent(dict(INDEXER, apikey="rotated-synthetic-key"), record)
|
||||
assert restored is not None
|
||||
recipe, url = _recipe(restored.enclosure)
|
||||
assert recipe["header"]["Authorization"] == "Bearer rotated-synthetic-key"
|
||||
assert url.endswith("/56354/download-link")
|
||||
assert IndexerModule.restore_search_torrent(dict(INDEXER, apikey=None), record) is None
|
||||
boundary.request.post_res.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status,payload,expected", [
|
||||
(200, None, "结构无效"), (200, {"code": 0, "data": []}, "有效 data"),
|
||||
(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 参数无效"}}, "失败"),
|
||||
])
|
||||
def test_envelope_errors_are_safe_and_keep_protocol_semantics(status, payload, expected):
|
||||
"""
|
||||
HTTP、内层业务码和坏结构都能明确失败,错误文本不回显令牌。
|
||||
"""
|
||||
with pytest.raises(ValueError) as error:
|
||||
site_rules.piggo_response_data(status, payload, "synthetic-key")
|
||||
assert expected in str(error.value)
|
||||
assert "synthetic-key" not in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", ["no-token", "no-response", "bad-json", "cooldown"])
|
||||
def test_connectivity_failures_do_not_open_web_pages(monkeypatch, case):
|
||||
"""
|
||||
缺少令牌、无响应、坏 JSON 和既有冷却都明确失败,不用 Cookie 探测页面。
|
||||
"""
|
||||
chain = SiteChain()
|
||||
site = SiteSnapshot(id=7274, name="猪猪", domain="piggo.me", url="https://piggo.me/", cookie="unused-cookie",
|
||||
apikey=None if case == "no-token" else "synthetic-key")
|
||||
monkeypatch.setattr(site_chain, "SitesHelper", Mock(return_value=Mock(get_indexer=Mock(return_value={}))))
|
||||
monkeypatch.setattr(site_chain, "site_request_config", lambda _url, _id: {"id": 7274, "domain": "piggo.me"})
|
||||
wait = Mock(side_effect=RateLimitExceededException("站点限流") if case == "cooldown" else None)
|
||||
monkeypatch.setattr(site_chain, "wait_for_site_request", wait)
|
||||
response = _response({})
|
||||
response._content = b"<html>WAF</html>"
|
||||
context = MagicMock()
|
||||
context.__enter__.return_value = None if case == "no-response" else response
|
||||
open_response = Mock(return_value=context)
|
||||
monkeypatch.setattr(site_chain, "_open_site_response", open_response)
|
||||
state, message = chain._SiteChain__piggo_test(site)
|
||||
assert not state
|
||||
assert {"no-token": "长期存取令牌", "no-response": "无法连接", "bad-json": "结构无效", "cooldown": "限流"}[case] in message
|
||||
assert open_response.call_count == (0 if case in ("no-token", "cooldown") else 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_piggo_rate_limit_is_classified_by_the_indexer(boundary, monkeypatch, asynchronous):
|
||||
"""
|
||||
猪猪限流必须进入订阅限流分类,并记录失败而不是把捕获的异常算作搜索成功。
|
||||
"""
|
||||
response = _response({"message": "请在一分钟后重试"}, 429, 429)
|
||||
request = boundary.async_request if asynchronous else boundary.request
|
||||
request.post_res.side_effect = [_response(CATALOG), response]
|
||||
monkeypatch.setattr(piggo, "defer_site_request", Mock())
|
||||
health = Mock(async_success=AsyncMock(), async_fail=AsyncMock())
|
||||
monkeypatch.setattr(indexer_module, "get_configured_site_health_service", lambda: health)
|
||||
monkeypatch.setattr(indexer_module, "SitesHelper", Mock(return_value=Mock(check=Mock(return_value=(False, "")))))
|
||||
module = object.__new__(IndexerModule)
|
||||
with capture_site_search_observation() as observation:
|
||||
result = (await module.async_search_torrents(INDEXER, keyword="title") if asynchronous else
|
||||
module.search_torrents(INDEXER, keyword="title"))
|
||||
assert result == []
|
||||
assert observation.outcome == "rate_limited" and "限流" in observation.error
|
||||
(health.async_fail if asynchronous else health.fail).assert_called_once()
|
||||
(health.async_success if asynchronous else health.success).assert_not_called()
|
||||
|
||||
|
||||
def test_category_id_can_belong_to_multiple_sections(boundary):
|
||||
"""
|
||||
分类 ID 在电影和剧集分区复用时仍可加载,按种子的实际分区判断类型。
|
||||
"""
|
||||
catalog = deepcopy(CATALOG)
|
||||
catalog["categories"].append({"id": 101, "section_id": 22, "name": "海外"})
|
||||
item = dict(ITEM, section_id=22, category_ids=[101], media={})
|
||||
boundary.request.post_res.side_effect = [_response(catalog), _response(_list([item]))]
|
||||
failed, results = piggo.PiggoSpider(INDEXER).search(None, MediaType.TV)
|
||||
assert not failed and results[0]["category"] == MediaType.TV.value
|
||||
assert boundary.request.post_res.call_args.kwargs["json"]["section_id"] == 22
|
||||
|
||||
|
||||
def test_multi_section_category_union_deduplicates_shared_ids(boundary):
|
||||
"""
|
||||
多分区的分类并集只传递唯一 ID,分类成员关系不会因复用 ID 而丢失。
|
||||
"""
|
||||
catalog = deepcopy(CATALOG)
|
||||
catalog["sections"].append({"id": 44, "name": "儿童电影"})
|
||||
catalog["categories"].append({"id": 101, "section_id": 44, "name": "海外"})
|
||||
boundary.request.post_res.side_effect = [_response(catalog), _response(_list())]
|
||||
assert piggo.PiggoSpider(INDEXER).search(None, MediaType.MOVIE)[0] is False
|
||||
assert boundary.request.post_res.call_args.kwargs["json"] == {"page": 1, "per_page": 100, "category_id": [101]}
|
||||
|
||||
|
||||
def test_ambiguous_visible_section_is_not_excluded_by_media_filter(boundary):
|
||||
"""
|
||||
可见目录有未能判型的纪录片分区时,不用单一电影分区过滤掉其中的电影。
|
||||
"""
|
||||
catalog = deepcopy(CATALOG)
|
||||
catalog["sections"].append({"id": 66, "name": "纪录片"})
|
||||
catalog["categories"].append({"id": 101, "section_id": 66, "name": "冒险"})
|
||||
item = dict(ITEM, section_id=66, category_ids=[101], media={"tmdb": "42", "tmdb_kind": "movie"})
|
||||
boundary.request.post_res.side_effect = [_response(catalog), _response(_list([item]))]
|
||||
failed, result = piggo.PiggoSpider(INDEXER).search("name", MediaType.MOVIE)
|
||||
assert not failed and result[0]["category"] == MediaType.MOVIE.value
|
||||
assert boundary.request.post_res.call_args.kwargs["json"] == {"page": 1, "per_page": 100, "q": "name"}
|
||||
221
tests/test_piggo_parser.py
Normal file
221
tests/test_piggo_parser.py
Normal file
@@ -0,0 +1,221 @@
|
||||
"""
|
||||
猪猪实验室资料完整性、分页失败与禁止页面回退的离线回归。
|
||||
"""
|
||||
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from requests import Response
|
||||
|
||||
import app.modules.indexer.parser.piggo as piggo
|
||||
from app.chain.site import SiteChain
|
||||
from app.modules.indexer import IndexerModule
|
||||
from app.modules.indexer.parser.nexus_php import NexusPhpSiteUserInfo
|
||||
|
||||
# 仅使用合成账号与合成令牌,容量样例来自公开接口文档。
|
||||
PROFILE = {"user": {"id": 42, "username": "synthetic-user", "enabled": True,
|
||||
"class": {"id": 8, "name": "主管"}, "stats": {"uploaded": "2.50 GB", "downloaded": "1.00 GB", "bonus": 12.5}}}
|
||||
|
||||
|
||||
def _response(data, status=200, code=0):
|
||||
response = Response()
|
||||
response.status_code = status
|
||||
response._content = json.dumps({"code": code, "data": data, "msg": "ok"}).encode()
|
||||
response.encoding = "utf-8"
|
||||
response.close = Mock()
|
||||
return response
|
||||
|
||||
|
||||
def _page(kind, items=None, page=1, total=None, per_page=100):
|
||||
items = [] if items is None else items
|
||||
total = len(items) if total is None else total
|
||||
return {"kind": kind, "items": items, "page": page, "per_page": per_page,
|
||||
"pages": max(1, (total + per_page - 1) // per_page), "total": total}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def boundary(monkeypatch):
|
||||
"""
|
||||
替换资料传输和等待边界,所有错误仍经过真实信封和分页校验。
|
||||
"""
|
||||
monkeypatch.setattr(piggo, "site_request_config", lambda _url: {"id": 7274, "domain": "piggo.me"})
|
||||
monkeypatch.setattr(piggo, "wait_for_site_request", Mock())
|
||||
monkeypatch.setattr(piggo, "get_runtime_setting", lambda _key: {"https": "proxy"})
|
||||
request = Mock()
|
||||
request.post_res.side_effect = [_response(PROFILE), _response(_page("seeding")), _response(_page("leeching"))]
|
||||
parser = piggo.PiggoSiteUserInfo(
|
||||
site_name="猪猪", url="https://piggo.me/", site_cookie="unused-cookie", apikey=" synthetic-key ",
|
||||
token="unused-token", request_utils=request, ua="Piggo-Test", proxy=True, emulate=True,
|
||||
)
|
||||
return parser, request
|
||||
|
||||
|
||||
def test_complete_profile_and_all_torrent_pages_are_published(boundary):
|
||||
"""
|
||||
做种和下载的末页全部成功后才公布统计,文本容量转换为字节,分享率按流量计算。
|
||||
"""
|
||||
parser, request = boundary
|
||||
seeding = [{"id": 1, "size": 1024, "seeders": 4}, {"id": 2, "size": 2048, "seeders": 7}]
|
||||
leeching = [{"id": 3, "size": 8192, "seeders": 2}, {"id": 4, "size": 4096, "seeders": 1}]
|
||||
responses = [_response(PROFILE),
|
||||
_response(_page("seeding", seeding[:1], total=2, per_page=1)),
|
||||
_response(_page("seeding", seeding[1:], page=2, total=2, per_page=1)),
|
||||
_response(_page("leeching", leeching[:1], total=2, per_page=1)),
|
||||
_response(_page("leeching", leeching[1:], page=2, total=2, per_page=1))]
|
||||
request.post_res.side_effect = responses
|
||||
parser.parse()
|
||||
assert parser.err_msg is None
|
||||
assert (parser.userid, parser.username, parser.user_level) == (42, "synthetic-user", "主管")
|
||||
assert (parser.upload, parser.download, parser.ratio, parser.bonus) == (2684354560, 1073741824, 2.5, 12.5)
|
||||
assert (parser.seeding, parser.seeding_size, parser.seeding_info) == (2, 3072, [[4, 1024], [7, 2048]])
|
||||
assert (parser.leeching, parser.leeching_size) == (2, 12288)
|
||||
assert parser.join_at is None and parser.message_unread == 0
|
||||
bodies = [call.kwargs["json"] for call in request.post_res.call_args_list]
|
||||
assert bodies == [{}, {"kind": "seeding", "page": 1, "per_page": 100}, {"kind": "seeding", "page": 2, "per_page": 100},
|
||||
{"kind": "leeching", "page": 1, "per_page": 100}, {"kind": "leeching", "page": 2, "per_page": 100}]
|
||||
for call in request.post_res.call_args_list:
|
||||
assert call.kwargs["url"].startswith("https://api.piggo.me/v1/api/me")
|
||||
assert call.kwargs["headers"]["Authorization"] == "Bearer synthetic-key"
|
||||
assert call.kwargs["cookies"] is None and call.kwargs["allow_redirects"] is False
|
||||
request.close.assert_called_once()
|
||||
for response in responses:
|
||||
response.close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("part", ["uploaded", "downloaded"])
|
||||
def test_missing_traffic_fails_without_partial_identity(boundary, part):
|
||||
"""
|
||||
缺少流量字段不能保存为零或让 KeyError 逃出资料入口。
|
||||
"""
|
||||
parser, request = boundary
|
||||
profile = deepcopy(PROFILE)
|
||||
del profile["user"]["stats"][part]
|
||||
request.post_res.side_effect = [_response(profile)]
|
||||
parser.parse()
|
||||
assert parser.userid is None and parser.err_msg
|
||||
assert parser.upload == parser.download == parser.seeding == 0
|
||||
request.post_res.assert_called_once()
|
||||
request.close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [{"page": 1}, {"total": 3}, {"kind": "leeching"}, {"items": []},
|
||||
{"items": [{"id": 1, "size": 1024, "seeders": 2}]}])
|
||||
def test_changed_or_incomplete_second_page_discards_entire_refresh(boundary, change):
|
||||
"""
|
||||
错页、变化的总数、错类、缺条目或重复 ID 都不能留下半份统计。
|
||||
"""
|
||||
parser, request = boundary
|
||||
first = _page("seeding", [{"id": 1, "size": 1024, "seeders": 2}], total=2, per_page=1)
|
||||
second = _page("seeding", [{"id": 2, "size": 2048, "seeders": 3}], page=2, total=2, per_page=1)
|
||||
second.update(change)
|
||||
request.post_res.side_effect = [_response(PROFILE), _response(first), _response(second)]
|
||||
parser.parse()
|
||||
assert parser.userid is None and "分页" in parser.err_msg
|
||||
assert parser.upload == parser.download == parser.seeding == parser.seeding_size == parser.leeching == 0
|
||||
assert parser.seeding_info == []
|
||||
request.close.assert_called_once()
|
||||
|
||||
|
||||
def test_last_leeching_page_failure_does_not_save_valid_seeding(boundary):
|
||||
"""
|
||||
下载列表失败也必须拒绝整个统计快照,不能仅保存已成功的做种数据。
|
||||
"""
|
||||
parser, request = boundary
|
||||
request.post_res.side_effect = [_response(PROFILE), _response(_page("seeding", [{"id": 1, "size": 1024, "seeders": 2}])),
|
||||
_response({}, status=401, code=401)]
|
||||
parser.parse()
|
||||
assert parser.userid is None and "令牌" in parser.err_msg
|
||||
assert parser.seeding == parser.upload == 0
|
||||
|
||||
|
||||
def test_failed_api_parser_never_falls_back_or_persists(boundary, monkeypatch):
|
||||
"""
|
||||
资料 API 失败后禁止探测 PHP 页面,SiteChain 不写入空白或半份用户数据。
|
||||
"""
|
||||
parser, request = boundary
|
||||
parser.apikey = None
|
||||
parser.token = None
|
||||
constructor = Mock(return_value=parser)
|
||||
constructor.schema = piggo.SiteSchema.Piggo
|
||||
module = object.__new__(IndexerModule)
|
||||
module._site_schemas = [constructor, NexusPhpSiteUserInfo]
|
||||
fallback = Mock(side_effect=AssertionError("猪猪 API 失败不能回退页面"))
|
||||
monkeypatch.setattr(NexusPhpSiteUserInfo, "parse", fallback)
|
||||
site = {"name": "猪猪", "url": "https://piggo.me/", "schema": "Piggo", "public": False}
|
||||
userdata = module.refresh_userdata(site)
|
||||
assert userdata.userid is None and "长期存取令牌" in userdata.err_msg
|
||||
fallback.assert_not_called()
|
||||
request.post_res.assert_not_called()
|
||||
chain = object.__new__(SiteChain)
|
||||
chain.run_module = Mock(return_value=userdata)
|
||||
chain.site_repository = Mock()
|
||||
assert chain.refresh_userdata(site) is userdata
|
||||
chain.site_repository.update_userdata.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field,value", [("id", True), ("id", -1), ("username", 42), ("username", " "),
|
||||
("enabled", False), ("stats", []), ("class", {}), ("class", []),
|
||||
("stats", {"uploaded": "invalid", "downloaded": 0}),
|
||||
("stats", {"uploaded": 0, "downloaded": 0, "bonus": "nan"}),
|
||||
("stats", {"uploaded": 0, "downloaded": 0, "bonus": []}),
|
||||
("stats", {"uploaded": 0, "downloaded": 0, "bonus": {"invalid": 1}})])
|
||||
def test_invalid_profile_is_not_saved_as_valid_user(boundary, field, value):
|
||||
"""
|
||||
外部资料的身份、等级、容量和有限魔力值必须有效,不传播原始账户字段。
|
||||
"""
|
||||
parser, request = boundary
|
||||
profile = deepcopy(PROFILE)
|
||||
profile["user"][field] = value
|
||||
request.post_res.side_effect = [_response(profile)]
|
||||
parser.parse()
|
||||
assert parser.userid is None and parser.err_msg
|
||||
assert parser.seeding_info == [] and parser.upload == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pages", [0, 1])
|
||||
def test_empty_torrents_and_zero_download_are_valid(boundary, pages):
|
||||
"""
|
||||
空做种、空下载列表不是失败;零下载量的分享率沿用零值合同。
|
||||
"""
|
||||
parser, request = boundary
|
||||
profile = deepcopy(PROFILE)
|
||||
profile["user"]["stats"]["downloaded"] = 0
|
||||
request.post_res.side_effect = [_response(profile), _response(dict(_page("seeding"), pages=pages)),
|
||||
_response(dict(_page("leeching"), pages=pages))]
|
||||
parser.parse()
|
||||
assert parser.userid == 42 and parser.err_msg is None
|
||||
assert parser.ratio == parser.seeding == parser.leeching == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status,code", [(429, 429), (403, 0), (200, 422)])
|
||||
def test_profile_api_errors_are_explicit_and_responses_close(boundary, monkeypatch, status, code):
|
||||
"""
|
||||
用户 API 的内层公告和限流失败均能展示原因,不进入种子分页或保存统计。
|
||||
"""
|
||||
parser, request = boundary
|
||||
response = _response({"code": "notice_unread", "notice_gate": {"title": "公告"}} if status == 403 else {}, status, code)
|
||||
request.post_res.side_effect = [response]
|
||||
defer = Mock()
|
||||
monkeypatch.setattr(piggo, "defer_site_request", defer)
|
||||
parser.parse()
|
||||
assert parser.userid is None and parser.err_msg
|
||||
assert defer.called is (status == 429)
|
||||
request.post_res.assert_called_once()
|
||||
response.close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [{"pages": 9}, {"per_page": 101}, {"per_page": 0}, {"total": -1}, {"page": 0},
|
||||
{"items": None}, {"items": [{}]}, {"items": [None]},
|
||||
{"items": [{"id": 1, "size": -1}]}, {"items": [{"id": 1, "size": 1, "seeders": "invalid"}]}])
|
||||
def test_malformed_torrent_page_discards_profile(boundary, change):
|
||||
"""
|
||||
无效元数据、错类型或坏整数不能被视为完整空列表。
|
||||
"""
|
||||
parser, request = boundary
|
||||
data = _page("seeding", [{"id": 1, "size": 1, "seeders": 1}])
|
||||
data.update(change)
|
||||
request.post_res.side_effect = [_response(PROFILE), _response(data)]
|
||||
parser.parse()
|
||||
assert parser.userid is None and "分页" in parser.err_msg
|
||||
Reference in New Issue
Block a user