mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-30 16:05:05 +08:00
fix(rss): recover missing and expired site feeds safely
This commit is contained in:
@@ -2,15 +2,21 @@
|
||||
RSS 订阅获取、站点链接生成、浏览器回退与资源解析。
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any, List, Optional, Protocol, Tuple, Union
|
||||
from typing import Any, Callable, List, Literal, Optional, Protocol, Tuple, Union
|
||||
|
||||
import dateutil.parser
|
||||
from cachetools import TTLCache
|
||||
from lxml import etree
|
||||
|
||||
from app.application.configuration import get_chain_runtime_config_snapshot
|
||||
from app.application.site.contract import SiteRepository, SiteSnapshot
|
||||
from app.domain import site as site_rules
|
||||
from app.foundation.url import UrlUtils, mask_url_credentials
|
||||
from app.runtime.log import logger
|
||||
|
||||
@@ -202,6 +208,7 @@ def reset_rss_ports() -> None:
|
||||
_rss_http_port = None
|
||||
_rss_browser_port = None
|
||||
_rss_parser_port = None
|
||||
_rss_link_recovery.reset()
|
||||
|
||||
|
||||
def _require_rss_ports() -> Tuple[RssHttpPort, RssBrowserPort, RssParserPort]:
|
||||
@@ -224,6 +231,25 @@ class RssHelper:
|
||||
# 最大解析条目数
|
||||
MAX_RSS_ITEMS = 1000
|
||||
|
||||
def _response_status(self, response: RssResponsePort, url: str) -> Literal["valid", "expired", "error"]:
|
||||
"""
|
||||
在 XML 解析前判断大小、明确过期事实和 HTTP 错误,保留非 200 的响应正文。
|
||||
|
||||
:param response: 实际收到的响应,不能以 requests 的真假值判断其是否存在
|
||||
:param url: 仅供脱敏诊断的请求地址
|
||||
:return: 可解析、需要续期或普通失败
|
||||
"""
|
||||
if len(response.content) > self.MAX_RSS_SIZE:
|
||||
logger.warning(f"RSS文件过大: {len(response.content) / 1024 / 1024:.1f}MB,跳过解析")
|
||||
return "error"
|
||||
if response.status_code == 200 or "rss" in response.text.casefold():
|
||||
if _require_rss_site_port().is_site_rss_expired(response.text):
|
||||
return "expired"
|
||||
if response.status_code != 200:
|
||||
logger.error(f"RSS请求失败,状态码: {response.status_code}, URL: {mask_url_credentials(url)}")
|
||||
return "error"
|
||||
return "valid"
|
||||
|
||||
@staticmethod
|
||||
def _parse_publish_time(value: str) -> Optional[datetime]:
|
||||
"""
|
||||
@@ -284,38 +310,27 @@ class RssHelper:
|
||||
timeout=timeout or 30,
|
||||
headers=headers,
|
||||
)
|
||||
if not ret:
|
||||
if ret is None:
|
||||
logger.error(f"获取RSS失败:请求返回空值,URL: {mask_url_credentials(url)}")
|
||||
return False
|
||||
except Exception as err:
|
||||
logger.error(mask_url_credentials(f"获取RSS失败:{str(err)} - {traceback.format_exc()}"))
|
||||
return False
|
||||
|
||||
if ret:
|
||||
if ret.status_code != 200:
|
||||
logger.error(f"RSS请求失败,状态码: {ret.status_code}, URL: {mask_url_credentials(url)}")
|
||||
return False
|
||||
if ret is not None:
|
||||
ret_xml = None
|
||||
root = None
|
||||
try:
|
||||
# 检查响应大小,避免处理过大的RSS文件
|
||||
raw_data = ret.content
|
||||
if raw_data and len(raw_data) > self.MAX_RSS_SIZE:
|
||||
logger.warning(f"RSS文件过大: {len(raw_data) / 1024 / 1024:.1f}MB,跳过解析")
|
||||
return False
|
||||
status = self._response_status(ret, url)
|
||||
if status != "valid":
|
||||
return None if status == "expired" else False
|
||||
|
||||
if _require_rss_site_port().is_site_rss_expired(ret.text):
|
||||
return None
|
||||
|
||||
if raw_data:
|
||||
if ret.content:
|
||||
ret_xml = http_port.decode_xml(
|
||||
ret,
|
||||
performance_mode=get_chain_runtime_config_snapshot().encoding_detection_performance_mode,
|
||||
confidence_threshold=get_chain_runtime_config_snapshot().encoding_detection_min_confidence
|
||||
)
|
||||
rust_items = self.__parse_with_rust(ret_xml)
|
||||
if rust_items is not None:
|
||||
return rust_items
|
||||
if not ret_xml:
|
||||
ret_xml = ret.text
|
||||
|
||||
@@ -323,10 +338,8 @@ class RssHelper:
|
||||
logger.error("RSS内容为空")
|
||||
return False
|
||||
|
||||
# 检查是否包含基本的RSS/XML结构
|
||||
ret_xml_stripped = ret_xml.strip()
|
||||
if not ret_xml_stripped.startswith('<'):
|
||||
logger.error("RSS内容不是有效的XML格式")
|
||||
if not site_rules.is_rss_document(ret_xml):
|
||||
logger.error("RSS内容不是有效的订阅文档,可能是登录页或错误页")
|
||||
return False
|
||||
|
||||
rust_items = self.__parse_with_rust(ret_xml)
|
||||
@@ -463,7 +476,29 @@ class RssHelper:
|
||||
|
||||
return ret_array
|
||||
|
||||
def get_rss_link(self, url: str, cookie: str, ua: str, proxy: bool = False, timeout: Optional[int] = None) -> Tuple[str, str]:
|
||||
@staticmethod
|
||||
def _extract_rss_link(html_text: str, recipe: RssLinkRecipe) -> Optional[str]:
|
||||
"""
|
||||
提取可抓取的生成结果,宽选择器跳过导航链接,兼容相对地址。
|
||||
|
||||
:param html_text: 生成页面正文
|
||||
:param recipe: Module 提供的生成页地址和选择器
|
||||
:return: 最后一个有效候选;没有候选时为 None
|
||||
"""
|
||||
html = etree.HTML(html_text)
|
||||
if html is None:
|
||||
return None
|
||||
try:
|
||||
for value in reversed(html.xpath(recipe.xpath)):
|
||||
candidate = site_rules.normalize_rss_link(value, recipe.url, broad=recipe.xpath == "//a/@href")
|
||||
if candidate:
|
||||
return candidate
|
||||
return None
|
||||
finally:
|
||||
del html
|
||||
|
||||
def get_rss_link(self, url: str, cookie: str, ua: str, proxy: bool = False,
|
||||
timeout: Optional[int] = None, render: bool = False) -> Tuple[str, str]:
|
||||
"""
|
||||
获取站点rss地址
|
||||
:param url: 站点地址
|
||||
@@ -471,12 +506,13 @@ class RssHelper:
|
||||
:param ua: 站点ua
|
||||
:param proxy: 是否使用代理
|
||||
:param timeout: 请求超时时间
|
||||
:param render: 是否按站点配置使用浏览器生成,专站配方也可强制启用
|
||||
:return: rss地址、错误信息
|
||||
"""
|
||||
try:
|
||||
http_port, browser_port, _ = _require_rss_ports()
|
||||
recipe = _require_rss_site_port().get_site_rss_recipe(url)
|
||||
if recipe.render:
|
||||
if recipe.render or render:
|
||||
html_text = browser_port.render(
|
||||
url=recipe.url,
|
||||
cookie=cookie,
|
||||
@@ -493,7 +529,7 @@ class RssHelper:
|
||||
proxies=get_chain_runtime_config_snapshot().proxy if proxy else None,
|
||||
timeout=timeout or 30,
|
||||
)
|
||||
if res:
|
||||
if res is not None and res.status_code == 200:
|
||||
html_text = res.text
|
||||
elif res is not None:
|
||||
return "", f"获取 {url} RSS链接失败,错误码:{res.status_code},错误原因:{res.reason}"
|
||||
@@ -501,17 +537,204 @@ class RssHelper:
|
||||
return "", f"获取RSS链接失败:无法连接 {url} "
|
||||
|
||||
if html_text:
|
||||
html = None
|
||||
try:
|
||||
html = etree.HTML(html_text)
|
||||
if html is not None and len(html) > 0:
|
||||
rss_link = html.xpath(recipe.xpath)
|
||||
if rss_link:
|
||||
return str(rss_link[-1]), ""
|
||||
finally:
|
||||
if html is not None:
|
||||
del html
|
||||
rss_link = self._extract_rss_link(html_text, recipe)
|
||||
if rss_link:
|
||||
return rss_link, ""
|
||||
|
||||
return "", f"获取RSS链接失败:{url}"
|
||||
except Exception as e:
|
||||
return "", f"获取 {url} RSS链接失败:{str(e)}"
|
||||
message = mask_url_credentials(f"获取 {url} RSS链接失败:{str(e)}")
|
||||
return "", message.replace(cookie, "<REDACTED>") if cookie else message
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RssLinkResult:
|
||||
"""
|
||||
站点 RSS 获取、续期和验证的结果,不在进程缓存中保留地址或订阅内容。
|
||||
|
||||
:param url: 当前可使用的地址,失败或正在退避时为 None
|
||||
:param items: 本次验证抓取到的资源,供同轮复用;未抓取时为 None
|
||||
:param message: 不含凭据的失败或延后原因
|
||||
:param notify: 是否需要发送本轮首次或间隔一天的续期失败通知
|
||||
"""
|
||||
|
||||
url: Optional[str] = None
|
||||
items: Optional[list[dict[str, Any]]] = None
|
||||
message: str = ""
|
||||
notify: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _RssLinkState:
|
||||
"""
|
||||
单份站点配置的失败退避与通知时间,不保存 Cookie、RSS 地址等原文。
|
||||
|
||||
:param failures: 本配置连续获取失败次数,最多累计十二次
|
||||
:param retry_at: 下一次允许生成链接的单调时钟时间
|
||||
:param notified_at: 最近一次过期通知时间;None 表示尚未通知
|
||||
"""
|
||||
|
||||
failures: int = 0
|
||||
retry_at: float = 0.0
|
||||
notified_at: Optional[float] = None
|
||||
|
||||
|
||||
class _RssLinkRecovery:
|
||||
"""
|
||||
合并同站点的链接获取,使用有界短期状态退避失败并防止重复通知。
|
||||
"""
|
||||
|
||||
# 不支持自动生成的站点也会进入退避;最多保存一天、1024 份配置的摘要。
|
||||
_STATE_TTL = 24 * 3600
|
||||
_RETRY_INITIAL = 5 * 60
|
||||
_RETRY_MAX = 3600
|
||||
|
||||
def __init__(self, clock: Callable[[], float] = time.monotonic) -> None:
|
||||
"""
|
||||
创建仅保护状态读写的锁,网络与数据库操作始终在锁外执行。
|
||||
|
||||
:param clock: 单调时钟,测试可注入虚拟时间
|
||||
"""
|
||||
self._clock = clock
|
||||
self._lock = threading.Lock()
|
||||
self._states: TTLCache[str, _RssLinkState] = TTLCache(maxsize=1024, ttl=self._STATE_TTL, timer=clock)
|
||||
self._inflight: set[int] = set()
|
||||
|
||||
def reset(self) -> None:
|
||||
"""
|
||||
技术端口退出时清理退避状态,仍在执行的准入由原调用负责释放。
|
||||
"""
|
||||
with self._lock:
|
||||
self._states.clear()
|
||||
|
||||
@staticmethod
|
||||
def _fingerprint(site: SiteSnapshot) -> str:
|
||||
"""
|
||||
用配置摘要隔离退避,更新 Cookie 或手工修改 RSS 后立即获得新预算。
|
||||
"""
|
||||
values = (site.id, site.url, site.rss, site.cookie, site.ua, site.apikey, site.token,
|
||||
site.proxy, site.timeout, site.render)
|
||||
return hashlib.sha256(repr(values).encode("utf-8")).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def _existing(site: SiteSnapshot, expired_url: Optional[str]) -> Optional[RssLinkResult]:
|
||||
"""
|
||||
保留有效配置及并发手工修改,停用或公开站点不自动生成私有订阅。
|
||||
"""
|
||||
current = UrlUtils.normalize_http_url(site.rss)
|
||||
if current and current != expired_url:
|
||||
return RssLinkResult(url=current)
|
||||
if site.is_active is False or site.public:
|
||||
return RssLinkResult(message="站点已停用或无需生成私有RSS")
|
||||
if site.rss and site.rss.strip() and not current:
|
||||
return RssLinkResult(message="RSS地址无效,请修正或清空后自动获取")
|
||||
return None
|
||||
|
||||
def _failure(self, key: str, message: str, expired: bool) -> RssLinkResult:
|
||||
"""
|
||||
失败从五分钟逐次退避到一小时,过期通知对同配置最多每天发送一次。
|
||||
"""
|
||||
with self._lock:
|
||||
previous = self._states.get(key, _RssLinkState())
|
||||
now = self._clock()
|
||||
failures = min(previous.failures + 1, 12)
|
||||
notify = expired and (previous.notified_at is None or now - previous.notified_at >= self._STATE_TTL)
|
||||
self._states[key] = _RssLinkState(
|
||||
failures=failures,
|
||||
retry_at=now + min(self._RETRY_INITIAL * 2 ** (failures - 1), self._RETRY_MAX),
|
||||
notified_at=now if notify else previous.notified_at,
|
||||
)
|
||||
logger.warning(message)
|
||||
return RssLinkResult(message=message, notify=notify)
|
||||
|
||||
@staticmethod
|
||||
def _attempt(site: SiteSnapshot, repository: SiteRepository, helper: RssHelper,
|
||||
expired_url: Optional[str]) -> RssLinkResult:
|
||||
"""
|
||||
生成并实际验证候选,只有验证成功且配置未变化时才保存新地址。
|
||||
"""
|
||||
if not site.url or not site.cookie:
|
||||
return RssLinkResult(message="站点缺少地址或Cookie,无法自动获取RSS")
|
||||
ua = site.ua or get_chain_runtime_config_snapshot().user_agent
|
||||
generated, message = helper.get_rss_link(
|
||||
url=site.url, cookie=site.cookie, ua=ua, proxy=bool(site.proxy),
|
||||
timeout=site.timeout, render=bool(site.render),
|
||||
)
|
||||
normalized = site_rules.normalize_rss_link(generated, site.url)
|
||||
if normalized is None:
|
||||
safe_message = mask_url_credentials(message).replace(site.cookie, "<REDACTED>")
|
||||
return RssLinkResult(message=safe_message or "未获取到有效RSS地址")
|
||||
candidate = site_rules.renew_rss_link(site.rss, normalized)
|
||||
if candidate == expired_url:
|
||||
return RssLinkResult(message="站点仍返回已过期的RSS地址,请更新Cookie或手工填写")
|
||||
items = helper.parse(candidate, proxy=bool(site.proxy), timeout=site.timeout or 30, ua=ua)
|
||||
if not isinstance(items, list):
|
||||
return RssLinkResult(message="新RSS地址验证失败,保留原配置并稍后重试")
|
||||
saved = repository.update_rss_if_unchanged(site, candidate)
|
||||
if not saved.success:
|
||||
return RssLinkResult(message=saved.message or "保存新RSS地址失败")
|
||||
logger.info(f"站点 {site.domain} RSS地址已验证并更新")
|
||||
return RssLinkResult(url=candidate, items=items)
|
||||
|
||||
def ensure(self, domain: str, repository: SiteRepository, *, expired_url: Optional[str],
|
||||
helper: RssHelper) -> RssLinkResult:
|
||||
"""
|
||||
按最新已提交配置补全缺失地址或续期,仅让同站点一个调用执行生成请求。
|
||||
|
||||
:param domain: 站点域名,用于从仓储读取最新配置
|
||||
:param repository: 独立事务的站点仓储
|
||||
:param expired_url: 本轮明确过期的地址;None 表示只补全缺失地址
|
||||
:param helper: RSS 生成及抓取边界
|
||||
:return: 可复用的地址、已验证资源或退避原因
|
||||
"""
|
||||
try:
|
||||
site = repository.get_by_domain(domain)
|
||||
except Exception as error:
|
||||
message = f"站点 {domain} RSS配置读取失败({type(error).__name__})"
|
||||
logger.error(message)
|
||||
return RssLinkResult(message=message)
|
||||
if site is None:
|
||||
return RssLinkResult(message="站点不存在")
|
||||
existing = self._existing(site, expired_url)
|
||||
if existing is not None:
|
||||
return existing
|
||||
key = self._fingerprint(site)
|
||||
with self._lock:
|
||||
state = self._states.get(key, _RssLinkState())
|
||||
if site.id in self._inflight or state.retry_at > self._clock():
|
||||
return RssLinkResult(message="RSS自动获取正在进行或等待重试")
|
||||
self._inflight.add(site.id)
|
||||
try:
|
||||
# 准入前另一个生成任务可能刚结束,重新读取以复用其保存结果。
|
||||
current = repository.get_by_domain(domain)
|
||||
if current != site:
|
||||
existing = self._existing(current, expired_url) if current else None
|
||||
return existing or RssLinkResult(message="站点配置已变化或已删除,稍后重试")
|
||||
result = self._attempt(site, repository, helper, expired_url)
|
||||
if result.url:
|
||||
with self._lock:
|
||||
self._states.pop(key, None)
|
||||
return result
|
||||
return self._failure(key, result.message, expired_url is not None)
|
||||
except Exception as error:
|
||||
return self._failure(key, f"站点 {domain} RSS自动获取失败({type(error).__name__})", expired_url is not None)
|
||||
finally:
|
||||
with self._lock:
|
||||
self._inflight.remove(site.id)
|
||||
|
||||
|
||||
_rss_link_recovery = _RssLinkRecovery()
|
||||
|
||||
|
||||
def ensure_site_rss(domain: str, repository: SiteRepository, *, expired_url: Optional[str] = None,
|
||||
helper: Optional[RssHelper] = None) -> RssLinkResult:
|
||||
"""
|
||||
供手工维护、CookieCloud 和订阅抓取共用的 RSS 补全与续期入口。
|
||||
|
||||
:param domain: 已保存站点的域名
|
||||
:param repository: 负责短事务和原子比较更新的仓储
|
||||
:param expired_url: 已确认过期的旧地址;缺省只补全空配置
|
||||
:param helper: 可选的 RSS 边界,默认使用启动注入的真实端口
|
||||
:return: 地址、可供本轮复用的资源,以及脱敏的失败提示
|
||||
"""
|
||||
return _rss_link_recovery.ensure(domain, repository, expired_url=expired_url, helper=helper or RssHelper())
|
||||
|
||||
@@ -750,6 +750,16 @@ class SiteWritePort(Protocol):
|
||||
"""
|
||||
...
|
||||
|
||||
def update_rss_if_unchanged(self, site: SiteSnapshot, rss: str) -> SiteWriteResult:
|
||||
"""
|
||||
仅在生成期间站点配置未变化时,在独立同步事务中保存 RSS。
|
||||
|
||||
:param site: 发起生成请求前读取的配置快照,认证及原 RSS 必须参与原子比较
|
||||
:param rss: 已通过实际抓取验证的新订阅地址
|
||||
:return: 提交成功或配置已变化、记录已删除等失败说明
|
||||
"""
|
||||
...
|
||||
|
||||
def update_userdata(
|
||||
self,
|
||||
domain: str,
|
||||
|
||||
@@ -15,7 +15,7 @@ from lxml import etree
|
||||
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.messaging.site import SiteInteractionHandler
|
||||
from app.application.rss import RssHelper
|
||||
from app.application.rss import RssHelper, ensure_site_rss
|
||||
from app.application.security.cookie import CookieHelper
|
||||
from app.application.site.contract import (
|
||||
SiteCookieLoginSource,
|
||||
@@ -534,22 +534,13 @@ class SiteChain(InteractionChainMixin, ChainBase):
|
||||
status, _ = self.test(domain)
|
||||
if status:
|
||||
logger.info(f"站点【{site_info.name}】连通性正常,不同步CookieCloud数据")
|
||||
if not site_info.public and not site_info.rss:
|
||||
rss_url: Optional[str]
|
||||
rss_url, errmsg = rsshelper.get_rss_link(
|
||||
url=site_info.url,
|
||||
cookie=cookie,
|
||||
ua=site_info.ua or self.runtime_config.user_agent,
|
||||
proxy=bool(site_info.proxy),
|
||||
timeout=site_info.timeout or 15,
|
||||
)
|
||||
if rss_url:
|
||||
repository.update_rss(domain=domain, rss=rss_url)
|
||||
else:
|
||||
logger.warning(errmsg)
|
||||
if not site_info.public and not str(site_info.rss or "").strip():
|
||||
ensure_site_rss(domain, repository, helper=rsshelper)
|
||||
return 0, 0, 0, False
|
||||
logger.info(f"更新站点 {domain} Cookie ...")
|
||||
repository.update_cookie(domain=domain, cookies=cookie)
|
||||
updated = repository.update_cookie(domain=domain, cookies=cookie)
|
||||
if updated.success:
|
||||
ensure_site_rss(domain, repository, helper=rsshelper)
|
||||
return 1, 0, 0, True
|
||||
if not indexer:
|
||||
return 0, 0, 0, True
|
||||
@@ -567,22 +558,19 @@ class SiteChain(InteractionChainMixin, ChainBase):
|
||||
if not indexer.get("public") and not SiteUtils.is_logged_in(response.text):
|
||||
logger.warning(f"站点 {indexer.get('name')} 登录失败,无法添加站点")
|
||||
return 0, 0, 1, False
|
||||
rss_url = None
|
||||
if not indexer.get("public") and domain_url:
|
||||
rss_url, errmsg = rsshelper.get_rss_link(
|
||||
url=domain_url, cookie=cookie, ua=self.runtime_config.user_agent, proxy=proxy
|
||||
)
|
||||
if errmsg:
|
||||
logger.warning(errmsg)
|
||||
repository.add(SiteMutation({
|
||||
added = repository.add(SiteMutation({
|
||||
"name": indexer.get("name"),
|
||||
"url": domain_url,
|
||||
"domain": domain,
|
||||
"cookie": cookie,
|
||||
"rss": rss_url,
|
||||
"rss": None,
|
||||
"proxy": 1 if proxy else 0,
|
||||
"public": 1 if indexer.get("public") else 0,
|
||||
}))
|
||||
if not added.success:
|
||||
logger.warning(f"站点 {domain} 添加失败:{added.message}")
|
||||
return 0, 0, 1, False
|
||||
ensure_site_rss(domain, repository, helper=rsshelper)
|
||||
return 0, 1, 0, True
|
||||
|
||||
def _cookiecloud_blacklisted(self, domain: str) -> bool:
|
||||
@@ -648,6 +636,21 @@ class SiteChain(InteractionChainMixin, ChainBase):
|
||||
text=response.text,
|
||||
)
|
||||
|
||||
@eventmanager.register(EventType.SiteUpdated)
|
||||
def complete_site_rss(self, event: Event) -> None:
|
||||
"""
|
||||
手工新增、修改或更新 Cookie 提交后,补全缺失的站点 RSS。
|
||||
|
||||
:param event: 已提交的站点更新事件;有效的手工 RSS 不会被覆盖
|
||||
"""
|
||||
data = event.event_data if event and isinstance(event.event_data, dict) else {}
|
||||
domain = data.get("domain")
|
||||
if not isinstance(domain, str) or not domain:
|
||||
return
|
||||
if domain.startswith("http"):
|
||||
domain = site_domain(domain)
|
||||
ensure_site_rss(domain, self.site_repository)
|
||||
|
||||
@eventmanager.register(EventType.SiteUpdated)
|
||||
def cache_site_icon(self, event: Event) -> None:
|
||||
"""
|
||||
@@ -927,10 +930,14 @@ class SiteChain(InteractionChainMixin, ChainBase):
|
||||
cookie, ua, msg = result
|
||||
if not cookie:
|
||||
return False, msg
|
||||
self.site_repository.update(site_id, SiteMutation({
|
||||
updated = self.site_repository.update(site_id, SiteMutation({
|
||||
"cookie": cookie,
|
||||
"ua": ua
|
||||
}))
|
||||
if updated is None:
|
||||
return False, "站点已删除,Cookie未保存"
|
||||
if updated.domain:
|
||||
ensure_site_rss(updated.domain, self.site_repository)
|
||||
return True, msg
|
||||
return False, "未知错误"
|
||||
|
||||
|
||||
@@ -2,14 +2,12 @@
|
||||
站点种子刷新、预识别缓存和订阅候选准备。
|
||||
"""
|
||||
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from typing import Any, Callable, Dict, List, Optional, Union, cast
|
||||
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.rss import RssHelper
|
||||
from app.application.rss import RssHelper, RssLinkResult, ensure_site_rss
|
||||
from app.application.site.observation import SiteSearchObservation, capture_site_search_observation
|
||||
from app.application.site.protocol import site_domain, torrent_resource_identity
|
||||
|
||||
@@ -355,25 +353,18 @@ class TorrentsChain(ChainBase):
|
||||
|
||||
def rss(self, domain: str) -> List[TorrentInfo]:
|
||||
"""
|
||||
获取站点RSS内容,返回种子清单,TTL缓存3分钟
|
||||
获取站点 RSS 内容,补全缺失地址,并在明确过期后同轮恢复一次。
|
||||
|
||||
:param domain: 站点域名
|
||||
:return: 本轮获取的种子清单;普通网络故障不触发凭据更新
|
||||
"""
|
||||
logger.info(f'开始获取站点 {domain} RSS ...')
|
||||
site = SitesHelper().get_indexer(domain)
|
||||
if not site:
|
||||
logger.error(f'站点 {domain} 不存在!')
|
||||
return []
|
||||
rss_url = UrlUtils.normalize_http_url(site.get("rss"))
|
||||
if rss_url is None:
|
||||
logger.warning(f'站点 {domain} RSS地址无效,跳过获取')
|
||||
return []
|
||||
rss_items = RssHelper().parse(rss_url, True if site.get("proxy") else False,
|
||||
timeout=int(site.get("timeout") or 30),
|
||||
ua=site.get("ua") if site.get("ua") else None)
|
||||
rss_items = self._rss_items(domain, site)
|
||||
if rss_items is None:
|
||||
# rss过期,尝试保留原配置生成新的rss
|
||||
self.__renew_rss_url(domain=domain, site=site)
|
||||
return []
|
||||
if not isinstance(rss_items, list):
|
||||
logger.error(f'站点 {domain} RSS返回格式无效!')
|
||||
@@ -414,6 +405,40 @@ class TorrentsChain(ChainBase):
|
||||
del rss_items
|
||||
return ret_torrents
|
||||
|
||||
@staticmethod
|
||||
def _parse_rss_url(site: dict[str, Any], url: str) -> Union[List[dict[str, Any]], None, bool]:
|
||||
"""
|
||||
使用当前站点的代理、超时和 User-Agent 读取订阅。
|
||||
"""
|
||||
return RssHelper().parse(url, proxy=bool(site.get("proxy")), timeout=int(site.get("timeout") or 30),
|
||||
ua=site.get("ua") or None)
|
||||
|
||||
def _recovered_rss_items(self, result: RssLinkResult, site: dict[str, Any]) -> Union[List[dict[str, Any]], bool]:
|
||||
"""
|
||||
复用续期时的验证结果;并发手工改成新地址时最多补抓一次,不递归续期。
|
||||
"""
|
||||
if not result.url:
|
||||
return False
|
||||
if result.items is not None:
|
||||
return result.items
|
||||
items = self._parse_rss_url(site, result.url)
|
||||
return items if isinstance(items, list) else False
|
||||
|
||||
def _rss_items(self, domain: str, site: dict[str, Any]) -> Union[List[dict[str, Any]], None, bool]:
|
||||
"""
|
||||
区分空配置、手工无效地址、明确过期和临时故障,限制每轮只恢复一次。
|
||||
"""
|
||||
rss_url = UrlUtils.normalize_http_url(site.get("rss"))
|
||||
if rss_url is None:
|
||||
if str(site.get("rss") or "").strip():
|
||||
logger.warning(f'站点 {domain} RSS地址无效,跳过获取')
|
||||
return None
|
||||
return self._recovered_rss_items(self.__renew_rss_url(domain, site, expired=False), site)
|
||||
items = self._parse_rss_url(site, rss_url)
|
||||
if items is None:
|
||||
return self._recovered_rss_items(self.__renew_rss_url(domain, site), site)
|
||||
return items
|
||||
|
||||
@staticmethod
|
||||
def _music_browse_paths(site: dict[str, Any]) -> List[str]:
|
||||
"""
|
||||
@@ -769,45 +794,22 @@ class TorrentsChain(ChainBase):
|
||||
return str(media_source)
|
||||
return "unknown"
|
||||
|
||||
def __renew_rss_url(self, domain: str, site: dict[str, Any]) -> None:
|
||||
def __renew_rss_url(self, domain: str, site: dict[str, Any], *, expired: bool = True) -> RssLinkResult:
|
||||
"""
|
||||
保留原配置生成新的rss地址
|
||||
通过统一用例补全或续期,只有被退避策略选中的过期失败才发送通知。
|
||||
|
||||
:param domain: 站点域名
|
||||
:param site: 本轮抓取时的索引配置,保留实际过期地址作为比较依据
|
||||
:param expired: 是否由明确过期响应触发,False 仅补全空地址
|
||||
:return: 保存结果及供本轮复用的验证资源
|
||||
"""
|
||||
try:
|
||||
# RSS链接过期
|
||||
logger.error(f"站点 {domain} RSS链接已过期,正在尝试自动获取!")
|
||||
# 自动生成rss地址
|
||||
site_url = site.get("url")
|
||||
site_cookie = site.get("cookie")
|
||||
site_rss = site.get("rss")
|
||||
if not isinstance(site_url, str) or not isinstance(site_cookie, str) or not isinstance(site_rss, str):
|
||||
return
|
||||
rss_url, errmsg = RssHelper().get_rss_link(
|
||||
url=site_url,
|
||||
cookie=site_cookie,
|
||||
ua=site.get("ua") or self.runtime_config.user_agent,
|
||||
proxy=True if site.get("proxy") else False,
|
||||
timeout=site.get("timeout"),
|
||||
)
|
||||
if rss_url:
|
||||
# 获取新的日期的passkey
|
||||
match = re.search(r'passkey=([a-zA-Z0-9]+)', rss_url)
|
||||
if match:
|
||||
new_passkey = match.group(1)
|
||||
# 获取过期rss除去passkey部分
|
||||
new_rss = re.sub(r'&passkey=([a-zA-Z0-9]+)', f'&passkey={new_passkey}', site_rss)
|
||||
logger.info(f"更新站点 {domain} RSS地址 ...")
|
||||
self.site_repository.update_rss(domain=domain, rss=new_rss)
|
||||
else:
|
||||
self.post_message(
|
||||
Message(mtype=MessageType.SiteMessage, title=f"站点 {domain} RSS链接已过期",
|
||||
link=self.runtime_config.site_url)
|
||||
)
|
||||
else:
|
||||
self.post_message(
|
||||
Message(mtype=MessageType.SiteMessage, title=f"站点 {domain} RSS链接已过期",
|
||||
link=self.runtime_config.site_url))
|
||||
except Exception as e:
|
||||
logger.error(f"站点 {domain} RSS链接自动获取失败:{str(e)} - {traceback.format_exc()}")
|
||||
self.post_message(Message(mtype=MessageType.SiteMessage, title=f"站点 {domain} RSS链接已过期",
|
||||
link=self.runtime_config.site_url))
|
||||
if expired and any(not isinstance(site.get(key), str) for key in ("url", "cookie", "rss")):
|
||||
return RssLinkResult(message="站点配置不完整,无法自动续期")
|
||||
result = ensure_site_rss(domain, self.site_repository,
|
||||
expired_url=UrlUtils.normalize_http_url(site.get("rss")) if expired else None)
|
||||
if result.notify:
|
||||
self.post_message(Message(
|
||||
mtype=MessageType.SiteMessage, title=f"站点 {domain} RSS链接已过期,自动更新失败",
|
||||
text=result.message, link=self.runtime_config.site_url,
|
||||
))
|
||||
return result
|
||||
|
||||
@@ -572,6 +572,22 @@ class TransactionalSiteRepository:
|
||||
"""
|
||||
return self._write(lambda repository: SiteWriteResult(*repository.update_rss(domain, rss)))
|
||||
|
||||
def update_rss_if_unchanged(self, site: SiteSnapshot, rss: str) -> SiteWriteResult:
|
||||
"""
|
||||
比较生成请求使用的快照并提交 RSS,配置变化时保留用户的新设置。
|
||||
|
||||
:param site: 请求开始前脱离 Session 的站点快照
|
||||
:param rss: 已验证的新地址
|
||||
:return: 原子更新结果;事务异常继续交给用例报告
|
||||
"""
|
||||
expected = {key: getattr(site, key) for key in (
|
||||
"domain", "url", "rss", "cookie", "ua", "apikey", "token", "proxy",
|
||||
"timeout", "render", "public", "is_active",
|
||||
)}
|
||||
return self._write(lambda repository: SiteWriteResult(*repository.update_rss_if_unchanged(
|
||||
site.id, rss, expected,
|
||||
)))
|
||||
|
||||
def update_userdata(
|
||||
self,
|
||||
domain: str,
|
||||
|
||||
@@ -12,7 +12,7 @@ from sqlalchemy.orm import Session
|
||||
from sqlalchemy.sql.dml import Update
|
||||
from sqlalchemy.sql.elements import TextClause
|
||||
|
||||
from app.db.base import DbOper
|
||||
from app.db.base import DbOper, execute_dml
|
||||
from app.db.models.site import Site
|
||||
from app.db.models.siteicon import SiteIcon
|
||||
from app.db.models.sitestatistic import SiteStatistic
|
||||
@@ -511,6 +511,29 @@ class SiteOper(DbOper):
|
||||
})
|
||||
return True, "更新站点RSS地址成功"
|
||||
|
||||
def update_rss_if_unchanged(self, sid: int, rss: str, expected: Mapping[str, Any]) -> Tuple[bool, str]:
|
||||
"""
|
||||
原子比较生成前的配置并暂存 RSS,避免覆盖并发修改或同域名新建的站点。
|
||||
|
||||
:param sid: 原站点主键
|
||||
:param rss: 验证成功的新地址
|
||||
:param expected: Adapter 从快照投影的认证、地址和启用状态
|
||||
:return: 是否暂存成功及失败原因;事务由调用方提交
|
||||
"""
|
||||
statement = update(Site).where(
|
||||
Site.id == sid, *(getattr(Site, key) == value for key, value in expected.items())
|
||||
).values(rss=rss).execution_options(synchronize_session=False)
|
||||
|
||||
def stage(session: Session) -> Tuple[bool, str]:
|
||||
"""
|
||||
在调用方会话中执行带前置条件的单条更新,不持有网络请求事务。
|
||||
"""
|
||||
if execute_dml(session, statement) == 1:
|
||||
return True, "更新站点RSS地址成功"
|
||||
return False, "站点配置已变化或已删除,未覆盖当前RSS地址"
|
||||
|
||||
return self._execute_sync_write(stage)
|
||||
|
||||
def update_userdata(self, domain: str, name: str, payload: dict[str, Any]) -> Tuple[bool, str]:
|
||||
"""
|
||||
更新站点用户数据
|
||||
|
||||
@@ -2,13 +2,96 @@
|
||||
站点地址匹配、页面登录状态与用户资料提取的纯规则。
|
||||
"""
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Optional
|
||||
from urllib.parse import urljoin
|
||||
from urllib.parse import parse_qsl, urlencode, urljoin, urlsplit, urlunsplit
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.foundation.dom import DomUtils
|
||||
from app.foundation.url import split_netloc
|
||||
from app.foundation.url import UrlUtils, split_netloc
|
||||
|
||||
# 生成页返回的认证参数必须整体更新,不能混用旧凭据、签名或有效期。
|
||||
_RSS_AUTH_PARAMS = frozenset({
|
||||
"passkey", "rsskey", "authkey", "key", "token", "auth", "auth_token",
|
||||
"access_token", "apikey", "api_key", "sign", "signature", "par", "uid", "userid", "user_id",
|
||||
})
|
||||
# 有效期和时间参数可能也是用户配置;只有生成页返回新值时才替换。
|
||||
_RSS_TIME_PARAMS = frozenset({"timestamp", "expires", "expire", "expiry", "exp", "t"})
|
||||
|
||||
|
||||
def normalize_rss_link(value: object, base_url: str, *, broad: bool = False) -> Optional[str]:
|
||||
"""
|
||||
将生成页里的 RSS 地址补全为 HTTP(S) 地址,拒绝空锚点和页面脚本。
|
||||
|
||||
:param value: XPath 提取的链接文本
|
||||
:param base_url: 生成页面地址,用于解析相对链接
|
||||
:param broad: 选择器匹配全部链接时,额外要求路径或参数带订阅标记
|
||||
:return: 可供抓取的完整地址;没有可信候选时为 None
|
||||
"""
|
||||
if not isinstance(value, str) or not value.strip() or value.strip().startswith("#"):
|
||||
return None
|
||||
try:
|
||||
candidate = UrlUtils.normalize_http_url(urljoin(base_url, value.strip()))
|
||||
except ValueError:
|
||||
return None
|
||||
if candidate is None:
|
||||
return None
|
||||
parts = urlsplit(candidate)
|
||||
if parts.username is not None or parts.password is not None:
|
||||
return None
|
||||
if broad and not (
|
||||
any(marker in parts.path.lower() for marker in ("rss", "feed"))
|
||||
or any(key.lower() in _RSS_AUTH_PARAMS for key, _value in parse_qsl(parts.query))
|
||||
):
|
||||
return None
|
||||
return candidate
|
||||
|
||||
|
||||
def renew_rss_link(previous: Optional[str], generated: str) -> str:
|
||||
"""
|
||||
用生成页的新认证参数续期,保留原链接的分类、条数等自定义筛选。
|
||||
|
||||
使用生成页返回的订阅入口,兼容域名、协议和路径迁移。编码在路径或 par 中的
|
||||
不透明凭据随生成结果整体更新,最终可用性由调用方抓取验证。
|
||||
|
||||
:param previous: 旧订阅地址;缺失或无效时直接使用生成结果
|
||||
:param generated: 已规范化的生成地址
|
||||
:return: 保留筛选并更新认证参数的候选地址
|
||||
"""
|
||||
old_url = UrlUtils.normalize_http_url(previous)
|
||||
if old_url is None:
|
||||
return generated
|
||||
old, new = urlsplit(old_url), urlsplit(generated)
|
||||
generated_params = parse_qsl(new.query, keep_blank_values=True)
|
||||
refreshed_keys = _RSS_AUTH_PARAMS | {key.lower() for key, _value in generated_params
|
||||
if key.lower() in _RSS_TIME_PARAMS}
|
||||
old_filters = [(key, value) for key, value in parse_qsl(old.query, keep_blank_values=True)
|
||||
if key.lower() not in refreshed_keys]
|
||||
filter_names = {key for key, _value in old_filters}
|
||||
new_params = [(key, value) for key, value in generated_params if key not in filter_names]
|
||||
# 路径本身携带票据时必须采用新路径,避免续期后继续访问旧票据。
|
||||
return urlunsplit((new.scheme, new.netloc, new.path, urlencode(old_filters + new_params), new.fragment))
|
||||
|
||||
|
||||
def is_rss_document(content: str) -> bool:
|
||||
"""
|
||||
只读取 XML 的首个元素,区分合法空订阅与登录页、错误页。
|
||||
|
||||
:param content: 解码后的订阅响应,调用方已经限制总大小
|
||||
:return: 根元素是 RSS、Atom 或 RDF 时为 True
|
||||
"""
|
||||
try:
|
||||
with BytesIO(content.encode("utf-8")) as stream:
|
||||
parser = etree.iterparse(stream, events=("start",), recover=True, resolve_entities=False,
|
||||
no_network=True, huge_tree=False)
|
||||
try:
|
||||
_event, root = next(parser)
|
||||
return etree.QName(root).localname.lower() in {"rss", "feed", "rdf"}
|
||||
finally:
|
||||
del parser
|
||||
except (ValueError, StopIteration, etree.XMLSyntaxError):
|
||||
return False
|
||||
|
||||
|
||||
def urls_match(first: str, second: str) -> bool:
|
||||
|
||||
@@ -14,7 +14,7 @@ REDACTED_URL_CREDENTIAL = "<REDACTED>"
|
||||
URL_QUERY_CREDENTIAL_PATTERN = re.compile(
|
||||
r"(?i)([?&](?:[a-z0-9]+[-_.])*(?:"
|
||||
r"passkey|rsskey|authkey|auth_token|access_token|access_key|refresh_token|id_token"
|
||||
r"|api_key|apikey|secret_key|secret|password|passwd|token|cookie|sign|pwd|auth|uid|pid|key"
|
||||
r"|api_key|apikey|secret_key|secret|password|passwd|token|cookie|sign|signature|par|pwd|auth|uid|pid|key"
|
||||
r"))(\s*=\s*)[^\s&#]*"
|
||||
)
|
||||
# 主机端口与 userinfo 口令都由冒号引导,因此只在 authority 内以最后一个 @ 为边界遮盖口令。
|
||||
|
||||
@@ -4,10 +4,15 @@
|
||||
这里只选择和解释站点配方,HTTP、浏览器和 XML 解析仍由公共用例执行。
|
||||
"""
|
||||
|
||||
import re
|
||||
from html import unescape
|
||||
from typing import Any
|
||||
from urllib.parse import urljoin, urlparse
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.application.rss import RssLinkRecipe
|
||||
from app.domain import site as site_rules
|
||||
|
||||
_DEFAULT_PARAMS = {
|
||||
"inclbookmarked": 0, "itemsmalldescr": 1, "showrows": 50, "search_mode": 1,
|
||||
@@ -77,4 +82,24 @@ def is_rss_expired(text: str) -> bool:
|
||||
:param text: 原始 RSS 响应正文
|
||||
:return: 是否属于支持的过期响应
|
||||
"""
|
||||
return text.strip() in _EXPIRED_MESSAGES
|
||||
if site_rules.is_rss_document(text):
|
||||
return False
|
||||
if "<" in text:
|
||||
root = etree.HTML(text)
|
||||
if root is None:
|
||||
return False
|
||||
try:
|
||||
bodies = root.xpath("//body")
|
||||
body = bodies[0] if bodies else root
|
||||
text = " ".join(body.xpath(".//text()[not(ancestor::script) and not(ancestor::style)]"))
|
||||
finally:
|
||||
del root
|
||||
return _expiration_text(text) in {_expiration_text(message) for message in _EXPIRED_MESSAGES}
|
||||
|
||||
|
||||
def _expiration_text(text: str) -> str:
|
||||
"""
|
||||
统一过期提示的实体、换行、标点和大小写,仍要求完整文案匹配。
|
||||
"""
|
||||
normalized = " ".join(unescape(text).replace(",", ",").replace("!", "!").split())
|
||||
return re.sub(r"\s*([,!])\s*", r"\1", normalized).casefold()
|
||||
|
||||
@@ -412,13 +412,13 @@ flowchart TB
|
||||
|
||||
架构基线中的 consumer 表示宿主源码中可静态证明的注册点,不是运行时 listener 实例数。
|
||||
collector 只接受 canonical `eventmanager`、`EventManager()` 及其有限别名,忽略其他对象的同名
|
||||
`register`/`add_event_listener`;当前宿主有 17 个静态注册点,另保留 1 个由工作流配置驱动的
|
||||
`register`/`add_event_listener`;当前宿主有 18 个静态注册点,另保留 1 个由工作流配置驱动的
|
||||
真实动态注册。`app/plugins/**` 插件副本不进入宿主事实。
|
||||
|
||||
生产者与消费者共用 `scripts/architecture/event_facts.py` 这一份逐调用事实源。当前宿主有 76 个
|
||||
生产调用,其中 74 个静态解析为 76 个事件引用,`Command.send_plugin_event` 的插件事件类型和
|
||||
`dispatch_event_handler` 的持久事件恢复类型保持动态;后者只接受 `DURABLE_EVENT_TOPICS`
|
||||
登记的事件。18 个消费注册中 17 个静态、1 个动态。生成的
|
||||
登记的事件。19 个消费注册中 18 个静态、1 个动态。生成的
|
||||
`runtime-contract-baseline.json` 保存 line-free 事实、数量和枚举索引;人工维护的
|
||||
`runtime-contract-policy.json` 只批准 consumer 的精确 fingerprint、owner 和理由,任何新增、替换、
|
||||
重复或陈旧项都会失败,`--write-host` 不会改写该 policy。
|
||||
@@ -630,6 +630,16 @@ flowchart LR
|
||||
- **RSS 和下载**:Application 持有 `RssSitePort` / `SiteProtocolPort`,启动组合根通过
|
||||
`ModuleInvocationDispatcher` 注入实现。专站 RSS 页面、表单和过期响应归 `modules/indexer/rss.py`,
|
||||
新旧换票配方、首次下载确认及旧站点加密包装归索引 Module;公共用例保留传输、限流、重试和来源安全策略。
|
||||
- **RSS 补全和续期**:`application/rss.py` 的 `ensure_site_rss` 统一服务站点更新事件、
|
||||
CookieCloud、登录更新和订阅抓取。只为启用的私有站点补全空地址;已有手工地址保留,
|
||||
只有完整的明确过期响应才续期,HTTP 错误、登录页和普通网络失败不会触发换票。
|
||||
`domain/site.py` 合并生成地址与原筛选,整体替换认证值及生成页更新的有效期,支持相对链接。
|
||||
候选经过真实 RSS 解析后,仓储以原主键、认证、访问配置和原 RSS 做单条条件更新,
|
||||
在独立短事务中提交,防止覆盖并发修改;验证结果供本轮抓取复用。
|
||||
同站点的生成请求互斥,网络与数据库操作在锁外;失败从五分钟退避至一小时,
|
||||
同配置的过期失败通知每天最多一次。状态仅在进程内保存一天且最多 1024 份配置摘要,
|
||||
修改 Cookie 或链接即获得新预算,重启会重置预算。公开站点、停用站点、缺少 Cookie 或
|
||||
不支持生成的站点保留人工配置入口;这些机制不代表所有专站及账号已经实测。
|
||||
- **身份和兼容**:Domain 只解释通用身份字段与查询签名;专站路径和短时票据由 Module 解释,
|
||||
缺少公开资源 ID 的旧检查点继续重取原页。旧站点地址、CookieCloud 和 DB Oper 使用独立的精确 Legacy SDK 门面,
|
||||
不把一种兼容入口的符号混入另一种导出面。
|
||||
@@ -835,19 +845,19 @@ flowchart LR
|
||||
|
||||
### 10.2 当前架构快照
|
||||
|
||||
以下是 2026-11-12 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照,
|
||||
以下是 2026-11-14 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照,
|
||||
不代表某个已发布镜像或正在运行的实例已经验证。
|
||||
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1166 |
|
||||
| 内部导入边 | 10,159 |
|
||||
| 内部导入边 | 10,165 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) |
|
||||
| Module Contract V2 spec | 237(其中 223 个方法进入 `run_module` 观察面) |
|
||||
| Event Contract | 53 |
|
||||
| Event producer / consumer | 76(74 静态、2 动态)/ 18(17 静态、1 动态) |
|
||||
| Event producer / consumer | 76(74 静态、2 动态)/ 19(18 静态、1 动态) |
|
||||
| Model/Oper 自动事务与自建 Session | 0 |
|
||||
| 组合根外 `SystemConfigOper()` | 0 |
|
||||
|
||||
|
||||
@@ -261,6 +261,16 @@ with patch.object(SomeModule, "fetch", new=AsyncMock(return_value=FAKE)):
|
||||
新增排程策略和轮询 owner 两个模块,因此三个启动入口的模块数快照各增加 2;
|
||||
仅更新该结构事实,原冷导入耗时记录与 3000ms 上限保留,生命周期组件集合及释放要求不变。
|
||||
|
||||
### 站点 RSS 补全和续期
|
||||
|
||||
`tests/test_rss_recovery.py` 离线回放 RSS 自动补全和续期:真实 HTTP 响应真假语义、HTML 包装的
|
||||
明确过期提示、合法空订阅与登录页区分、相对地址、重复筛选参数和完整认证值替换,
|
||||
以及 CookieCloud、手工更新事件和登录更新入口。虚拟时钟验证失败退避、每日通知去重与
|
||||
配置变更后的即时重试;真实线程屏障验证同站合并且不阻塞其他站点,验证资源直接供同轮使用。
|
||||
`tests/test_site_repository.py` 在临时 SQLite 中验证新链接提交、NULL 条件比较、并发配置修改
|
||||
及删除重建的保护,并验证 Oper 仍由调用方决定提交或回滚。测试不使用真实凭据、不连接站点,
|
||||
专站页面变更及真实账号续期仍需对应站点验收。
|
||||
|
||||
### 站点流控
|
||||
|
||||
本地流控等待由实际拒绝原因决定:访问间隔不足只等待间隔,计数配额耗尽才等待计数窗口。
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
"app/application/plugin/identity.py:PluginIdentity.__post_init__": 26,
|
||||
"app/application/plugin/install.py:PluginInstallCommand.__execute_locked": 28,
|
||||
"app/application/plugin/source.py:select_plugin_candidate": 19,
|
||||
"app/application/rss.py:RssHelper._parse_impl": 37,
|
||||
"app/application/rss.py:RssHelper._parse_impl": 34,
|
||||
"app/application/security/cookie.py:CookieHelper._get_site_cookie_ua_impl": 45,
|
||||
"app/application/security/cookie.py:CookieHelper._get_site_cookie_ua_impl.__page_handler": 43,
|
||||
"app/application/torrent/download.py:TorrentHelper.download_torrent": 22,
|
||||
|
||||
@@ -963,8 +963,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10159,
|
||||
"edge_sha256": "b00d7edef6d49ece1f002dfef6f21b80a787959c08b60729c8b9a805d330c125",
|
||||
"edge_count": 10165,
|
||||
"edge_sha256": "3256a88ae8af9a22db4a253019e9cd28ba510edce839b09886aacb0011e31389",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -4154,6 +4154,10 @@
|
||||
"app.application.recognition -> app.schemas.types",
|
||||
"app.application.rss -> app.application",
|
||||
"app.application.rss -> app.application.configuration",
|
||||
"app.application.rss -> app.application.site",
|
||||
"app.application.rss -> app.application.site.contract",
|
||||
"app.application.rss -> app.domain",
|
||||
"app.application.rss -> app.domain.site",
|
||||
"app.application.rss -> app.foundation",
|
||||
"app.application.rss -> app.foundation.url",
|
||||
"app.application.rss -> app.runtime",
|
||||
@@ -8125,6 +8129,8 @@
|
||||
"app.modules.indexer.parser.zhixing -> app.modules.indexer.parser",
|
||||
"app.modules.indexer.rss -> app.application",
|
||||
"app.modules.indexer.rss -> app.application.rss",
|
||||
"app.modules.indexer.rss -> app.domain",
|
||||
"app.modules.indexer.rss -> app.domain.site",
|
||||
"app.modules.indexer.spider -> app.adapters",
|
||||
"app.modules.indexer.spider -> app.adapters.network",
|
||||
"app.modules.indexer.spider -> app.adapters.network.http",
|
||||
|
||||
@@ -1381,8 +1381,8 @@
|
||||
]
|
||||
},
|
||||
"event_facts": {
|
||||
"consumer_event_reference_count": 17,
|
||||
"consumer_registration_count": 18,
|
||||
"consumer_event_reference_count": 18,
|
||||
"consumer_registration_count": 19,
|
||||
"consumers": [
|
||||
{
|
||||
"caller": "app.chain.download.facade",
|
||||
@@ -1474,6 +1474,21 @@
|
||||
"receiver_kind": "canonical_singleton",
|
||||
"registration_kind": "decorator"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.site",
|
||||
"dynamic": false,
|
||||
"events": [
|
||||
"EventType.SiteUpdated"
|
||||
],
|
||||
"fingerprint": "d8f405fce4efc179dea6661d54b25b700b95eef996a93d1f2b4507d022e8ee8f",
|
||||
"handler": "SiteChain.complete_site_rss",
|
||||
"invalid": false,
|
||||
"method": "register",
|
||||
"priority": "<default>",
|
||||
"qualname": "SiteChain",
|
||||
"receiver_kind": "canonical_singleton",
|
||||
"registration_kind": "decorator"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.subscribe.facade",
|
||||
"dynamic": false,
|
||||
@@ -1931,7 +1946,8 @@
|
||||
"consumer_fingerprints": [
|
||||
"1200b7097150958ec2003a597237ab746defe80a865b0efef30596dc3b503598",
|
||||
"6ca5d8f1adb42c94670be1125435387ea8b9f3f20b4505337b2adc090a4b5714",
|
||||
"c43b969848df947bc8e13d1777a08282cd45386867991786fba7f7ffe5027b47"
|
||||
"c43b969848df947bc8e13d1777a08282cd45386867991786fba7f7ffe5027b47",
|
||||
"d8f405fce4efc179dea6661d54b25b700b95eef996a93d1f2b4507d022e8ee8f"
|
||||
],
|
||||
"producer_fingerprints": [
|
||||
"7ccc7af8b1102056372e6450bf3ee6f9067aa984e3e655fd5061d16eec327097",
|
||||
@@ -2023,7 +2039,7 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"fact_count": 94,
|
||||
"fact_count": 95,
|
||||
"invalid_consumer_count": 0,
|
||||
"invalid_producer_count": 0,
|
||||
"producer_call_count": 76,
|
||||
@@ -2940,7 +2956,7 @@
|
||||
"receiver_kind": "canonical_singleton"
|
||||
}
|
||||
],
|
||||
"static_consumer_count": 17,
|
||||
"static_consumer_count": 18,
|
||||
"static_producer_call_count": 74
|
||||
},
|
||||
"event_specs": {
|
||||
|
||||
@@ -100,6 +100,24 @@
|
||||
"owner": "app.chain.site",
|
||||
"reason": "站点更新后由 SiteChain 清理已经失效的站点数据。"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.site",
|
||||
"qualname": "SiteChain",
|
||||
"method": "register",
|
||||
"receiver_kind": "canonical_singleton",
|
||||
"events": [
|
||||
"EventType.SiteUpdated"
|
||||
],
|
||||
"dynamic": false,
|
||||
"invalid": false,
|
||||
"handler": "SiteChain.complete_site_rss",
|
||||
"registration_kind": "decorator",
|
||||
"priority": "<default>",
|
||||
"fingerprint": "d8f405fce4efc179dea6661d54b25b700b95eef996a93d1f2b4507d022e8ee8f",
|
||||
"classification": "approved_static_registration",
|
||||
"owner": "app.chain.site",
|
||||
"reason": "站点变更提交后由 SiteChain 调用共享 RSS 用例补全缺失地址,用例保留手工配置并在短事务外执行网络验证。"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.site",
|
||||
"qualname": "SiteChain",
|
||||
|
||||
@@ -457,13 +457,13 @@ def test_event_contract_baseline_covers_every_public_event_enum() -> None:
|
||||
assert events["dynamic_producer_count"] == 2
|
||||
assert events["invalid_producer_count"] == 0
|
||||
assert events["producer_event_reference_count"] == 76
|
||||
assert events["consumer_registration_count"] == 18
|
||||
assert events["static_consumer_count"] == 17
|
||||
assert events["consumer_registration_count"] == 19
|
||||
assert events["static_consumer_count"] == 18
|
||||
assert events["dynamic_consumer_count"] == 1
|
||||
assert events["invalid_consumer_count"] == 0
|
||||
assert events["consumer_event_reference_count"] == 17
|
||||
assert events["fact_count"] == 94
|
||||
assert len({fact["fingerprint"] for fact in events["consumers"]}) == 18
|
||||
assert events["consumer_event_reference_count"] == 18
|
||||
assert events["fact_count"] == 95
|
||||
assert len({fact["fingerprint"] for fact in events["consumers"]}) == 19
|
||||
assert all(
|
||||
not fact["caller"].startswith("app.plugins")
|
||||
for fact in (*events["producers"], *events["consumers"])
|
||||
|
||||
@@ -1221,7 +1221,7 @@ def publish(kind):
|
||||
|
||||
def test_collect_event_facts_matches_current_host_inventory() -> None:
|
||||
"""
|
||||
统一事实覆盖当前 76 个 producer 调用与 18 个 consumer 调用。
|
||||
统一事实覆盖当前 76 个 producer 调用与 19 个 consumer 调用。
|
||||
"""
|
||||
facts = current_event_facts()
|
||||
producers = facts["producers"]
|
||||
@@ -1232,10 +1232,10 @@ def test_collect_event_facts_matches_current_host_inventory() -> None:
|
||||
assert sum(fact["dynamic"] for fact in producers) == 2
|
||||
assert sum(fact["invalid"] for fact in producers) == 0
|
||||
assert sum(len(fact["events"]) for fact in producers) == 76
|
||||
assert len(consumers) == 18
|
||||
assert sum(not fact["dynamic"] and not fact["invalid"] for fact in consumers) == 17
|
||||
assert len(consumers) == 19
|
||||
assert sum(not fact["dynamic"] and not fact["invalid"] for fact in consumers) == 18
|
||||
assert sum(fact["dynamic"] for fact in consumers) == 1
|
||||
assert sum(fact["invalid"] for fact in consumers) == 0
|
||||
assert sum(len(fact["events"]) for fact in consumers) == 17
|
||||
assert sum(len(fact["events"]) for fact in consumers) == 18
|
||||
consumer_fingerprints = [fact["fingerprint"] for fact in consumers]
|
||||
assert len(consumer_fingerprints) == len(set(consumer_fingerprints))
|
||||
|
||||
@@ -124,7 +124,7 @@ def test_event_policy_accepts_exact_static_and_dynamic_facts() -> None:
|
||||
|
||||
def test_current_event_consumer_policy_matches_exact_reviewed_set() -> None:
|
||||
"""
|
||||
当前 18 条宿主 consumer 必须逐条匹配人工政策且没有非法成员。
|
||||
当前 19 条宿主 consumer 必须逐条匹配人工政策且没有非法成员。
|
||||
"""
|
||||
facts = current_event_facts()["consumers"]
|
||||
policy = json.loads(DEFAULT_EVENT_POLICY_PATH.read_text(encoding="utf-8"))
|
||||
@@ -133,17 +133,17 @@ def test_current_event_consumer_policy_matches_exact_reviewed_set() -> None:
|
||||
result = check_event_consumer_policy(facts)
|
||||
|
||||
assert result.ok
|
||||
assert result.actual_count == result.reviewed_count == 18
|
||||
assert result.static_count == 17
|
||||
assert result.actual_count == result.reviewed_count == 19
|
||||
assert result.static_count == 18
|
||||
assert result.dynamic_count == 1
|
||||
assert result.invalid_count == 0
|
||||
assert len({fact["fingerprint"] for fact in facts}) == 18
|
||||
assert len({fact["fingerprint"] for fact in facts}) == 19
|
||||
assert {entry["fingerprint"] for entry in entries} == {
|
||||
fact["fingerprint"] for fact in facts
|
||||
}
|
||||
assert sum(
|
||||
entry["classification"] == STATIC_CLASSIFICATION for entry in entries
|
||||
) == 17
|
||||
) == 18
|
||||
dynamic_entries = [
|
||||
entry
|
||||
for entry in entries
|
||||
|
||||
618
tests/test_rss_recovery.py
Normal file
618
tests/test_rss_recovery.py
Normal file
@@ -0,0 +1,618 @@
|
||||
"""
|
||||
站点 RSS 补全、续期验证、并发保护和失败退避的离线回归。
|
||||
"""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import replace
|
||||
from threading import Event as ThreadEvent
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
from urllib.parse import parse_qsl, urlsplit
|
||||
|
||||
import pytest
|
||||
from requests import Response
|
||||
|
||||
from app.application import rss as rss_module
|
||||
from app.application.rss import RssHelper, ensure_site_rss
|
||||
from app.application.site.contract import SiteRepository, SiteSnapshot, SiteWriteResult
|
||||
from app.chain import site as site_module
|
||||
from app.chain import torrents as torrents_module
|
||||
from app.chain.site import SiteChain
|
||||
from app.chain.torrents import TorrentsChain
|
||||
from app.domain import site as site_rules
|
||||
from app.modules.indexer.rss import get_rss_recipe, is_rss_expired
|
||||
|
||||
OLD_URL = "https://rss.example/rss?passkey=FAKEOLD&cat=1"
|
||||
NEW_URL = "https://rss.example/rss?passkey=FAKENEW&cat=all"
|
||||
|
||||
|
||||
def _site(**changes) -> SiteSnapshot:
|
||||
"""
|
||||
构造已保存且启用的私有站点,所有凭据均为虚构文本。
|
||||
"""
|
||||
values = dict(id=9001, name="离线RSS", domain="rss.example", url="https://rss.example/",
|
||||
rss=OLD_URL, cookie="FAKECOOKIE", ua="RSS-Test", is_active=True, public=False)
|
||||
return SiteSnapshot(**(values | changes))
|
||||
|
||||
|
||||
def _storage(site: SiteSnapshot) -> SimpleNamespace:
|
||||
"""
|
||||
隔离仓储边界,保留配置快照比较和提交后读取的真实调用顺序。
|
||||
"""
|
||||
current = [site]
|
||||
repository = Mock(spec=SiteRepository)
|
||||
repository.get_by_domain.side_effect = lambda _domain: current[0]
|
||||
|
||||
def save(expected, url):
|
||||
"""
|
||||
模拟单条带条件更新;生产 SQL 的原子行为另由真实数据库测试覆盖。
|
||||
"""
|
||||
if current[0] != expected:
|
||||
return SiteWriteResult(False, "站点配置已变化")
|
||||
current[0] = replace(expected, rss=url)
|
||||
return SiteWriteResult(True)
|
||||
|
||||
repository.update_rss_if_unchanged.side_effect = save
|
||||
helper = Mock(spec=RssHelper)
|
||||
helper.get_rss_link.return_value = (NEW_URL, "")
|
||||
helper.parse.return_value = [{"title": "Offline torrent", "enclosure": "https://rss.example/dl/1"}]
|
||||
return SimpleNamespace(current=current, repository=repository, helper=helper)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def recovery(monkeypatch):
|
||||
"""
|
||||
每个用例拥有独立退避状态和虚拟时钟,不污染宿主共享配置。
|
||||
"""
|
||||
clock = SimpleNamespace(now=0.0)
|
||||
owner = rss_module._RssLinkRecovery(clock=lambda: clock.now)
|
||||
monkeypatch.setattr(rss_module, "_rss_link_recovery", owner)
|
||||
return SimpleNamespace(clock=clock, owner=owner)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rss_access(monkeypatch):
|
||||
"""
|
||||
保留真实 RSS 解析和配方,替换 HTTP、浏览器及可选原生解析出口。
|
||||
"""
|
||||
http = Mock(spec=rss_module.RssHttpPort)
|
||||
http.decode_xml.side_effect = lambda response, **_kwargs: response.text
|
||||
parser = Mock(spec=rss_module.RssParserPort)
|
||||
parser.parse.return_value = None
|
||||
monkeypatch.setattr(rss_module, "_rss_http_port", http)
|
||||
monkeypatch.setattr(rss_module, "_rss_browser_port", Mock(spec=rss_module.RssBrowserPort))
|
||||
monkeypatch.setattr(rss_module, "_rss_parser_port", parser)
|
||||
monkeypatch.setattr(rss_module, "_rss_site_port", SimpleNamespace(
|
||||
get_site_rss_recipe=get_rss_recipe, is_site_rss_expired=is_rss_expired,
|
||||
))
|
||||
return http
|
||||
|
||||
|
||||
def _response(status: int, text: str) -> Response:
|
||||
"""
|
||||
使用真实 requests 响应的真假语义回放 HTTP 错误,不发起网络请求。
|
||||
"""
|
||||
response = Response()
|
||||
response.status_code = status
|
||||
response.encoding = "utf-8"
|
||||
response._content = text.encode("utf-8")
|
||||
return response
|
||||
|
||||
|
||||
@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")]),
|
||||
("cat=1&passkey=OLD", "passkey=NEW-TAIL_1%2B2%2F3%3D", [("cat", "1"), ("passkey", "NEW-TAIL_1+2/3=")]),
|
||||
("cat=1&cat=2&search=&passkey=OLD", "cat=all&passkey=NEW&rows=50",
|
||||
[("cat", "1"), ("cat", "2"), ("search", ""), ("passkey", "NEW"), ("rows", "50")]),
|
||||
("par=OLD&cat=1", "par=NEW-opaque", [("cat", "1"), ("par", "NEW-opaque")]),
|
||||
("uid=1&passkey=OLD&cat=1", "uid=2&passkey=NEW", [("cat", "1"), ("uid", "2"), ("passkey", "NEW")]),
|
||||
("passkey=OLD&signature=OLD&expires=1", "passkey=NEW&signature=NEW&expires=2",
|
||||
[("passkey", "NEW"), ("signature", "NEW"), ("expires", "2")]),
|
||||
("passkey=OLD&t=movie&exp=90", "passkey=NEW", [("t", "movie"), ("exp", "90"), ("passkey", "NEW")]),
|
||||
])
|
||||
def test_renew_preserves_filters_and_whole_credentials(old_query, new_query, expected):
|
||||
"""
|
||||
更新完整认证值,保留重复分类、空筛选与未被生成页更新的有效期配置。
|
||||
"""
|
||||
result = site_rules.renew_rss_link(f"https://rss.example/rss?{old_query}", f"https://rss.example/rss?{new_query}")
|
||||
assert parse_qsl(urlsplit(result).query, keep_blank_values=True) == expected
|
||||
|
||||
|
||||
def test_renew_accepts_new_domain_and_path_without_losing_filters():
|
||||
"""
|
||||
站点迁移域名、协议或票据路径后采用新入口,同时保留可表达的筛选参数。
|
||||
"""
|
||||
result = site_rules.renew_rss_link(OLD_URL, "https://new.example/feed/FAKENEW?passkey=NEW")
|
||||
assert result == "https://new.example/feed/FAKENEW?cat=1&passkey=NEW"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status,body", [
|
||||
(200, "RSS Link has expired, You need to get a new one!"),
|
||||
(403, "RSS Link has expired, You need to get a new one!"),
|
||||
(401, "RSS 链接已过期,您需要获得一个新的!"),
|
||||
(200, "<html><head><title>Error</title></head><body><p>RSS Link has expired,<br>You need to get a new one!</p></body></html>"),
|
||||
(200, "RSS Link has expired,\nYou need to get a new one!"),
|
||||
(200, " rss link has expired, you need to get new! "),
|
||||
])
|
||||
def test_explicit_expiration_survives_http_and_html_forms(rss_access, status, body):
|
||||
"""
|
||||
完整过期提示的状态码、HTML 包装、换行和标点变化不会漏掉续期。
|
||||
"""
|
||||
rss_access.get.return_value = _response(status, body)
|
||||
assert RssHelper().parse(OLD_URL) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status,body", [
|
||||
(429, "Too many requests"), (503, "RSS is temporarily unavailable"),
|
||||
(200, "<html><body>Please log in</body></html>"),
|
||||
(200, "<error>Invalid passkey</error>"),
|
||||
])
|
||||
def test_transient_errors_and_login_pages_do_not_trigger_renewal(rss_access, status, body):
|
||||
"""
|
||||
普通错误和登录页面不是凭据过期,也不能伪装成一个合法空订阅。
|
||||
"""
|
||||
rss_access.get.return_value = _response(status, body)
|
||||
assert RssHelper().parse(OLD_URL) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [
|
||||
"<rss><channel /></rss>",
|
||||
'<?xml version="1.0"?><feed xmlns="http://www.w3.org/2005/Atom" />',
|
||||
'<!-- 前置说明 --><rss><channel><title>RSS Link has expired, You need to get a new one!</title></channel></rss>',
|
||||
])
|
||||
def test_real_empty_feed_is_success_even_with_expiration_text(rss_access, body):
|
||||
"""
|
||||
合法空订阅正常返回空列表,标题或内容提到过期也不会误触发续期。
|
||||
"""
|
||||
rss_access.get.return_value = _response(200, body)
|
||||
assert RssHelper().parse(OLD_URL) == []
|
||||
|
||||
|
||||
def test_oversized_rss_is_rejected_before_document_parsing(rss_access, monkeypatch):
|
||||
"""
|
||||
超过大小限制的响应在 XML 和原生解析前失败,避免新增校验绕过原有内存保护。
|
||||
"""
|
||||
monkeypatch.setattr(RssHelper, "MAX_RSS_SIZE", 8)
|
||||
rss_access.get.return_value = _response(200, "<rss><channel /></rss>")
|
||||
assert RssHelper().parse(OLD_URL) is False
|
||||
rss_access.decode_xml.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("href,expected", [
|
||||
("https://rss.example/rss?passkey=FAKE", "https://rss.example/rss?passkey=FAKE"),
|
||||
("/rss?passkey=FAKE", "https://rss.example/rss?passkey=FAKE"),
|
||||
("javascript:void(0)", ""), ("#", ""), ("ftp://rss.example/feed", ""), ("http://[bad/rss", ""),
|
||||
])
|
||||
def test_generated_links_are_normalized_and_validated(rss_access, href, expected):
|
||||
"""
|
||||
相对链接会补全,脚本、空锚点和非 HTTP 地址不会作为成功结果保存。
|
||||
"""
|
||||
rss_access.post.return_value = _response(200, f'<a class="faqlink" href="{href}">RSS</a>')
|
||||
link, message = RssHelper().get_rss_link("https://rss.example/", "FAKECOOKIE", "audit")
|
||||
assert link == expected
|
||||
assert bool(message) is not bool(expected)
|
||||
|
||||
|
||||
def test_broad_link_selector_ignores_navigation_after_feed(rss_access):
|
||||
"""
|
||||
专站宽选择器中 RSS 后面出现退出链接时仍选择订阅地址。
|
||||
"""
|
||||
rss_access.post.return_value = _response(200, '<a href="/rss?token=FAKE">RSS</a><a href="/logout">退出</a>')
|
||||
assert RssHelper().get_rss_link("https://monikadesign.uk/", "FAKECOOKIE", "audit")[0] == "https://monikadesign.uk/rss?token=FAKE"
|
||||
|
||||
|
||||
def test_generation_exception_redacts_cookie_and_query_credentials(rss_access):
|
||||
"""
|
||||
生成页传输异常即使含原 Cookie 和链接凭据,对外提示也必须脱敏。
|
||||
"""
|
||||
rss_access.post.side_effect = RuntimeError("FAKECOOKIE /rss?par=FAKESECRET&signature=FAKESIGN")
|
||||
link, message = RssHelper().get_rss_link("https://rss.example/", "FAKECOOKIE", "audit")
|
||||
assert not link
|
||||
assert all(secret not in message for secret in ("FAKECOOKIE", "FAKESECRET", "FAKESIGN"))
|
||||
|
||||
|
||||
def test_generation_respects_browser_configuration_and_timeout(rss_access):
|
||||
"""
|
||||
启用渲染时通过已注入的浏览器入口生成,并沿用站点 Cookie、UA 和超时。
|
||||
"""
|
||||
browser = rss_module._rss_browser_port
|
||||
browser.render.return_value = '<a class="faqlink" href="/rss?passkey=FAKE">RSS</a>'
|
||||
link, _message = RssHelper().get_rss_link("https://rss.example/", "FAKECOOKIE", "audit", timeout=27, render=True)
|
||||
assert link == "https://rss.example/rss?passkey=FAKE"
|
||||
assert browser.render.call_args.kwargs == dict(url="https://rss.example/getrss.php", cookie="FAKECOOKIE",
|
||||
ua="audit", proxies=None, timeout=27)
|
||||
rss_access.post.assert_not_called()
|
||||
|
||||
|
||||
def test_recovery_validates_before_save_and_returns_same_round_items(recovery):
|
||||
"""
|
||||
续期先验证实际订阅,保存后把同一份资源交给本轮,不再重复抓取。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
sequence = []
|
||||
storage.helper.parse.side_effect = lambda *_args, **_kwargs: sequence.append("validate") or []
|
||||
save = storage.repository.update_rss_if_unchanged.side_effect
|
||||
|
||||
def observed_save(*args):
|
||||
"""
|
||||
记录验证与保存的顺序,并执行配置比较。
|
||||
"""
|
||||
sequence.append("save")
|
||||
return save(*args)
|
||||
|
||||
storage.repository.update_rss_if_unchanged.side_effect = observed_save
|
||||
result = ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
assert result.url == "https://rss.example/rss?cat=1&passkey=FAKENEW"
|
||||
assert result.items == []
|
||||
assert sequence == ["validate", "save"]
|
||||
assert storage.current[0].rss == result.url
|
||||
storage.helper.parse.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_result", [None, False])
|
||||
def test_invalid_new_feed_keeps_old_configuration(recovery, invalid_result):
|
||||
"""
|
||||
新地址仍过期或抓取失败时不覆盖原地址,返回一次续期失败通知。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
storage.helper.parse.return_value = invalid_result
|
||||
result = ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
assert result.url is None and result.notify
|
||||
assert storage.current[0].rss == OLD_URL
|
||||
storage.repository.update_rss_if_unchanged.assert_not_called()
|
||||
|
||||
|
||||
def test_failed_write_is_reported_and_enters_backoff(recovery):
|
||||
"""
|
||||
仓储拒绝保存时按失败处理,不能假装更新成功或在下一调用立即重发请求。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
storage.repository.update_rss_if_unchanged.side_effect = None
|
||||
storage.repository.update_rss_if_unchanged.return_value = SiteWriteResult(False, "保存失败")
|
||||
first = ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
second = ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
assert first.url is None and first.notify and first.message == "保存失败"
|
||||
assert not second.notify
|
||||
storage.helper.get_rss_link.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stage", ["generate", "save"])
|
||||
def test_recovery_exception_releases_admission_without_leaking_credentials(recovery, stage):
|
||||
"""
|
||||
请求或提交异常只报告异常类型,保留旧地址、释放准入,并允许退避后重试。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
boundary = storage.helper.get_rss_link if stage == "generate" else storage.repository.update_rss_if_unchanged
|
||||
successful = boundary.side_effect
|
||||
boundary.side_effect = RuntimeError("FAKECOOKIE https://rss.example/rss?passkey=FAKEOLD")
|
||||
failed = ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
assert failed.url is None and failed.notify
|
||||
assert "FAKECOOKIE" not in failed.message and "FAKEOLD" not in failed.message
|
||||
assert storage.current[0].rss == OLD_URL
|
||||
assert not recovery.owner._inflight
|
||||
|
||||
boundary.side_effect = successful
|
||||
recovery.clock.now = 300
|
||||
assert ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper).url
|
||||
|
||||
|
||||
@pytest.mark.parametrize("snapshot", [None, RuntimeError("FAKECOOKIE")])
|
||||
def test_missing_or_unreadable_site_does_not_generate(recovery, snapshot):
|
||||
"""
|
||||
站点已删除或读取失败时不使用索引缓存里的旧凭据生成订阅。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
if isinstance(snapshot, Exception):
|
||||
storage.repository.get_by_domain.side_effect = snapshot
|
||||
else:
|
||||
storage.current[0] = snapshot
|
||||
result = ensure_site_rss("rss.example", storage.repository, helper=storage.helper)
|
||||
assert result.url is None and "FAKECOOKIE" not in result.message
|
||||
storage.helper.get_rss_link.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changed", [None, _site(cookie="FAKENEWCOOKIE"), _site(rss=NEW_URL)])
|
||||
def test_site_changed_before_generation_uses_current_configuration(recovery, changed):
|
||||
"""
|
||||
获取准入前另一任务完成修改或删除时,不继续使用原快照发起生成请求。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
storage.repository.get_by_domain.side_effect = [storage.current[0], changed]
|
||||
result = ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
assert result.url == (NEW_URL if changed is not None and changed.rss == NEW_URL else None)
|
||||
assert not recovery.owner._inflight
|
||||
storage.helper.get_rss_link.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [dict(rss="invalid"), dict(rss=None, cookie=None)])
|
||||
def test_invalid_manual_address_or_missing_cookie_keeps_configuration(recovery, changes):
|
||||
"""
|
||||
手工无效地址和缺少 Cookie 都保留原配置,给出修正提示而不请求生成页。
|
||||
"""
|
||||
storage = _storage(_site(**changes))
|
||||
result = ensure_site_rss("rss.example", storage.repository, helper=storage.helper)
|
||||
assert result.url is None and result.message
|
||||
storage.repository.update_rss_if_unchanged.assert_not_called()
|
||||
storage.helper.get_rss_link.assert_not_called()
|
||||
|
||||
|
||||
def test_generator_returning_expired_address_is_not_retried_recursively(recovery):
|
||||
"""
|
||||
生成页仍返回完全相同的过期地址时直接报告失败,不循环验证或写回旧地址。
|
||||
"""
|
||||
unchanged = "https://rss.example/rss?passkey=FAKENEW"
|
||||
storage = _storage(_site(rss=unchanged))
|
||||
storage.helper.get_rss_link.return_value = (unchanged, "")
|
||||
result = ensure_site_rss("rss.example", storage.repository, expired_url=unchanged, helper=storage.helper)
|
||||
assert result.url is None and result.notify
|
||||
storage.helper.parse.assert_not_called()
|
||||
storage.repository.update_rss_if_unchanged.assert_not_called()
|
||||
|
||||
|
||||
def test_retry_backoff_and_daily_notification_deduplication(recovery):
|
||||
"""
|
||||
用虚拟时钟验证五分钟、十分钟退避及同配置每天最多一次过期通知。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
storage.helper.get_rss_link.return_value = ("", "生成页不可用")
|
||||
|
||||
def run():
|
||||
"""
|
||||
通过公共入口触发同一配置的过期恢复。
|
||||
"""
|
||||
return ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
|
||||
assert run().notify
|
||||
recovery.clock.now = 299
|
||||
assert not run().notify
|
||||
assert storage.helper.get_rss_link.call_count == 1
|
||||
recovery.clock.now = 300
|
||||
assert not run().notify
|
||||
assert storage.helper.get_rss_link.call_count == 2
|
||||
recovery.clock.now = 899
|
||||
assert not run().notify
|
||||
assert storage.helper.get_rss_link.call_count == 2
|
||||
recovery.clock.now = 900
|
||||
assert not run().notify
|
||||
assert storage.helper.get_rss_link.call_count == 3
|
||||
recovery.clock.now = 24 * 3600
|
||||
assert run().notify
|
||||
assert storage.helper.get_rss_link.call_count == 4
|
||||
assert "FAKECOOKIE" not in repr(recovery.owner._states)
|
||||
assert "FAKEOLD" not in repr(recovery.owner._states)
|
||||
|
||||
|
||||
def test_changed_credentials_bypass_old_failure_backoff(recovery):
|
||||
"""
|
||||
修正 Cookie 后无需等待旧配置的退避,生成请求必须使用新凭据。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
storage.helper.get_rss_link.return_value = ("", "旧凭据不可用")
|
||||
ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
storage.current[0] = replace(storage.current[0], cookie="FAKE-NEW-COOKIE")
|
||||
storage.helper.get_rss_link.return_value = (NEW_URL, "")
|
||||
assert ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper).url
|
||||
assert storage.helper.get_rss_link.call_count == 2
|
||||
assert storage.helper.get_rss_link.call_args.kwargs["cookie"] == "FAKE-NEW-COOKIE"
|
||||
|
||||
|
||||
def test_concurrent_recovery_is_coalesced_without_holding_io_lock(recovery):
|
||||
"""
|
||||
同站点并发请求只生成一次;另一站点能够在首站网络阻塞时完成。
|
||||
"""
|
||||
first = _storage(_site())
|
||||
other = _storage(_site(id=9002, domain="other.example", rss=None))
|
||||
entered, release = ThreadEvent(), ThreadEvent()
|
||||
|
||||
def generate(**_kwargs):
|
||||
"""
|
||||
暂停第一个站点的生成请求,让并发准入可确定性地被观察。
|
||||
"""
|
||||
entered.set()
|
||||
assert release.wait(5)
|
||||
return NEW_URL, ""
|
||||
|
||||
first.helper.get_rss_link.side_effect = generate
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
pending = executor.submit(ensure_site_rss, "rss.example", first.repository,
|
||||
expired_url=OLD_URL, helper=first.helper)
|
||||
try:
|
||||
assert entered.wait(5)
|
||||
deferred = ensure_site_rss("rss.example", first.repository, expired_url=OLD_URL, helper=first.helper)
|
||||
assert deferred.url is None and not deferred.notify
|
||||
assert ensure_site_rss("other.example", other.repository, helper=other.helper).url
|
||||
first.helper.get_rss_link.assert_called_once()
|
||||
finally:
|
||||
release.set()
|
||||
assert pending.result(timeout=5).url
|
||||
assert not recovery.owner._inflight
|
||||
|
||||
|
||||
def test_concurrent_manual_change_is_not_overwritten(recovery):
|
||||
"""
|
||||
网络请求期间用户改写 RSS 时,旧生成结果不能覆盖新配置。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
manual_url = "https://rss.example/rss?passkey=FAKEMANUAL&cat=3"
|
||||
|
||||
def parse_and_edit(*_args, **_kwargs):
|
||||
"""
|
||||
在验证响应到达时提交手工修改,模拟真实请求期间的配置竞争。
|
||||
"""
|
||||
storage.current[0] = replace(storage.current[0], rss=manual_url)
|
||||
return []
|
||||
|
||||
storage.helper.parse.side_effect = parse_and_edit
|
||||
result = ensure_site_rss("rss.example", storage.repository, expired_url=OLD_URL, helper=storage.helper)
|
||||
assert result.url is None
|
||||
assert storage.current[0].rss == manual_url
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes", [dict(public=True, rss=None), dict(is_active=False, rss=None)])
|
||||
def test_public_or_disabled_site_does_not_generate(recovery, changes):
|
||||
"""
|
||||
公开或停用站点不发起需要私有 Cookie 的 RSS 自动生成。
|
||||
"""
|
||||
storage = _storage(_site(**changes))
|
||||
assert ensure_site_rss("rss.example", storage.repository, helper=storage.helper).url is None
|
||||
storage.helper.get_rss_link.assert_not_called()
|
||||
|
||||
|
||||
def _chain(storage, monkeypatch) -> TorrentsChain:
|
||||
"""
|
||||
保留真实种子链与共享用例,只替换站点资源和 HTTP 解析边界。
|
||||
"""
|
||||
chain = object.__new__(TorrentsChain)
|
||||
chain.site_repository = storage.repository
|
||||
chain.runtime_config = SimpleNamespace(user_agent="audit", site_url="http://localhost/")
|
||||
chain.post_message = Mock()
|
||||
snapshot = storage.current[0]
|
||||
indexer = dict(id=snapshot.id, domain=snapshot.domain, url=snapshot.url, rss=snapshot.rss,
|
||||
name=snapshot.name, cookie=snapshot.cookie, ua=snapshot.ua)
|
||||
monkeypatch.setattr(torrents_module, "SitesHelper", lambda: SimpleNamespace(get_indexer=lambda _domain: indexer))
|
||||
monkeypatch.setattr(RssHelper, "get_rss_link", storage.helper.get_rss_link)
|
||||
monkeypatch.setattr(RssHelper, "parse", storage.helper.parse)
|
||||
return chain
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", [False, True])
|
||||
def test_torrents_recovers_and_matches_in_current_round(recovery, monkeypatch, missing):
|
||||
"""
|
||||
空地址或明确过期都在本轮返回资源,验证抓取不会被重复执行。
|
||||
"""
|
||||
storage = _storage(_site(rss=None if missing else OLD_URL))
|
||||
items = [{"title": "Offline torrent", "enclosure": "https://rss.example/dl/1"}]
|
||||
storage.helper.parse.side_effect = [items] if missing else [None, items]
|
||||
chain = _chain(storage, monkeypatch)
|
||||
result = chain.rss("rss.example")
|
||||
assert len(result) == 1 and result[0].title == "Offline torrent"
|
||||
assert storage.helper.parse.call_count == (1 if missing else 2)
|
||||
chain.post_message.assert_not_called()
|
||||
|
||||
|
||||
def test_torrents_only_notifies_once_for_repeated_failure(recovery, monkeypatch):
|
||||
"""
|
||||
订阅层多次遇到同一过期地址时只通知一次,不绕过用例退避反复生成。
|
||||
"""
|
||||
storage = _storage(_site())
|
||||
storage.helper.parse.return_value = None
|
||||
storage.helper.get_rss_link.return_value = ("", "无法生成")
|
||||
chain = _chain(storage, monkeypatch)
|
||||
assert chain.rss("rss.example") == []
|
||||
assert chain.rss("rss.example") == []
|
||||
chain.post_message.assert_called_once()
|
||||
storage.helper.get_rss_link.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reachable", [False, True])
|
||||
def test_cookiecloud_completes_missing_rss_in_same_sync(recovery, monkeypatch, reachable):
|
||||
"""
|
||||
已有有效 Cookie 或本轮刚更新 Cookie,都在本轮补齐缺失 RSS。
|
||||
"""
|
||||
storage = _storage(_site(rss=None))
|
||||
chain = object.__new__(SiteChain)
|
||||
chain.site_repository = storage.repository
|
||||
chain.runtime_config = SimpleNamespace(user_agent="audit")
|
||||
monkeypatch.setattr(chain, "test", Mock(return_value=(reachable, "")))
|
||||
|
||||
def update_cookie(**kwargs):
|
||||
"""
|
||||
模拟 Cookie 提交后才对 RSS 用例开放新凭据。
|
||||
"""
|
||||
storage.current[0] = replace(storage.current[0], cookie=kwargs["cookies"])
|
||||
return SiteWriteResult(True)
|
||||
|
||||
storage.repository.update_cookie.side_effect = update_cookie
|
||||
chain._sync_cookiecloud_domain(domain="rss.example", cookie="FAKE-NEW", indexer={},
|
||||
site_info=storage.current[0], repository=storage.repository, rsshelper=storage.helper)
|
||||
assert storage.current[0].rss
|
||||
assert storage.helper.get_rss_link.call_args.kwargs["cookie"] == ("FAKECOOKIE" if reachable else "FAKE-NEW")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved", [True, False])
|
||||
def test_cookiecloud_new_site_generates_only_after_successful_save(recovery, monkeypatch, saved):
|
||||
"""
|
||||
CookieCloud 新增站点先提交 Cookie 再生成 RSS,新增失败时不发起无归属的生成请求。
|
||||
"""
|
||||
storage = _storage(_site(rss=None))
|
||||
storage.current[0] = None
|
||||
chain = object.__new__(SiteChain)
|
||||
chain.runtime_config = SimpleNamespace(cookiecloud_blacklist="", user_agent="audit")
|
||||
monkeypatch.setattr(chain, "_cookiecloud_connect", lambda *_args: (
|
||||
False, _response(200, '<html><body><a href="logout.php">退出</a></body></html>'),
|
||||
))
|
||||
|
||||
def create(mutation):
|
||||
"""
|
||||
模拟站点创建事务,提交后才允许独立仓储读取快照。
|
||||
"""
|
||||
assert mutation.values["rss"] is None
|
||||
storage.current[0] = _site(**mutation.to_payload()) if saved else None
|
||||
return SiteWriteResult(saved, "" if saved else "保存失败")
|
||||
|
||||
storage.repository.add.side_effect = create
|
||||
result = chain._sync_cookiecloud_domain(
|
||||
domain="rss.example", cookie="FAKE-NEW", indexer={"domain": "https://rss.example/", "name": "离线RSS"},
|
||||
site_info=None, repository=storage.repository, rsshelper=storage.helper,
|
||||
)
|
||||
assert result == ((0, 1, 0, True) if saved else (0, 0, 1, False))
|
||||
if saved:
|
||||
assert storage.current[0].rss
|
||||
assert storage.helper.get_rss_link.call_args.kwargs["cookie"] == "FAKE-NEW"
|
||||
else:
|
||||
storage.helper.get_rss_link.assert_not_called()
|
||||
|
||||
|
||||
def test_site_updated_completes_missing_but_preserves_manual_rss(recovery, monkeypatch):
|
||||
"""
|
||||
手工维护提交后的事件补全空地址,重复事件不改写已经有效的手工地址。
|
||||
"""
|
||||
storage = _storage(_site(rss=None))
|
||||
chain = object.__new__(SiteChain)
|
||||
chain.site_repository = storage.repository
|
||||
monkeypatch.setattr(RssHelper, "get_rss_link", storage.helper.get_rss_link)
|
||||
monkeypatch.setattr(RssHelper, "parse", storage.helper.parse)
|
||||
event = SimpleNamespace(event_data={"domain": "rss.example"})
|
||||
chain.complete_site_rss(event)
|
||||
generated_url = storage.current[0].rss
|
||||
assert generated_url
|
||||
storage.current[0] = replace(storage.current[0], rss=OLD_URL)
|
||||
chain.complete_site_rss(event)
|
||||
assert storage.current[0].rss == OLD_URL
|
||||
storage.helper.get_rss_link.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved", [True, False])
|
||||
def test_cookie_login_completes_rss_after_new_cookie_commit(recovery, monkeypatch, saved):
|
||||
"""
|
||||
用户名密码登录拿到 Cookie 后,同一请求补全 RSS,并使用已提交的新 Cookie。
|
||||
"""
|
||||
storage = _storage(_site(rss=None))
|
||||
chain = object.__new__(SiteChain)
|
||||
chain.site_repository = storage.repository
|
||||
chain.runtime_config = SimpleNamespace(proxy_server=None)
|
||||
login = Mock()
|
||||
login.get_site_cookie_ua.return_value = ("FAKE-LOGIN", "New UA", "登录成功")
|
||||
monkeypatch.setattr(site_module, "CookieHelper", lambda: login)
|
||||
monkeypatch.setattr(RssHelper, "get_rss_link", storage.helper.get_rss_link)
|
||||
monkeypatch.setattr(RssHelper, "parse", storage.helper.parse)
|
||||
|
||||
def commit_cookie(_site_id, mutation):
|
||||
"""
|
||||
先保存 Cookie,再返回提交后的快照。
|
||||
"""
|
||||
if not saved:
|
||||
return None
|
||||
storage.current[0] = replace(storage.current[0], **mutation.to_payload())
|
||||
return storage.current[0]
|
||||
|
||||
storage.repository.update.side_effect = commit_cookie
|
||||
assert chain.update_cookie(storage.current[0], "user", "FAKEPASSWORD") == (
|
||||
(True, "登录成功") if saved else (False, "站点已删除,Cookie未保存")
|
||||
)
|
||||
if saved:
|
||||
assert storage.current[0].rss
|
||||
assert storage.helper.get_rss_link.call_args.kwargs["cookie"] == "FAKE-LOGIN"
|
||||
else:
|
||||
storage.helper.get_rss_link.assert_not_called()
|
||||
@@ -20,6 +20,7 @@ from app.db.models.site import Site
|
||||
from app.db.models.siteicon import SiteIcon
|
||||
from app.db.models.sitestatistic import SiteStatistic
|
||||
from app.db.models.siteuserdata import SiteUserData
|
||||
from app.db.oper.site import SiteOper
|
||||
from app.db.session import SessionFactory, async_session_scope
|
||||
from app.db.uow import SqlAlchemyAsyncUnitOfWork
|
||||
|
||||
@@ -222,3 +223,88 @@ async def test_session_repository_leaves_commit_and_rollback_to_caller(db) -> No
|
||||
|
||||
# 本用例已构造非空数据,直接检查或修改其内容以验证快照契约。
|
||||
assert repository.get(snapshot.id).pri == 8 # type: ignore[union-attr]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("previous", [None, "", "https://rss-save.example/rss?passkey=OLD"])
|
||||
def test_rss_compare_update_commits_with_nullable_fields(db, previous) -> None:
|
||||
"""
|
||||
真实 SQL 条件正确匹配空字段,缺失补抓和旧链接续期都在返回成功前提交。
|
||||
"""
|
||||
db.add(Site(name="RSS保存", domain="rss-save.example", url="https://rss-save.example/",
|
||||
rss=previous, cookie="FAKECOOKIE"))
|
||||
repository = _transactional_repository()
|
||||
original = repository.get_by_domain("rss-save.example")
|
||||
assert original is not None
|
||||
assert original.proxy is None and original.token is None
|
||||
|
||||
result = repository.update_rss_if_unchanged(original, "https://rss-save.example/rss?passkey=NEW")
|
||||
|
||||
assert result.success
|
||||
# 另开短会话读取,避免测试被当前 Session 的对象缓存误导。
|
||||
saved = _transactional_repository().get(original.id)
|
||||
assert saved is not None and saved.rss == "https://rss-save.example/rss?passkey=NEW"
|
||||
assert not repository.update_rss_if_unchanged(original, "https://rss-save.example/rss?passkey=STALE").success
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", [
|
||||
{"rss": "https://rss-race.example/manual"}, {"cookie": "FAKENEWCOOKIE"},
|
||||
{"url": "https://new-rss-race.example/"}, {"ua": "New UA"}, {"apikey": "FAKEAPI"},
|
||||
{"token": "FAKETOKEN"}, {"proxy": 1}, {"timeout": 60}, {"render": 1},
|
||||
{"public": 1}, {"is_active": False},
|
||||
])
|
||||
def test_rss_compare_update_rejects_changed_configuration(db, mutation) -> None:
|
||||
"""
|
||||
网络请求期间发生认证、访问配置或手工 RSS 修改时,单条条件更新不能覆盖新配置。
|
||||
"""
|
||||
db.add(Site(name="RSS并发", domain="rss-race.example", url="https://rss-race.example/",
|
||||
rss="https://rss-race.example/rss?passkey=OLD", cookie="FAKECOOKIE"))
|
||||
repository = _transactional_repository()
|
||||
original = repository.get_by_domain("rss-race.example")
|
||||
assert original is not None
|
||||
changed = repository.update(original.id, SiteMutation(mutation))
|
||||
assert changed is not None
|
||||
|
||||
result = repository.update_rss_if_unchanged(original, "https://rss-race.example/rss?passkey=NEW")
|
||||
|
||||
assert not result.success
|
||||
assert repository.get(original.id) == changed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("recreate", [False, True])
|
||||
def test_rss_compare_update_rejects_deleted_or_replaced_site(db, recreate) -> None:
|
||||
"""
|
||||
删除站点或在同域名重建记录后,旧任务不得将新地址写入替代记录。
|
||||
"""
|
||||
record = db.add(Site(name="RSS删除", domain="rss-delete.example", url="https://rss-delete.example/",
|
||||
cookie="FAKECOOKIE"))
|
||||
repository = _transactional_repository()
|
||||
original = repository.get(record.id)
|
||||
assert original is not None
|
||||
db.session.delete(record)
|
||||
db.session.commit()
|
||||
if recreate:
|
||||
db.add(Site(id=original.id + 1, name="RSS重建", domain=original.domain, url=original.url,
|
||||
cookie=original.cookie))
|
||||
|
||||
assert not repository.update_rss_if_unchanged(original, "https://rss-delete.example/rss?passkey=NEW").success
|
||||
current = repository.get_by_domain("rss-delete.example")
|
||||
if recreate:
|
||||
assert current is not None and current.rss is None
|
||||
else:
|
||||
assert current is None
|
||||
|
||||
|
||||
def test_rss_oper_leaves_transaction_to_caller(db) -> None:
|
||||
"""
|
||||
Oper 的条件写入只暂存,调用方回滚后原地址仍可被独立会话读取。
|
||||
"""
|
||||
record = db.add(Site(name="RSS回滚", domain="rss-rollback.example", url="https://rss-rollback.example/"))
|
||||
with SessionFactory() as session:
|
||||
result = SiteOper(db=session).update_rss_if_unchanged(
|
||||
record.id, "https://rss-rollback.example/rss?passkey=NEW", {"rss": None},
|
||||
)
|
||||
assert result[0]
|
||||
session.rollback()
|
||||
|
||||
saved = _transactional_repository().get(record.id)
|
||||
assert saved is not None and saved.rss is None
|
||||
|
||||
@@ -68,6 +68,8 @@ def test_url_matches_trusted_hosts_requires_exact_http_host(url, trusted_hosts,
|
||||
"https://example.com/torrentrss.php?id=1&passkey=<REDACTED>&isdownload=0"),
|
||||
("https://example.com/rss?access_token=SECRET",
|
||||
"https://example.com/rss?access_token=<REDACTED>"),
|
||||
("https://example.com/rss?par=SECRET&signature=SECRET&cat=1",
|
||||
"https://example.com/rss?par=<REDACTED>&signature=<REDACTED>&cat=1"),
|
||||
("https://example.com/rss?X-Plex-Token=SECRET&sort=title",
|
||||
"https://example.com/rss?X-Plex-Token=<REDACTED>&sort=title"),
|
||||
("https://example.com/rss?key=a%2Fb&uid=42&sign=deadbeef",
|
||||
|
||||
Reference in New Issue
Block a user