mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 00:15:56 +08:00
fix(indexer): adapt starspace user data and RSS pages (#7495)
This commit is contained in:
@@ -124,12 +124,14 @@ class RssLinkRecipe:
|
||||
:param xpath: 获取生成链接的页面选择器
|
||||
:param params: 获取链接时提交的表单字段
|
||||
:param render: 是否使用已注入的浏览器端口
|
||||
:param method: 页面读取方法;默认 POST 保持通用生成表单的既有行为
|
||||
"""
|
||||
|
||||
url: str
|
||||
xpath: str
|
||||
params: dict[str, Any]
|
||||
render: bool = False
|
||||
method: Literal["get", "post"] = "post"
|
||||
|
||||
|
||||
class RssSitePort(Protocol):
|
||||
@@ -521,14 +523,23 @@ class RssHelper:
|
||||
timeout=timeout or 60
|
||||
)
|
||||
else:
|
||||
res = http_port.post(
|
||||
url=recipe.url,
|
||||
data=recipe.params,
|
||||
cookie=cookie,
|
||||
ua=ua,
|
||||
proxies=get_chain_runtime_config_snapshot().proxy if proxy else None,
|
||||
timeout=timeout or 30,
|
||||
)
|
||||
if recipe.method == "get":
|
||||
res = http_port.get(
|
||||
url=recipe.url,
|
||||
ua=ua,
|
||||
headers={"Cookie": cookie},
|
||||
proxies=get_chain_runtime_config_snapshot().proxy if proxy else None,
|
||||
timeout=timeout or 30,
|
||||
)
|
||||
else:
|
||||
res = http_port.post(
|
||||
url=recipe.url,
|
||||
data=recipe.params,
|
||||
cookie=cookie,
|
||||
ua=ua,
|
||||
proxies=get_chain_runtime_config_snapshot().proxy if proxy else None,
|
||||
timeout=timeout or 30,
|
||||
)
|
||||
if res is not None and res.status_code == 200:
|
||||
html_text = res.text
|
||||
elif res is not None:
|
||||
|
||||
@@ -37,6 +37,8 @@ class SiteSchema(Enum):
|
||||
NexusPhp = "NexusPhp"
|
||||
# 采用 NexusProject 页面结构的站点。
|
||||
NexusProject = "NexusProject"
|
||||
# 星空的 FireFly 定制页面。
|
||||
StarSpace = "StarSpace"
|
||||
# 采用 NexusRabbit JSON 接口的站点。
|
||||
NexusRabbit = "NexusRabbit"
|
||||
# 憨憨的 NexusPHP 定制页面。
|
||||
|
||||
218
app/modules/indexer/parser/starspace.py
Normal file
218
app/modules/indexer/parser/starspace.py
Normal file
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
解析星空 FireFly 页面的用户身份、流量、资料和做种列表。
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Optional
|
||||
from urllib.parse import parse_qs, parse_qsl, urlencode, urljoin, urlsplit, urlunsplit
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.foundation import temporal as time_tools
|
||||
from app.foundation import text as text_tools
|
||||
from app.modules.indexer.parser import SitePage, SiteSchema
|
||||
from app.modules.indexer.parser.nexus_php import NexusPhpSiteUserInfo
|
||||
from app.runtime.log import logger
|
||||
|
||||
# 页面等级图片的 class1 至 class11 对应的站点等级名称。
|
||||
_USER_LEVELS = (
|
||||
"User", "Power User", "Elite User", "Crazy User", "Insane User", "Veteran User",
|
||||
"Extreme User", "Ultimate User", "Master User", "Star User", "God User",
|
||||
)
|
||||
_SEEDING_PATH = "/p_torrent/torrent_user.php"
|
||||
|
||||
|
||||
class StarSpaceSiteUserInfo(NexusPhpSiteUserInfo):
|
||||
"""
|
||||
复用用户数据请求生命周期,独立解释星空的带前缀页面协议。
|
||||
|
||||
:ivar _visited_seeding_pages: 本轮已请求或已安排的做种页面,防止循环分页
|
||||
"""
|
||||
|
||||
schema = SiteSchema.StarSpace
|
||||
allow_schema_fallback = False
|
||||
|
||||
def _parse_site_page(self, html_text: SitePage) -> None:
|
||||
"""
|
||||
从本站个人资料链接读取用户身份,并设置详情和做种入口。
|
||||
|
||||
Cookie 中的 ffid 只作为认证凭据,不能代替页面确认登录后的用户身份。
|
||||
"""
|
||||
self.userid = None
|
||||
self._user_detail_page = None
|
||||
self._torrent_seeding_page = None
|
||||
self._user_traffic_page = None
|
||||
# 星空的消息协议独立,不能请求 NexusPHP 的默认消息页。
|
||||
self._user_mail_unread_page = None
|
||||
self._sys_mail_unread_page = None
|
||||
self._visited_seeding_pages: set[str] = set()
|
||||
|
||||
html = etree.HTML(self._prepare_html_text(html_text))
|
||||
if html is None:
|
||||
return
|
||||
for link in html.xpath('//a[contains(@href, "user_detail.php")]'):
|
||||
target = urlsplit(urljoin(self._site_url, link.get("href", "")))
|
||||
userids = parse_qs(target.query).get("uid", [])
|
||||
if (target.scheme != urlsplit(self._base_url).scheme
|
||||
or target.netloc != urlsplit(self._base_url).netloc
|
||||
or target.path != "/p_user/user_detail.php"
|
||||
or len(userids) != 1 or not userids[0].isdigit() or int(userids[0]) <= 0):
|
||||
continue
|
||||
self.userid = userids[0]
|
||||
self.username = link.xpath("string(.)").strip() or None
|
||||
self._user_detail_page = f"p_user/user_detail.php?uid={self.userid}"
|
||||
self._torrent_seeding_page = f"p_torrent/torrent_user.php?pop=8&uid={self.userid}"
|
||||
return
|
||||
|
||||
def _parse_user_base_info(self, html_text: SitePage) -> None:
|
||||
"""
|
||||
从已登录首页读取流量及当前账号的统计,避免重复请求首页。
|
||||
"""
|
||||
self._parse_user_traffic_info(self._prepare_html_text(html_text))
|
||||
|
||||
@staticmethod
|
||||
def _parse_size(value: str) -> Optional[int]:
|
||||
"""
|
||||
解释星空省略 B 后缀的容量,缺失或无效值保持未知。
|
||||
|
||||
:param value: 页面显示的容量,支持 G、GB 和 GiB 等单位
|
||||
:return: 容量的整数字节数;格式无效时为 None
|
||||
"""
|
||||
match = re.fullmatch(r"\s*([\d,]+(?:\.\d+)?)\s*([KMGTPI](?:i?B)?|B)?\s*", value, re.I)
|
||||
if not match:
|
||||
return None
|
||||
unit = (match.group(2) or "B").upper()
|
||||
return StarSpaceSiteUserInfo.num_filesize(f"{match.group(1)} {unit if unit.endswith('B') else unit + 'B'}")
|
||||
|
||||
def _parse_user_traffic_info(self, html_text: str) -> None:
|
||||
"""
|
||||
从账号概览读取上传、下载、魔力和明确给出的做种、下载数量。
|
||||
"""
|
||||
html = etree.HTML(html_text)
|
||||
if html is None:
|
||||
return
|
||||
overview = " ".join(html.xpath(
|
||||
'//span[@id="user_info" or @id="user_info_no_hover"]//text()'
|
||||
))
|
||||
for label, attribute in (("上传", "upload"), ("下载", "download")):
|
||||
match = re.search(rf"{label}\s*[::]\s*([\d,.]+\s*(?:[KMGTPI](?:i?B)?|B)?)", overview, re.I)
|
||||
value = self._parse_size(match.group(1)) if match else None
|
||||
if value is not None:
|
||||
setattr(self, attribute, value)
|
||||
self.ratio = round(self.upload / self.download, 3) if self.download else 0.0
|
||||
|
||||
for link in html.xpath('//a[contains(@href, "torrent_user.php")]'):
|
||||
query = parse_qs(urlsplit(link.get("href", "")).query)
|
||||
if query.get("uid", [str(self.userid)]) != [str(self.userid)]:
|
||||
continue
|
||||
count = re.search(r"[\d,]+", link.xpath("string(.)"))
|
||||
if count and query.get("pop") == ["8"]:
|
||||
self._summary_seeding = self.seeding = int(count.group().replace(",", ""))
|
||||
elif count and query.get("pop") == ["9"]:
|
||||
self.leeching = int(count.group().replace(",", ""))
|
||||
bonus = html.xpath('//a[contains(@href, "p_bonus/bonus_hour.php")]')
|
||||
if bonus:
|
||||
match = re.search(r"[\d,]+(?:\.\d+)?", bonus[0].xpath("string(.)"))
|
||||
if match:
|
||||
self.bonus = text_tools.parse_float(match.group().replace(",", ""))
|
||||
|
||||
@staticmethod
|
||||
def _profile_field(html: etree._Element, label: str) -> Optional[etree._Element]:
|
||||
"""
|
||||
按资料表字段名读取相邻值单元格,避免扫描整页误取其他用户数据。
|
||||
|
||||
:param html: 当前账号的资料页节点
|
||||
:param label: 资料表中的完整字段名
|
||||
:return: 字段对应的值单元格;页面没有该字段时为 None
|
||||
"""
|
||||
cells = html.xpath('//tr/td[normalize-space(.)=$label]/following-sibling::td[1]', label=label)
|
||||
return cells[0] if cells else None
|
||||
|
||||
def _parse_user_detail_info(self, html_text: str) -> None:
|
||||
"""
|
||||
读取资料表的等级、注册时间、传输统计及魔力,保留首页已取得的字段。
|
||||
"""
|
||||
html = etree.HTML(html_text)
|
||||
if html is None:
|
||||
return
|
||||
self._parse_user_traffic_info(html_text)
|
||||
for label, attribute in (("用户名称", "username"), ("加入日期", "join_at"), ("魔力", "bonus")):
|
||||
cell = self._profile_field(html, label)
|
||||
value = cell.xpath("string(.)").strip() if cell is not None else ""
|
||||
if not value:
|
||||
continue
|
||||
if attribute == "join_at":
|
||||
self.join_at = time_tools.normalize_datetime(value.split(" (")[0])
|
||||
elif attribute == "bonus":
|
||||
self.bonus = text_tools.parse_float(value.replace(",", ""))
|
||||
else:
|
||||
self.username = value
|
||||
level = self._profile_field(html, "用户等级")
|
||||
if level is not None:
|
||||
markers = level.xpath('.//img/@alt | .//img/@src')
|
||||
match = re.search(r"class(\d+)", " ".join(markers))
|
||||
if match and 1 <= int(match.group(1)) <= len(_USER_LEVELS):
|
||||
self.user_level = _USER_LEVELS[int(match.group(1)) - 1]
|
||||
transfer = self._profile_field(html, "传输")
|
||||
if transfer is not None:
|
||||
cells = transfer.xpath('.//tr[@id="tr_item_min"]/td')
|
||||
if len(cells) >= 4:
|
||||
for index, attribute in ((0, "upload"), (2, "download")):
|
||||
size = self._parse_size(cells[index].xpath("string(.)").strip())
|
||||
if size is not None:
|
||||
setattr(self, attribute, size)
|
||||
ratio = cells[3].xpath("string(.)").strip()
|
||||
self.ratio = (text_tools.parse_float(ratio.replace(",", ""))
|
||||
if re.fullmatch(r"[\d,]+(?:\.\d+)?", ratio)
|
||||
else round(self.upload / self.download, 3) if self.download else 0.0)
|
||||
|
||||
def _parse_user_torrent_seeding_info(self, html_text: str, multi_page: Optional[bool] = False) -> Optional[str]:
|
||||
"""
|
||||
累加做种列表中的实际容量和可见做种人数,并跟随本站的下一页入口。
|
||||
|
||||
:param html_text: 当前做种列表页
|
||||
:param multi_page: 是否为后续页面
|
||||
:return: 尚未请求的下一页地址;无后续页时为 None
|
||||
"""
|
||||
html = etree.HTML(html_text)
|
||||
if html is None:
|
||||
return None
|
||||
if not multi_page:
|
||||
self._visited_seeding_pages = {urljoin(self._base_url, self._torrent_seeding_page or "")}
|
||||
rows = html.xpath('//table[@id="table_tm"]//tr[@id="tr_list" or starts-with(@class, "tm_tr")]')
|
||||
for row in rows:
|
||||
cells = row.xpath("./td")
|
||||
if len(cells) < 4:
|
||||
continue
|
||||
size = self._parse_size(cells[3].xpath("string(.)").strip())
|
||||
if size is None:
|
||||
logger.warning(f"{self._site_name} 做种列表存在无法解析的体积,统计可能不完整")
|
||||
continue
|
||||
self.seeding += 1
|
||||
self.seeding_size += size
|
||||
seeders = cells[4].xpath("string(.)").strip() if len(cells) > 4 else ""
|
||||
if re.fullmatch(r"[\d,]+", seeders):
|
||||
self.seeding_info.append([int(seeders.replace(",", "")), size])
|
||||
return self._next_seeding_page(html) if rows else None
|
||||
|
||||
def _next_seeding_page(self, html: etree._Element) -> Optional[str]:
|
||||
"""
|
||||
保留当前账号和做种筛选,拒绝跨站、跨账号或循环的分页链接。
|
||||
|
||||
:param html: 当前做种列表页节点
|
||||
:return: 保留账号筛选的完整下一页地址;没有有效下一页时为 None
|
||||
"""
|
||||
links: list[str] = html.xpath('//a[@rel="next" or contains(., "下一页") or contains(., "下一頁")]/@href')
|
||||
for link in links:
|
||||
target = urlsplit(urljoin(urljoin(self._base_url, self._torrent_seeding_page or ""), link))
|
||||
query = dict(parse_qsl(target.query))
|
||||
if (target.scheme != urlsplit(self._base_url).scheme
|
||||
or target.netloc != urlsplit(self._base_url).netloc or target.path != _SEEDING_PATH
|
||||
or query.get("pop", "8") != "8" or query.get("uid", str(self.userid)) != str(self.userid)):
|
||||
continue
|
||||
query.update(pop="8", uid=str(self.userid))
|
||||
next_page = urlunsplit(target._replace(query=urlencode(sorted(query.items())), fragment=""))
|
||||
if next_page not in self._visited_seeding_pages:
|
||||
self._visited_seeding_pages.add(next_page)
|
||||
return next_page
|
||||
return None
|
||||
@@ -21,6 +21,10 @@ _DEFAULT_XPATH = "//a[@class='faqlink']/@href"
|
||||
|
||||
# 只登记相对于通用配方的专站差异,配方构造时复制参数,避免跨请求共享可变状态。
|
||||
_SITE_RECIPES: dict[str, dict[str, Any]] = {
|
||||
"star-space.net": {
|
||||
"url": "p_rss/rss_create.php", "method": "get", "params": {},
|
||||
"xpath": "//a[contains(@href, 'rss.php?key=')]/@href",
|
||||
},
|
||||
"hares.top": {"xpath": "//*[@id='layui-layer100001']/div[2]/div/p[4]/a/@href"},
|
||||
"et8.org": {"xpath": "//*[@id='outer']/table/tbody/tr/td/table/tbody/tr/td/a[2]/@href"},
|
||||
"pttime.org": {
|
||||
@@ -70,8 +74,9 @@ def get_rss_recipe(url: str) -> RssLinkRecipe:
|
||||
return RssLinkRecipe(
|
||||
url=urljoin(url, conf.get("url") or "getrss.php"),
|
||||
xpath=conf.get("xpath") or _DEFAULT_XPATH,
|
||||
params=dict(conf.get("params") or _DEFAULT_PARAMS),
|
||||
params=dict(conf.get("params", _DEFAULT_PARAMS)),
|
||||
render=bool(conf.get("render")),
|
||||
method=conf.get("method", "post"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -850,8 +850,8 @@ flowchart LR
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1188 |
|
||||
| 内部导入边 | 10,419 |
|
||||
| Python 模块 | 1189 |
|
||||
| 内部导入边 | 10,428 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) |
|
||||
|
||||
30
docs/site-starspace.md
Normal file
30
docs/site-starspace.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# 星空站点页面适配
|
||||
|
||||
星空(`https://star-space.net/`)使用带 `p_` 前缀的 FireFly 定制页面。
|
||||
用户资料需要包含 `StarSpace` 解析器的 MoviePilot 后端及索引资源 `3.0.33` 或更高版本。
|
||||
仅更新站点资源无法给旧后端补充解析器;已有的搜索、音乐分区和下载规则保持原有协议。
|
||||
|
||||
## 配置与使用
|
||||
|
||||
- 站点地址填写 `https://star-space.net/`,认证继续使用站点 Cookie。
|
||||
- 更新后端及站点资源后,重新刷新站点用户数据。资料入口为
|
||||
`p_index/index.php` → `p_user/user_detail.php?uid=…`,做种入口为
|
||||
`p_torrent/torrent_user.php?pop=8&uid=…`。
|
||||
- RSS 请先登录站点,在 `p_rss/rss_create.php` 创建所需订阅。MoviePilot 从该页读取已创建的
|
||||
`p_rss/rss.php?key=…` 地址,不自动创建或删除站内 RSS。
|
||||
- 如果已经保存了返回 404 的旧 RSS 地址,请在站点设置中替换为站内生成的新地址,或清空旧地址后重新获取。
|
||||
多个 RSS 有不同筛选条件时,直接填写需要的那一个。
|
||||
|
||||
「连接测试」中的网页可访问只证明网页连通性,不能代替用户资料解析或用户认证接口的结果。
|
||||
解析器只从已登录页面的本站个人资料链接确认用户编号,不使用 Cookie 中的 `ffid` 冒充资料解析成功。
|
||||
|
||||
## 验证范围
|
||||
|
||||
离线测试按现有公开星空适配定义构造合成页面,覆盖个人资料路由、上传/下载的省略 B 单位、
|
||||
等级、加入时间、魔力、做种分页、Cookie 与分页隔离,以及已有 RSS 的读取与失败行为。
|
||||
这些用例不是报告者账号的页面录制,也不代表已在其群晖 Docker 实例或真实星空账号中完成验收。
|
||||
|
||||
参考:[问题 #7494](https://github.com/jxxghp/MoviePilot/issues/7494)、
|
||||
[公开的星空页面适配定义](https://github.com/pt-plugins/PT-depiler/blob/7817b40695537d0377b0640bbfe4bf0f991b98f8/src/packages/site/definitions/starspace.ts)。
|
||||
[RSS 页面协议参考](https://github.com/linyuan0213/nexus-media/blob/98419056c91484cceb3bfc1df90eb7e9ebdcfdac/src/app/plugin_framework/builtin_plugins/autogenrss/backend/handlers/starspace.py)。
|
||||
个人 Cookie、RSS key 和完整 RSS 地址均为凭据,请勿提交到公开 Issue。
|
||||
@@ -977,8 +977,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10419,
|
||||
"edge_sha256": "07addae85ceb8650f858dee5e61b5612e04e3e3cda83c96809ef9f3594d65a08",
|
||||
"edge_count": 10428,
|
||||
"edge_sha256": "1aba7ad1b3c39cff4b0300db80d2f3de3b61246109f5481f3e0160752f0fb765",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -8321,6 +8321,15 @@
|
||||
"app.modules.indexer.parser.small_horse -> app.modules",
|
||||
"app.modules.indexer.parser.small_horse -> app.modules.indexer",
|
||||
"app.modules.indexer.parser.small_horse -> app.modules.indexer.parser",
|
||||
"app.modules.indexer.parser.starspace -> app.foundation",
|
||||
"app.modules.indexer.parser.starspace -> app.foundation.temporal",
|
||||
"app.modules.indexer.parser.starspace -> app.foundation.text",
|
||||
"app.modules.indexer.parser.starspace -> app.modules",
|
||||
"app.modules.indexer.parser.starspace -> app.modules.indexer",
|
||||
"app.modules.indexer.parser.starspace -> app.modules.indexer.parser",
|
||||
"app.modules.indexer.parser.starspace -> app.modules.indexer.parser.nexus_php",
|
||||
"app.modules.indexer.parser.starspace -> app.runtime",
|
||||
"app.modules.indexer.parser.starspace -> app.runtime.log",
|
||||
"app.modules.indexer.parser.sunnypt -> app.foundation",
|
||||
"app.modules.indexer.parser.sunnypt -> app.foundation.temporal",
|
||||
"app.modules.indexer.parser.sunnypt -> app.modules",
|
||||
@@ -11400,7 +11409,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1188,
|
||||
"module_count": 1189,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -12221,6 +12230,7 @@
|
||||
"app.modules.indexer.parser.piggo",
|
||||
"app.modules.indexer.parser.rousi",
|
||||
"app.modules.indexer.parser.small_horse",
|
||||
"app.modules.indexer.parser.starspace",
|
||||
"app.modules.indexer.parser.sunnypt",
|
||||
"app.modules.indexer.parser.tnode",
|
||||
"app.modules.indexer.parser.torrent_leech",
|
||||
|
||||
@@ -99,6 +99,63 @@ def _response(status: int, text: str) -> Response:
|
||||
return response
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hostname", ["star-space.net", "www.star-space.net"])
|
||||
def test_starspace_reads_existing_feed_from_prefixed_rss_page(rss_access: Mock, hostname: str) -> None:
|
||||
"""
|
||||
星空只读取站内已创建的 RSS 链接,保留完整票据且不提交通用生成表单。
|
||||
"""
|
||||
rss_access.get.return_value = _response(
|
||||
200, '<a href="../p_rss/rss.php?key=FAKESTAR&cat=all">RSS</a>'
|
||||
'<a href="../p_login/logout.php">退出</a>',
|
||||
)
|
||||
|
||||
link, message = RssHelper().get_rss_link(f"https://{hostname}/", "FAKECOOKIE", "audit", timeout=19)
|
||||
|
||||
assert link == f"https://{hostname}/p_rss/rss.php?key=FAKESTAR&cat=all"
|
||||
assert not message
|
||||
rss_access.get.assert_called_once_with(
|
||||
url=f"https://{hostname}/p_rss/rss_create.php", ua="audit",
|
||||
headers={"Cookie": "FAKECOOKIE"}, proxies=None, timeout=19,
|
||||
)
|
||||
rss_access.post.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hostname", ["star-space.net.evil.example", "notstar-space.net"])
|
||||
def test_starspace_recipe_does_not_match_unrelated_hosts(hostname: str) -> None:
|
||||
"""
|
||||
名称相似的无关站点继续使用通用 RSS 页面和表单。
|
||||
"""
|
||||
recipe = get_rss_recipe(f"https://{hostname}/")
|
||||
assert recipe.url == f"https://{hostname}/getrss.php"
|
||||
assert recipe.params["showrows"] == 50
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [
|
||||
"<html><body>尚未创建 RSS</body></html>",
|
||||
'<a href="/p_rss/rss_create.php">创建 RSS</a>',
|
||||
'<form action="/p_login/login_act.php">登录</form>',
|
||||
])
|
||||
def test_starspace_missing_existing_feed_does_not_create_or_guess_one(rss_access: Mock, body: str) -> None:
|
||||
"""
|
||||
未创建 RSS 或登录失效时明确失败,不自动创建站内订阅或拼接账号票据。
|
||||
"""
|
||||
rss_access.get.return_value = _response(200, body)
|
||||
link, message = RssHelper().get_rss_link("https://star-space.net/", "FAKECOOKIE", "audit")
|
||||
assert not link and message
|
||||
rss_access.post.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [403, 404, 503])
|
||||
def test_starspace_rss_get_keeps_http_failure_details(rss_access: Mock, status: int) -> None:
|
||||
"""
|
||||
读取失败保留 HTTP 状态诊断,且不会换用错误的通用生成表单。
|
||||
"""
|
||||
rss_access.get.return_value = _response(status, "")
|
||||
link, message = RssHelper().get_rss_link("https://star-space.net/", "FAKECOOKIE", "audit")
|
||||
assert not link and str(status) in message
|
||||
rss_access.post.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("old_query,new_query,expected", [
|
||||
("passkey=OLD&cat=1", "passkey=NEW", [("cat", "1"), ("passkey", "NEW")]),
|
||||
("cat=1&passkey=OLD-TAIL", "passkey=NEW", [("cat", "1"), ("passkey", "NEW")]),
|
||||
|
||||
225
tests/test_starspace_parser.py
Normal file
225
tests/test_starspace_parser.py
Normal file
@@ -0,0 +1,225 @@
|
||||
"""
|
||||
按公开的星空适配协议构造页面回放,验证专站路由、容量单位及分页隔离。
|
||||
|
||||
页面均为合成结构,账号、Cookie 和 RSS 票据不来自真实用户。
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.indexer import IndexerModule
|
||||
from app.modules.indexer.parser.starspace import StarSpaceSiteUserInfo
|
||||
|
||||
BASE_URL = "https://star-space.net/"
|
||||
HOME_URL = f"{BASE_URL}p_index/index.php"
|
||||
DETAIL_URL = f"{BASE_URL}p_user/user_detail.php?uid=42"
|
||||
SEEDING_URL = f"{BASE_URL}p_torrent/torrent_user.php?pop=8&uid=42"
|
||||
NEXT_URL = f"{BASE_URL}p_torrent/torrent_user.php?page=2&pop=8&uid=42"
|
||||
HOMEPAGE = """
|
||||
<html><body>
|
||||
<a href="../p_user/user_detail.php?uid=42"><span class="uc1">Offline User</span></a>
|
||||
<span id="user_info"><a href="../p_user/user_upload.php?uid=42">上传:445.11 G</a></span>
|
||||
<span id="user_info_no_hover">下载:29.61 G</span>
|
||||
<a href="../p_torrent/torrent_user.php?pop=8&uid=42">做种(3)</a>
|
||||
<a href="../p_torrent/torrent_user.php?pop=9&uid=42">下载(2)</a>
|
||||
<a href="../p_bonus/bonus_hour.php">魔力:12,345.67</a>
|
||||
<a href="../p_login/logout.php">退出</a>
|
||||
</body></html>
|
||||
"""
|
||||
DETAIL = """
|
||||
<html><body><table>
|
||||
<tr id="tr_item"><td class="nowrap">用户名称</td><td><span>Offline User</span></td></tr>
|
||||
<tr id="tr_item"><td class="nowrap">用户等级</td><td><img alt="class6" src="../pic/class6.png"></td></tr>
|
||||
<tr id="tr_item"><td class="nowrap">加入日期</td><td>2024-01-02 03:04:05 (2年前)</td></tr>
|
||||
<tr id="tr_item"><td class="nowrap">魔力</td><td>23,456.78</td></tr>
|
||||
<tr id="tr_item"><td class="nowrap">传输</td><td><table><tr id="tr_item_min">
|
||||
<td>1 T</td><td>已完成</td><td>512 G</td><td>2.001</td>
|
||||
</tr></table></td></tr>
|
||||
</table></body></html>
|
||||
"""
|
||||
FIRST_SEEDING_PAGE = """
|
||||
<table id="table_tm">
|
||||
<tr><th>种子</th><th>分类</th><th>日期</th><th>大小</th><th>做种</th></tr>
|
||||
<tr id="tr_list"><td>One</td><td>电影</td><td>今天</td><td>2 G</td><td><a>12</a></td></tr>
|
||||
<tr class="tm_tr_top"><td>Two</td><td>电影</td><td>今天</td><td>3 GiB</td><td><a>4</a></td></tr>
|
||||
</table>
|
||||
<a href="torrent_user.php?pop=8&uid=42&page=2">下一页</a>
|
||||
"""
|
||||
LAST_SEEDING_PAGE = """
|
||||
<table id="table_tm">
|
||||
<tr id="tr_list"><td>Three</td><td>音乐</td><td>昨天</td><td>1.5 T</td><td><a>6</a></td></tr>
|
||||
</table>
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def parser() -> StarSpaceSiteUserInfo:
|
||||
"""
|
||||
注入无网络能力的客户端,保留真实解析生命周期。
|
||||
"""
|
||||
return StarSpaceSiteUserInfo(
|
||||
"星空", HOME_URL, "ffid=42; auth=FAKECOOKIE", None, None, request_utils=Mock(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def replay(monkeypatch: pytest.MonkeyPatch) -> tuple[dict[str, str], list[str]]:
|
||||
"""
|
||||
只允许请求已登记的合成页面,错误路由会直接令用例失败。
|
||||
"""
|
||||
pages = {HOME_URL: HOMEPAGE, DETAIL_URL: DETAIL, SEEDING_URL: FIRST_SEEDING_PAGE,
|
||||
NEXT_URL: LAST_SEEDING_PAGE}
|
||||
requested = []
|
||||
|
||||
def read_page(_parser: StarSpaceSiteUserInfo, url: str, **_kwargs: object) -> str:
|
||||
"""
|
||||
记录真实解析器请求的地址,回放对应页面。
|
||||
"""
|
||||
requested.append(url)
|
||||
return pages[url]
|
||||
|
||||
monkeypatch.setattr(StarSpaceSiteUserInfo, "_get_page_content", read_page)
|
||||
return pages, requested
|
||||
|
||||
|
||||
def test_starspace_full_parse_keeps_prefixes_and_collects_all_seeding_pages(
|
||||
parser: StarSpaceSiteUserInfo, replay: tuple[dict[str, str], list[str]],
|
||||
) -> None:
|
||||
"""
|
||||
首页、详情和两页做种均通过正确路径读取,资料表显示值优先于首页概览。
|
||||
"""
|
||||
_pages, requested = replay
|
||||
parser.parse()
|
||||
|
||||
assert requested == [HOME_URL, DETAIL_URL, SEEDING_URL, NEXT_URL]
|
||||
assert parser.userid == "42" and parser.username == "Offline User"
|
||||
assert parser.user_level == "Veteran User"
|
||||
assert parser.join_at == "2024-01-02 03:04:05"
|
||||
assert parser.upload == 1024 ** 4
|
||||
assert parser.download == 512 * 1024 ** 3
|
||||
assert parser.ratio == 2.001
|
||||
assert parser.bonus == 23456.78
|
||||
assert parser.seeding == 3 and parser.leeching == 2
|
||||
assert parser.seeding_size == 5 * 1024 ** 3 + round(1.5 * 1024 ** 4)
|
||||
assert parser.seeding_info == [[12, 2 * 1024 ** 3], [4, 3 * 1024 ** 3], [6, round(1.5 * 1024 ** 4)]]
|
||||
parser._request_utils.close.assert_called_once()
|
||||
|
||||
|
||||
def test_starspace_indexer_uses_declared_schema_without_reloading_parsers(
|
||||
monkeypatch: pytest.MonkeyPatch, replay: tuple[dict[str, str], list[str]],
|
||||
) -> None:
|
||||
"""
|
||||
资源声明可经真实索引模块生成用户统计,不动态重载其他站点解析器。
|
||||
"""
|
||||
module = object.__new__(IndexerModule)
|
||||
monkeypatch.setattr(module, "_site_schemas", [StarSpaceSiteUserInfo])
|
||||
|
||||
result = module.refresh_userdata({
|
||||
"schema": "StarSpace", "name": "星空", "url": BASE_URL,
|
||||
"userdata_path": "p_index/index.php", "cookie": "ffid=42; auth=FAKECOOKIE", "public": False,
|
||||
})
|
||||
|
||||
assert result is not None and not result.err_msg
|
||||
assert result.userid == "42" and result.seeding == 3
|
||||
assert result.upload == 1024 ** 4 and result.ratio == 2.001
|
||||
assert replay[1] == [HOME_URL, DETAIL_URL, SEEDING_URL, NEXT_URL]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("href", [
|
||||
"../p_user/user_detail.php?uid=42", "/p_user/user_detail.php?uid=42&view=1",
|
||||
"https://star-space.net/p_user/user_detail.php?uid=42",
|
||||
])
|
||||
def test_starspace_user_link_preserves_prefixed_detail_route(parser: StarSpaceSiteUserInfo, href: str) -> None:
|
||||
"""
|
||||
相对和绝对个人链接均保留 p_user 前缀,不拼接不存在的 userdetails.php。
|
||||
"""
|
||||
parser._parse_site_page(f'<a href="{href}"><span>Offline User</span></a>')
|
||||
assert parser.userid == "42" and parser.username == "Offline User"
|
||||
assert parser._user_detail_page == "p_user/user_detail.php?uid=42"
|
||||
assert parser._torrent_seeding_page == "p_torrent/torrent_user.php?pop=8&uid=42"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("href", [
|
||||
"../p_user/edit_user.php", "../p_user/user_detail.php?uid=0",
|
||||
"../p_user/user_detail.php?uid=abc", "../p_user/user_detail.php?uid=1&uid=2",
|
||||
"https://unrelated.example/p_user/user_detail.php?uid=42",
|
||||
"http://star-space.net/p_user/user_detail.php?uid=42",
|
||||
"../p_user/user_detail.php.bak?uid=42",
|
||||
])
|
||||
def test_starspace_does_not_infer_identity_from_cookie_or_unrelated_links(
|
||||
parser: StarSpaceSiteUserInfo, href: str,
|
||||
) -> None:
|
||||
"""
|
||||
资料链接无效时不能从 Cookie、脚本或其他站点的用户编号推断成功。
|
||||
"""
|
||||
parser._parse_site_page(f'<a href="{href}">Offline User</a><script>var uid=42;</script>')
|
||||
assert parser.userid is None
|
||||
assert parser._user_detail_page is None and parser._torrent_seeding_page is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value,expected", [
|
||||
("445.11 G", round(445.11 * 1024 ** 3)), ("2 GB", 2 * 1024 ** 3),
|
||||
("2 GiB", 2 * 1024 ** 3), ("1,024 M", 1024 ** 3), ("0 B", 0),
|
||||
("512", 512), ("", None), ("--", None), ("2 GBB", None),
|
||||
])
|
||||
def test_starspace_size_units_are_normalized_once(value: str, expected: Optional[int]) -> None:
|
||||
"""
|
||||
单位只补齐一次 B,并区分明确的零值与未提供的容量。
|
||||
"""
|
||||
assert StarSpaceSiteUserInfo._parse_size(value) == expected
|
||||
|
||||
|
||||
def test_starspace_homepage_overview_and_missing_profile_keep_available_values(parser: StarSpaceSiteUserInfo) -> None:
|
||||
"""
|
||||
概览中的无 B 单位和魔力可独立解析,空详情不会清空已取得的流量。
|
||||
"""
|
||||
parser._parse_site_page(HOMEPAGE)
|
||||
parser._parse_user_base_info(HOMEPAGE)
|
||||
parser._parse_user_detail_info("")
|
||||
assert parser.upload == round(445.11 * 1024 ** 3)
|
||||
assert parser.download == round(29.61 * 1024 ** 3)
|
||||
assert parser.bonus == 12345.67
|
||||
assert parser.seeding == 3 and parser.leeching == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("href", [
|
||||
"https://unrelated.example/p_torrent/torrent_user.php?page=2", "/p_rss/rss_create.php",
|
||||
"http://star-space.net/p_torrent/torrent_user.php?page=2",
|
||||
"?pop=9&uid=42&page=2", "?pop=8&uid=99&page=2", "?pop=8&uid=42",
|
||||
])
|
||||
def test_starspace_seeding_rejects_unrelated_or_repeated_next_page(parser: StarSpaceSiteUserInfo, href: str) -> None:
|
||||
"""
|
||||
下一页不能切换站点、用户或下载列表,也不能回到已请求的首页。
|
||||
"""
|
||||
parser._parse_site_page(HOMEPAGE)
|
||||
page = FIRST_SEEDING_PAGE.split("</table>")[0] + f'</table><a rel="next" href="{href}">下一页</a>'
|
||||
assert parser._parse_user_torrent_seeding_info(page) is None
|
||||
assert parser.seeding == 2
|
||||
|
||||
|
||||
def test_starspace_seeding_detects_cycle_and_does_not_guess_seeders(parser: StarSpaceSiteUserInfo) -> None:
|
||||
"""
|
||||
循环链接只安排一次;页面未提供做种人数时不伪造人数分布。
|
||||
"""
|
||||
parser._parse_site_page(HOMEPAGE)
|
||||
assert parser._parse_user_torrent_seeding_info(FIRST_SEEDING_PAGE) == NEXT_URL
|
||||
page = LAST_SEEDING_PAGE.replace("<td><a>6</a></td>", "<td>--</td>")
|
||||
page += f'<a rel="next" href="{NEXT_URL}">下一页</a>'
|
||||
assert parser._parse_user_torrent_seeding_info(page, multi_page=True) is None
|
||||
assert parser.seeding == 3
|
||||
assert len(parser.seeding_info) == 2
|
||||
|
||||
|
||||
def test_starspace_invalid_login_stops_before_detail_and_seeding(
|
||||
parser: StarSpaceSiteUserInfo, replay: tuple[dict[str, str], list[str]],
|
||||
) -> None:
|
||||
"""
|
||||
登录页即使保留 Cookie 编号,也只能读取一次首页并报告未登录。
|
||||
"""
|
||||
pages, requested = replay
|
||||
pages[HOME_URL] = '<form action="login_act.php"><input name="username"></form>'
|
||||
parser.parse()
|
||||
assert requested == [HOME_URL]
|
||||
assert parser.userid is None and parser.err_msg
|
||||
Reference in New Issue
Block a user