fix(download): preserve protocol failures and isolate site updates (#7143)

* fix(download): preserve protocol failures and isolate site updates

* test: cover tracker token lifecycle and record dependency facts

---------

Co-authored-by: jxxghp <jxxghp@gmail.com>
This commit is contained in:
Aqr-K
2026-10-23 07:22:22 +08:00
committed by GitHub
parent d666ae9d86
commit 598d1663b1
33 changed files with 1553 additions and 254 deletions

View File

@@ -31,6 +31,7 @@ from app.domain.context import Context, MediaInfo, MusicInfo, SubtitleInfo, Torr
from app.domain.media import is_music_media_source, normalize_music_type
from app.domain.meta.metabase import MetaBase
from app.domain.metainfo import MetaInfo
from app.foundation.url import UrlUtils
from app.schemas.common import ServiceClientInfo as _SchemaServiceClientInfo
from app.schemas.context import MediaInfo as _SchemaMediaInfo
from app.schemas.context import SubtitleInfo as _SchemaSubtitleInfo
@@ -85,7 +86,7 @@ def _prepare_subtitle_download(
return False, "字幕站点信息不存在"
subtitle.enclosure = clean_url
subtitle.site_cookie = site.cookie
subtitle.site_cookie = site.cookie if UrlUtils.same_origin(site.url, clean_url) else None
subtitle.site_ua = site.ua
subtitle.site_proxy = bool(site.proxy)
return True, ""

View File

@@ -454,6 +454,14 @@ class RssHelper:
logger.warning(f"RSS文件过大: {len(raw_data) / 1024 / 1024:.1f}MB,跳过解析")
return False
expired_messages = {
"RSS 链接已过期, 您需要获得一个新的!",
"RSS Link has expired, You need to get a new one!",
"RSS Link has expired, You need to get new!",
}
if ret.text.strip() in expired_messages:
return None
if raw_data:
ret_xml = http_port.decode_xml(
ret,
@@ -601,14 +609,6 @@ class RssHelper:
except Exception as e2:
logger.error(f"解析RSS失败:{str(e2)} - {traceback.format_exc()}")
# RSS过期检查
_rss_expired_msg = [
"RSS 链接已过期, 您需要获得一个新的!",
"RSS Link has expired, You need to get a new one!",
"RSS Link has expired, You need to get new!"
]
if ret_xml in _rss_expired_msg:
return None
return False
finally:
if root is not None:

View File

@@ -22,6 +22,7 @@ from app.application.subscription.contract import (
)
from app.application.subscription.delete import AsyncUnitOfWork
from app.schemas.common import JsonData
from app.schemas.exception import SiteDomainConflictError
from app.schemas.types import SystemConfigKey
SiteMutationResult: TypeAlias = SiteWriteResult
@@ -181,8 +182,12 @@ class SiteMutationCommand:
"public": 1 if site_info.get("public") else 0,
}
)
await self._repository.stage_create(SiteMutation(values))
await self._commit()
try:
await self._repository.stage_create(SiteMutation(values))
await self._commit()
except SiteDomainConflictError:
await self._unit_of_work.rollback()
return SiteMutationResult(False, f"{domain} 站点已存在")
await self._publish_updated({"domain": domain})
return SiteMutationResult(True)
@@ -204,8 +209,12 @@ class SiteMutationCommand:
values["url"] = normalized_url
values["domain"] = normalized_domain
values.pop("id", None)
await self._repository.stage_update(site_id, SiteMutation(values))
await self._commit()
try:
await self._repository.stage_update(site_id, SiteMutation(values))
await self._commit()
except SiteDomainConflictError:
await self._unit_of_work.rollback()
return SiteMutationResult(False, f"{normalized_domain} 站点已存在")
await self._publish_updated(
{
"site_id": site_id,

View File

@@ -9,6 +9,7 @@ from app.domain.media import is_music_media_source, normalize_music_type
from app.domain.meta.metamusic import MetaMusic
from app.domain.metainfo import MetaInfo
from app.foundation.crypto import HashUtils
from app.runtime.cache import async_cache_mutation
from app.schemas.types import MUSIC_ENTITY_RECORDING, MediaSource, MediaType, MusicTargetEntityType
@@ -113,12 +114,24 @@ class TorrentCacheRecognitionService:
)
else:
mediainfo.clear()
target_context.media_info = mediainfo
video_cache, music_cache = self.torrents_chain.split_cache_contexts(cache_data)
video_file, music_file = self.torrents_chain.cache_files()
await self.torrents_chain.async_save_cache(video_cache, video_file)
await self.torrents_chain.async_save_cache(music_cache, music_file)
async with async_cache_mutation("torrent-snapshots"):
# 远端识别期间不占写锁;提交时重读当前快照,仅修改本次目标。
latest = await self.torrents_chain.async_get_torrents()
current = next((context for context in latest.get(domain, [])
if HashUtils.md5(f"{context.torrent_info.title}{context.torrent_info.description}")
== torrent_hash), None)
if current is None:
return False, "种子缓存已刷新,目标条目不存在", None
current.media_info = mediainfo
video_cache, music_cache = self.torrents_chain.split_cache_contexts(latest)
video_file, music_file = self.torrents_chain.cache_files()
# 同一个资源不会跨分类移动;只写其所属缓存,避免无关文件失败或部分提交。
is_music_cache = current.torrent_info.category in (MediaType.MUSIC, MediaType.MUSIC.value)
cache, filename = (music_cache, music_file) if is_music_cache else (video_cache, video_file)
try:
await self.torrents_chain.async_save_cache(cache, filename, strict=True)
except Exception:
return False, "种子缓存保存失败,请稍后重试", None
return True, "重新识别完成", {
"media_name": mediainfo.title if mediainfo else "",
"media_year": mediainfo.year if mediainfo else "",

View File

@@ -26,6 +26,7 @@ from app.domain.meta.metamusic import audio_quality_tier, normalize_audio_format
from app.domain.metainfo import MetaInfo
from app.foundation import text as text_tools
from app.foundation.crypto import HashUtils
from app.foundation.url import UrlUtils
from app.runtime.cache import FileCache, TTLCache
from app.runtime.log import logger
from app.schemas.media import resolve_media_identity
@@ -327,6 +328,59 @@ class TorrentHelper:
time.sleep(attempt + 1)
return None
def _request_torrent_redirects(
self,
http_port: TorrentHttpPort,
*,
url: str,
cookie: Optional[str],
ua: Optional[str],
referer: Optional[str],
proxies: Optional[dict[str, Any]],
retry: bool,
) -> tuple[Optional[TorrentResponsePort], str, Optional[str]]:
"""
有界处理GET跳转,跨来源后永久移除原站点凭据和Referer。
:param http_port: 已装配HTTP端口
:param url: 当前下载地址
:param cookie: 仅供原始来源使用的站点Cookie
:param ua: 请求用户代理
:param referer: 原始来源页地址
:param proxies: 本次请求代理
:param retry: 是否对普通GET执行既有瞬时失败重试
:return: 最终响应、最终地址及允许在该地址使用的Cookie
:raises ValueError: 跳转缺少地址、目标非法、重复或超过上限
"""
seen = set()
for _hop in range(9):
if url in seen:
raise ValueError("种子下载重定向出现环路")
seen.add(url)
response = self._request_torrent_get(
http_port, retry and not torrent_rules.is_expiring_download_url(url),
url=url, cookie=cookie, ua=ua, referer=referer,
proxies=proxies, allow_redirects=False,
)
if response is None or response.status_code not in (301, 302, 303, 307, 308):
return response, url, cookie
location = response.headers.get("Location") or response.headers.get("location")
close = getattr(response, "close", None)
if callable(close):
close()
if not location:
raise ValueError("种子下载重定向缺少目标地址")
destination = urljoin(url, location)
if destination.startswith("magnet:"):
return None, destination, None
target = urlsplit(destination)
if target.scheme not in ("http", "https") or not target.hostname or target.username or target.password:
raise ValueError("种子下载重定向目标无效")
if not UrlUtils.same_origin(url, destination):
cookie, referer = None, None
url = destination
raise ValueError("种子下载重定向次数超过上限")
def _should_retry_torrent_response(self, response: Optional[TorrentResponsePort]) -> bool:
"""
保留重定向、磁力和首次确认页,明确限流不得消耗瞬时重试预算。
@@ -380,19 +434,15 @@ class TorrentHelper:
config = get_chain_runtime_config_snapshot()
http_port = _require_torrent_port()
retry = cache_invalid and not torrent_rules.is_expiring_download_url(url)
req = self._request_torrent_get(
http_port, retry, url=url, cookie=cookie, ua=ua, referer=referer,
proxies=config.proxy if proxy else None, allow_redirects=False,
)
while req is not None and req.status_code in [301, 302]:
url = req.headers['Location']
if url and url.startswith("magnet:"):
return None, url, "", [], "获取到磁力链接"
req = self._request_torrent_get(
http_port, retry and not torrent_rules.is_expiring_download_url(url),
url=url, cookie=cookie, ua=ua, referer=referer,
proxies=config.proxy if proxy else None, allow_redirects=False,
try:
req, url, cookie = self._request_torrent_redirects(
http_port, url=url, cookie=cookie, ua=ua, referer=referer,
proxies=config.proxy if proxy else None, retry=retry,
)
except ValueError as err:
return cache_path, None, "", [], str(err)
if url.startswith("magnet:"):
return None, url, "", [], "获取到磁力链接"
if rate_limit_error := _torrent_rate_limit_error(req):
return cache_path, None, "", [], rate_limit_error
if req is not None and req.status_code == 200:
@@ -416,7 +466,7 @@ class TorrentHelper:
action, data = confirmation
req = http_port.request(
method="POST", url=action, cookie=cookie, ua=ua,
referer=url, proxies=config.proxy if proxy else None, data=data,
referer=url, proxies=config.proxy if proxy else None, data=data, allow_redirects=False,
)
if rate_limit_error := _torrent_rate_limit_error(req):
return cache_path, None, "", [], rate_limit_error

View File

@@ -147,14 +147,20 @@ class ChainBase(RecognitionMixin, MessageProcessingMixin, NotificationMixin, met
logger.error(f"异步加载缓存 {filename} 出错:{str(err)}")
return None
async def async_save_cache(self, cache: Any, filename: str) -> None:
async def async_save_cache(self, cache: Any, filename: str, *, strict: bool = False) -> None:
"""
异步保存缓存
异步保存缓存,默认保留旧插件的失败日志合同。
:param cache: 待序列化的业务快照
:param filename: 目标缓存键
:param strict: 为True时向需要确认落盘的用例传播失败
"""
try:
await self.async_filecache.set(filename, pickle.dumps(cache))
except Exception as err:
logger.error(f"异步保存缓存 {filename} 出错:{str(err)}")
if strict:
raise
return
def save_cache(self, cache: Any, filename: str) -> None:

View File

@@ -6,6 +6,7 @@ from __future__ import annotations
import re
import shutil
import tempfile
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union, cast
@@ -33,6 +34,7 @@ from app.domain.context import (
SubtitleInfo,
)
from app.domain.metainfo import MetaInfo
from app.foundation.url import UrlUtils
from app.runtime.log import logger
from app.schemas.file import FileItem as _SchemaFileItem
from app.schemas.file import FileURI
@@ -264,7 +266,9 @@ class DownloadSubtitleOwner(_DownloadOwnerBase):
"""
生成安全的字幕文件名。
"""
file_name = Path(file_name or fallback_name).name
file_name = Path((file_name or fallback_name).replace("\\", "/")).name
if file_name in ("", ".", ".."):
file_name = Path(fallback_name).name
if not Path(file_name).suffix and Path(fallback_name).suffix:
file_name = f"{file_name}{Path(fallback_name).suffix}"
return file_name
@@ -471,10 +475,12 @@ class DownloadSubtitleOwner(_DownloadOwnerBase):
return False, message, []
saved_files = []
temp_file = self.runtime_config.temporary_path / file_name
temp_extract_dir = temp_file.with_name(temp_file.stem)
temp_root = None
try:
self.runtime_config.temporary_path.mkdir(parents=True, exist_ok=True)
temp_root = Path(tempfile.mkdtemp(prefix="subtitle-", dir=self.runtime_config.temporary_path))
temp_file = temp_root / file_name
temp_extract_dir = temp_root / "extracted"
temp_file.write_bytes(response.content)
if self._is_subtitle_archive(file_name):
try:
@@ -492,6 +498,9 @@ class DownloadSubtitleOwner(_DownloadOwnerBase):
temp_extract_dir,
self.runtime_config.subtitle_extensions,
):
if not sub_file.resolve().is_relative_to(temp_extract_dir.resolve()):
logger.warning("字幕解压结果越过临时目录,拒绝上传")
continue
uploaded_path, message = self._upload_subtitle_file(
storage_chain=storage_chain,
storage=storage,
@@ -524,10 +533,8 @@ class DownloadSubtitleOwner(_DownloadOwnerBase):
return False, message, []
finally:
try:
if temp_extract_dir.exists():
shutil.rmtree(temp_extract_dir)
if temp_file.exists():
temp_file.unlink()
if temp_root is not None:
shutil.rmtree(temp_root)
except Exception as err:
logger.error(f"删除临时字幕文件失败:{str(err)}")
@@ -634,62 +641,35 @@ class DownloadSubtitleOwner(_DownloadOwnerBase):
if response.status_code != 200:
logger.error(f"下载字幕文件失败:{sublink}")
return
file_name = TorrentHelper.get_url_filename(response, sublink)
if not file_name:
raw_name = TorrentHelper.get_url_filename(response, sublink)
if not raw_name:
logger.warn(f"链接不是字幕文件:{sublink}")
return
archive_format = self._SUBTITLE_ARCHIVE_FORMATS.get(
Path(file_name).suffix.lower()
)
if not archive_format:
if Path(file_name).suffix.lower() not in self.runtime_config.subtitle_extensions:
logger.warn(f"链接不是支持的字幕文件:{sublink} - {file_name}")
return
sub_file = self.runtime_config.temporary_path / file_name
sub_file.write_bytes(response.content)
if not working_dir_item.path:
logger.error("字幕工作目录路径为空")
return
target_sub_file = Path(working_dir_item.path) / sub_file.name
if storage_chain.get_file_item(storage, target_sub_file):
logger.info(f"字幕文件已存在:{target_sub_file}")
return
logger.info(f"转移字幕 {sub_file} 到 {target_sub_file} ...")
storage_chain.upload_file(working_dir_item, sub_file)
file_name = self._safe_subtitle_file_name(raw_name, "subtitle.srt")
archive_format = self._subtitle_archive_format(file_name)
if not archive_format and Path(file_name).suffix.lower() not in self.runtime_config.subtitle_extensions:
logger.warn(f"链接不是支持的字幕文件:{sublink} - {file_name}")
return
archive_file = self.runtime_config.temporary_path / file_name
archive_file.write_bytes(response.content)
archive_path = archive_file.with_name(archive_file.stem)
try:
archive_port.unpack(
archive_file,
archive_path,
archive_format=archive_format,
)
for sub_file in archive_port.list_files(
archive_path,
self.runtime_config.subtitle_extensions,
):
if not working_dir_item.path:
logger.error("字幕工作目录路径为空")
return
target_sub_file = Path(working_dir_item.path) / sub_file.name
if storage_chain.get_file_item(storage, target_sub_file):
logger.info(f"字幕文件已存在:{target_sub_file}")
continue
logger.info(f"转移字幕 {sub_file} 到 {target_sub_file} ...")
storage_chain.upload_file(working_dir_item, sub_file)
except Exception as err:
logger.error(f"字幕压缩包解压失败:{archive_file} - {str(err)}")
finally:
self.runtime_config.temporary_path.mkdir(parents=True, exist_ok=True)
# 临时目录只属于本次响应;清理范围不由远端文件名或压缩包名称决定。
with tempfile.TemporaryDirectory(prefix="site-subtitle-", dir=self.runtime_config.temporary_path) as directory:
temporary = Path(directory)
subtitle_file = temporary / file_name
subtitle_file.write_bytes(response.content)
try:
if archive_path.exists():
shutil.rmtree(archive_path)
if archive_file.exists():
archive_file.unlink()
if archive_format:
archive_path = temporary / "extracted"
archive_port.unpack(subtitle_file, archive_path, archive_format=archive_format)
files = archive_port.list_files(archive_path, self.runtime_config.subtitle_extensions)
else:
archive_path, files = temporary, [subtitle_file]
for sub_file in files:
if not sub_file.resolve().is_relative_to(archive_path.resolve()):
logger.warning("字幕解压结果越过临时目录,拒绝上传")
continue
self._upload_subtitle_file(storage_chain, storage, working_dir_item, sub_file)
except Exception as err:
logger.error(f"删除临时文件失败:{str(err)}")
logger.error(f"保存站点字幕失败:{str(err)}")
def download_site_subtitles(
self,
@@ -751,7 +731,7 @@ class DownloadSubtitleOwner(_DownloadOwnerBase):
logger.info(f"找到字幕下载链接:{sublink},开始下载...")
ret = http.get(
sublink,
cookies=torrent.site_cookie,
cookies=torrent.site_cookie if UrlUtils.same_origin(torrent.page_url, sublink) else None,
ua=torrent.site_ua,
proxies=self.runtime_config.proxy if torrent.site_proxy else None,
)

View File

@@ -411,6 +411,7 @@ class SearchSubtitleOwner(_SearchOwnerBase):
)
subtitles: List[SubtitleInfo] = []
matches: List[SubtitleInfo] = []
search_count = 0
for search_word in keywords:
if search_count > 0:
@@ -424,22 +425,16 @@ class SearchSubtitleOwner(_SearchOwnerBase):
or []
)
search_count += 1
if not self.runtime_config.search_multiple_name and subtitles:
logger.info(f"共搜索到 {len(subtitles)} 个字幕,停止搜索")
matches = await run_in_threadpool(
self._parse_subtitle_result, subtitles=subtitles, mediainfo=mediainfo,
keyword=mediainfo.title, season_episodes=season_episodes,
episode=episode, custom_words=custom_words,
)
if not self.runtime_config.search_multiple_name and matches:
logger.info(f"共匹配到 {len(matches)} 个字幕,停止别名搜索")
break
return cast(
List[SubtitleInfo],
await run_in_threadpool(
self._parse_subtitle_result,
subtitles=subtitles,
mediainfo=mediainfo,
keyword=mediainfo.title,
season_episodes=season_episodes,
episode=episode,
custom_words=custom_words,
),
)
return matches
async def _async_search_subtitles_for_media_stream(
self,
@@ -498,6 +493,7 @@ class SearchSubtitleOwner(_SearchOwnerBase):
)
subtitles: List[SubtitleInfo] = []
matches: List[SubtitleInfo] = []
search_count = 0
for search_word in keywords:
if search_count > 0:
@@ -516,8 +512,13 @@ class SearchSubtitleOwner(_SearchOwnerBase):
}
search_count += 1
if not self.runtime_config.search_multiple_name and subtitles:
logger.info(f"共搜索到 {len(subtitles)} 个字幕,停止搜索")
matches = await run_in_threadpool(
self._parse_subtitle_result, subtitles=subtitles, mediainfo=mediainfo,
keyword=mediainfo.title, season_episodes=season_episodes,
episode=episode, custom_words=custom_words,
)
if not self.runtime_config.search_multiple_name and matches:
logger.info(f"共匹配到 {len(matches)} 个字幕,停止别名搜索")
break
yield {
@@ -527,15 +528,7 @@ class SearchSubtitleOwner(_SearchOwnerBase):
"text": f"正在识别匹配 {len(subtitles)} 个候选字幕 ...",
}
match_subtitles = await run_in_threadpool(
self._parse_subtitle_result,
subtitles=subtitles,
mediainfo=mediainfo,
keyword=mediainfo.title,
season_episodes=season_episodes,
episode=episode,
custom_words=custom_words,
)
match_subtitles = matches
final_items = [subtitle.to_dict() for subtitle in match_subtitles]
yield {
"type": "replace",

View File

@@ -749,7 +749,8 @@ class SiteChain(InteractionChainMixin, ChainBase):
favicon_url = urljoin(url, fav_link[0])
with _open_site_response(
method="GET", url=favicon_url, cookie=cookie, timeout=15, ua=ua
method="GET", url=favicon_url,
cookie=cookie if url_tools.UrlUtils.same_origin(url, favicon_url) else None, timeout=15, ua=ua
) as res:
if res:
return favicon_url, base64.b64encode(res.content).decode()

View File

@@ -23,6 +23,7 @@ from app.domain.meta.metabase import MetaBase
from app.domain.meta.metamusic import MetaMusic
from app.domain.metainfo import MetaInfo
from app.foundation.url import UrlUtils
from app.runtime.cache import cache_mutation
from app.runtime.log import logger
from app.runtime.stop import runtime_stop_state
from app.schemas.media import resolve_media_identity
@@ -606,6 +607,7 @@ class TorrentsChain(ChainBase):
context.media_recognize_fail_count = 1
return context
@cache_mutation("torrent-snapshots")
def refresh(
self,
stype: Optional[str] = None,

View File

@@ -6,9 +6,11 @@ from datetime import datetime
from typing import Any, List, Mapping, Optional, Tuple
from sqlalchemy import delete as sqlalchemy_delete
from sqlalchemy import false, func, or_, select
from sqlalchemy import false, func, or_, select, text, update
from sqlalchemy.ext.asyncio import AsyncSession
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.models.site import Site
@@ -16,6 +18,7 @@ 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.query import literal_contains
from app.schemas.exception import SiteDomainConflictError
async def _async_first(session: AsyncSession, statement: Any) -> Optional[Site]:
@@ -118,6 +121,64 @@ def _latest_userdata_join(statement: Any, subquery: Any) -> Any:
)
def _site_domain_lock(dialect: str) -> TextClause | Update:
"""
在数据库事务中锁住站点域名准入,兼容空表及已有重复历史记录。
SQLite的零行UPDATE仍获取数据库写锁;PostgreSQL表锁覆盖空表与并发插入。
不持有进程锁,不提交事务,锁由调用方UoW提交或回滚时释放。
:param dialect: 当前会话绑定的SQLAlchemy方言名称
:return: 获取事务写入准入的语句
"""
if dialect == "postgresql":
return text("LOCK TABLE site IN SHARE ROW EXCLUSIVE MODE")
if dialect == "sqlite":
return update(Site).where(Site.id == -1).values(id=Site.id)
raise RuntimeError("站点域名并发准入不支持当前数据库方言")
def _check_site_domain(session: Session, domain: Optional[str], site_id: Optional[int] = None) -> None:
"""
同步取得事务准入后重新检查域名,防止先查后插竞争。
:param session: 调用方持有的真实数据库会话
:param domain: 新配置的规范域名
:param site_id: 更新时允许保留该站点自身域名
:raises SiteDomainConflictError: 已有另一站点占用域名
"""
if domain is None:
return
session.execute(_site_domain_lock(session.get_bind().dialect.name))
statement = select(Site.id).where(Site.domain == domain)
if site_id is not None:
statement = statement.where(Site.id != site_id)
if session.execute(statement.limit(1)).scalar_one_or_none() is not None:
raise SiteDomainConflictError("站点已存在")
async def _async_check_site_domain(
session: AsyncSession, domain: Optional[str], site_id: Optional[int] = None,
) -> None:
"""
异步取得数据库事务准入后重新检查域名。
:param session: 调用方持有的真实数据库会话
:param domain: 新配置的规范域名
:param site_id: 更新时允许保留该站点自身域名
:raises SiteDomainConflictError: 已有另一站点占用域名
"""
if domain is None:
return
await session.execute(_site_domain_lock(session.get_bind().dialect.name))
statement = select(Site.id).where(Site.domain == domain)
if site_id is not None:
statement = statement.where(Site.id != site_id)
result = await session.execute(statement.limit(1))
if result.scalar_one_or_none() is not None:
raise SiteDomainConflictError("站点已存在")
class SiteOper(DbOper):
"""
站点管理
@@ -127,11 +188,18 @@ class SiteOper(DbOper):
"""
新增站点
"""
site = Site(**kwargs)
if not self.get_by_domain(kwargs.get("domain")):
self._stage_create(site)
def stage(session: Session) -> Tuple[bool, str]:
"""
在同一调用方事务中完成锁定、查重及暂存。
"""
try:
_check_site_domain(session, kwargs.get("domain"))
except SiteDomainConflictError:
return False, "站点已存在"
session.add(Site(**kwargs))
return True, "新增站点成功"
return False, "站点已存在"
return self._execute_sync_write(stage)
def get(self, sid: int) -> Optional[Site]:
"""
@@ -169,6 +237,7 @@ class SiteOper(DbOper):
raise RuntimeError("站点事务新增需要调用方提供 AsyncSession")
values = dict(payload)
values.pop("id", None)
await _async_check_site_domain(self._db, values.get("domain"))
self._db.add(Site(**values))
async def stage_update(
@@ -179,6 +248,8 @@ class SiteOper(DbOper):
"""
暂存站点字段更新,事务由调用方统一提交。
"""
if "domain" in payload:
await _async_check_site_domain(self._db, payload["domain"], site_id)
site = await self.async_get(site_id)
if not site:
return False
@@ -331,20 +402,37 @@ class SiteOper(DbOper):
"""
更新站点
"""
site = self.get(sid)
if not site:
return None
self._stage_update(site, payload)
return site
def stage(session: Session) -> Optional[Site]:
"""
在同一事务中校验域名并更新现有站点。
"""
if "domain" in payload:
_check_site_domain(session, payload["domain"], sid)
site: Optional[Site] = session.get(Site, sid)
if site is not None:
for key, value in payload.items():
setattr(site, key, value)
return site
return self._execute_sync_write(stage)
async def async_update(self, sid: int, payload: dict[str, Any]) -> Optional[Site]:
"""
异步更新站点。
在调用方异步事务内校验域名并更新站点。
"""
site = await self.async_get(sid)
if site:
await self._stage_async_update(site, payload)
return site
async def stage(session: AsyncSession) -> Optional[Site]:
"""
共享与站点创建相同的数据库准入锁。
"""
if "domain" in payload:
await _async_check_site_domain(session, payload["domain"], sid)
site: Optional[Site] = await session.get(Site, sid)
if site is not None:
for key, value in payload.items():
setattr(site, key, value)
return site
return await self._execute_async_write(stage)
def get_by_domain(self, domain: Optional[str]) -> Optional[Site]:
"""

View File

@@ -44,6 +44,25 @@ class UrlUtils:
return None
return normalized_url
@staticmethod
def same_origin(source: object, destination: object) -> bool:
"""
比较HTTP来源的协议、主机及有效端口;无效地址不能接收来源凭据。
:param source: 认证凭据所属的绝对HTTP地址
:param destination: 准备请求的绝对HTTP地址
:return: 两地址来源完全一致且均有效时为True
"""
source_url, destination_url = UrlUtils.normalize_http_url(source), UrlUtils.normalize_http_url(destination)
if source_url is None or destination_url is None:
return False
first, second = urlparse(source_url), urlparse(destination_url)
if first.username or first.password or second.username or second.password:
return False
return (first.scheme, first.hostname, first.port if first.port is not None else (443 if first.scheme == "https" else 80)) == (
second.scheme, second.hostname, second.port if second.port is not None else (443 if second.scheme == "https" else 80)
)
@staticmethod
def standardize_base_url(host: str) -> str:
"""

View File

@@ -157,6 +157,10 @@ class MTorrentSiteUserInfo(SiteParserBase):
self.seeding_size += page_seeding_size
self.seeding_info.extend(page_seeding_info)
# 空页或没有有效条目的页面不再推进,汇总可能滞后于实时做种明细。
if not page_seeding:
return None
# 查询总做种数
seeder_count = 0
try:

View File

@@ -371,16 +371,26 @@ class NexusAudiencesSiteUserInfo(NexusPhpSiteUserInfo):
if not DomUtils.has_child_elements(html):
return
for user_node in html.xpath('//*[@data-uploader-url or @data-uploader-stats]'):
userbars = html.xpath(
'//*[contains(concat(" ", normalize-space(@class), " "), " site-userbar ")]'
)
scope = userbars[0] if userbars else html
nodes = scope.xpath('.//*[@data-uploader-url or @data-uploader-stats]')
# 兼容只有单个用户卡的旧页面;多用户卡且无用户栏时不能猜测当前账号。
if not userbars:
nodes = [node for node in nodes if self.userid and
re.search(rf"userdetails\.php\?id={re.escape(str(self.userid))}(?:&|$)",
node.get("data-uploader-url") or "")] or (nodes if len(nodes) == 1 else [])
for user_node in nodes:
self.__parse_user_identity(user_node)
self.__parse_uploader_stats(user_node.get("data-uploader-stats"))
# data-uploader-stats 不包含分享率,需从 compact metric 的 class 中读取。
self.__parse_compact_metric(html, "ratio", "ratio")
self.__parse_compact_metric(html, "uploaded", "upload")
self.__parse_compact_metric(html, "downloaded", "download")
self.__parse_compact_metric(html, "bonus", "bonus")
self.__parse_compact_metric(html, "active", "active")
self.__parse_compact_metric(scope, "ratio", "ratio")
self.__parse_compact_metric(scope, "uploaded", "upload")
self.__parse_compact_metric(scope, "downloaded", "download")
self.__parse_compact_metric(scope, "bonus", "bonus")
self.__parse_compact_metric(scope, "active", "active")
finally:
if html is not None:
del html

View File

@@ -221,7 +221,11 @@ class MTorrentSpider:
统一判定搜索响应状态并投影 M-Team 种子结果。
"""
if res and res.status_code == 200:
data = res.json().get('data', {})
payload = res.json()
if str(payload.get("code")) != "0" or not isinstance(payload.get("data"), dict):
logger.warning(f"{self._name} 搜索失败,站点返回业务错误")
return True, []
data = payload["data"]
results = data.get("data") or []
# 分页事实只供逐页搜索判断末页,空结果仍按末页处理。
page_number, total_pages = data.get("pageNumber"), data.get("totalPages")

View File

@@ -7,13 +7,13 @@ from typing import Any, List, Optional, Tuple
from app.adapters.network.http import AsyncRequestUtils, RequestUtils
from app.foundation import temporal as time_tools
from app.foundation.singleton import SingletonClass
from app.foundation.crypto import HashUtils
from app.runtime.cache import cached
from app.runtime.log import logger
from app.runtime.settings import get_runtime_setting
class TNodeSpider(metaclass=SingletonClass):
class TNodeSpider:
"""
TNode 页面令牌与种子搜索 API 适配器。
"""
@@ -47,13 +47,28 @@ class TNodeSpider(metaclass=SingletonClass):
if indexer.get('proxy'):
self._proxy = get_runtime_setting('PROXY')
self._cookie = indexer.get('cookie')
self._token_key = HashUtils.md5(repr((self._domain, self._cookie, indexer.get('ua'))))
self._ua = indexer.get('ua')
self._timeout = indexer.get('timeout') or 15
@cached(region="indexer_spider", maxsize=1, ttl=60 * 60 * 24, skip_empty=True, shared_key="get_token")
def __get_token(self) -> Optional[str]:
"""
以当前站点和凭据隔离的缓存键获取同步CSRF令牌。
"""
return self.__cached_token(self._token_key)
async def __async_get_token(self) -> Optional[str]:
"""
以当前站点和凭据隔离的缓存键获取异步CSRF令牌。
"""
return await self.__async_cached_token(self._token_key)
@cached(region="indexer_spider", maxsize=64, ttl=60 * 60 * 24, skip_empty=True, shared_key="get_token")
def __cached_token(self, _identity: str) -> Optional[str]:
"""
同步请求站点首页并提取 CSRF 令牌。
:param _identity: 站点和凭据摘要,用于隔离共享令牌缓存
"""
if not self._domain:
return None
@@ -63,10 +78,12 @@ class TNodeSpider(metaclass=SingletonClass):
timeout=self._timeout).get_res(url=self._domain)
return self.__parse_token_response(res)
@cached(region="indexer_spider", maxsize=1, ttl=60 * 60 * 24, skip_empty=True, shared_key="get_token")
async def __async_get_token(self) -> Optional[str]:
@cached(region="indexer_spider", maxsize=64, ttl=60 * 60 * 24, skip_empty=True, shared_key="get_token")
async def __async_cached_token(self, _identity: str) -> Optional[str]:
"""
异步请求站点首页并提取 CSRF 令牌。
:param _identity: 站点和凭据摘要,用于隔离共享令牌缓存
"""
if not self._domain:
return None

View File

@@ -463,13 +463,12 @@ class QbittorrentModule(_DownloaderModuleBase[Qbittorrent]):
:param hashs: 种子哈希或哈希列表
:param tags: 需要追加的标签列表
:param downloader: 下载器配置名称,省略时使用默认实例
:return: 找到实例并调用标签接口后返回 True,不表示写入已经确认;找不到实例时返回 None
:return: 客户端接受标签写入时返回 True,RPC失败时返回 False;找不到实例时返回 None
"""
server = self.get_instance(downloader)
if not server:
return None
server.set_torrents_tag(ids=hashs, tags=tags)
return True
return server.set_torrents_tag(ids=hashs, tags=tags)
def update_torrent(
self,

View File

@@ -451,21 +451,22 @@ class Qbittorrent:
logger.error(f"移除种子Tag出错:{str(err)}")
return False
def set_torrents_tag(self, ids: Union[str, list[str]], tags: list[str]) -> None:
def set_torrents_tag(self, ids: Union[str, list[str]], tags: list[str]) -> bool:
"""
向指定种子追加标签,保留原有标签。
未连接时直接返回,请求失败只记录日志;本方法不返回写入确认。
:param ids: 种子哈希或哈希列表
:param tags: 待追加的标签列表
:return: RPC成功完成时为True,未连接或失败时为False
"""
if not self.qbc:
return
return False
try:
self.qbc.torrents_add_tags(tags=tags, torrent_hashes=ids)
return True
except Exception as err:
logger.error(f"设置种子Tag出错:{str(err)}")
return False
def is_force_resume(self) -> Optional[bool]:
"""

View File

@@ -5,6 +5,7 @@ rTorrent 下载模块,负责实例路由、任务投影与下载文件选择
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple, Union, cast
from app.domain import torrent as torrent_rules
from app.domain.metainfo import MetaInfo
from app.foundation import size as size_tools
from app.foundation import temporal as time_tools
@@ -115,6 +116,7 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]):
if not torrent_from_file and not is_magnet:
return None, None, None, "添加种子任务失败:无法读取种子文件"
resolved_content = cast(Union[str, bytes], resolved_content)
expected_hashes = torrent_rules.download_hashes(resolved_content)
# 失败提示使用种子名称(磁力链接保留原文),不拼接种子文件的二进制内容
torrent_desc = torrent_from_file.name if torrent_from_file else resolved_content
@@ -157,12 +159,8 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]):
if torrents:
try:
for torrent in torrents:
# 名称与大小相等则认为是同一个种子
if torrent.get("name") == getattr(
torrent_from_file, "name", ""
) and torrent.get("total_size") == getattr(
torrent_from_file, "total_size", 0
):
candidate_hash = str(torrent.get("hash") or "").lower()
if candidate_hash in expected_hashes:
torrent_hash = cast(str, torrent.get("hash"))
torrent_tags = [
str(t).strip()
@@ -208,45 +206,14 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]):
else:
torrent_hash = added_torrent_hash
if episodes:
torrent_files = server.get_files(torrent_hash)
if not torrent_files:
return (
downloader or self.get_default_config_name(),
torrent_hash,
torrent_layout,
"获取种子文件失败,下载任务可能在暂停状态",
)
# 不需要的文件ID
file_ids = []
# 需要的集清单
sucess_epidised = set()
try:
for torrent_file in torrent_files:
file_id = torrent_file["id"]
file_name = torrent_file["name"]
meta_info = MetaInfo(file_name)
if not meta_info.episode_list or not set(
meta_info.episode_list
).issubset(episodes):
file_ids.append(file_id)
else:
sucess_epidised.update(meta_info.episode_list)
finally:
torrent_files.clear()
del torrent_files
selected_episodes = list(sucess_epidised)
if selected_episodes and file_ids:
# 设置不需要的文件优先级为0(不下载)
server.set_files(
torrent_hash=torrent_hash, file_ids=file_ids, priority=0
)
server.start_torrents(torrent_hash)
selected, message = self._select_episode_files(server, torrent_hash, episodes)
if not selected:
return None, None, None, message
return (
downloader or self.get_default_config_name(),
torrent_hash,
torrent_layout,
f"添加下载成功,已选择集数:{selected_episodes}",
message,
)
else:
return (
@@ -256,6 +223,36 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]):
"添加下载成功",
)
@staticmethod
def _select_episode_files(server: Rtorrent, torrent_hash: str, episodes: Set[int]) -> Tuple[bool, str]:
"""
对暂停添加的任务完成选集,所有RPC均成功才允许下载链确认任务。
:param server: 当前下载器客户端
:param torrent_hash: 已暂停添加的任务Hash
:param episodes: 本次允许下载的目标集数
:return: 是否确认选集启动成功及结果说明
"""
torrent_files = server.get_files(torrent_hash)
if not torrent_files:
return False, "获取种子文件失败,下载任务保留暂停状态,请检查下载器"
file_ids, selected_episodes = [], set()
for torrent_file in torrent_files:
meta = MetaInfo(torrent_file["name"])
if meta.episode_list and set(meta.episode_list).issubset(episodes):
selected_episodes.update(meta.episode_list)
else:
file_ids.append(torrent_file["id"])
if not selected_episodes:
return False, "未匹配到目标集数,下载任务保留暂停状态"
if file_ids and not server.set_files(torrent_hash=torrent_hash, file_ids=file_ids, priority=0):
return False, "设置选集优先级失败,下载任务保留暂停状态"
if not server.start_torrents(torrent_hash):
stopped = server.stop_torrents(torrent_hash)
message = "启动下载失败,已请求暂停,请检查下载器确认状态" if stopped else "启动下载状态未知,请检查下载器"
return False, message
return True, f"添加下载成功,已选择集数:{sorted(selected_episodes)}"
def list_torrents(
self,
status: Optional[TorrentStatus] = None,
@@ -448,6 +445,7 @@ class RtorrentModule(_DownloaderModuleBase[Rtorrent]):
return server.delete_torrents(
delete_file=delete_file if delete_file is not None else True,
ids=hashs,
path_mapper=lambda path: self.normalize_return_path(path, downloader),
)
def set_torrents_tag(

View File

@@ -7,7 +7,7 @@ import io
import socket
import traceback
import xmlrpc.client
from collections.abc import Buffer
from collections.abc import Buffer, Callable
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, TypedDict, Union, cast
from urllib.parse import urlparse
@@ -504,16 +504,18 @@ class Rtorrent:
logger.error(f"停止种子出错:{str(err)}")
return False
def delete_torrents(self, delete_file: bool, ids: Union[str, list[str]]) -> bool:
def delete_torrents(self, delete_file: bool, ids: Union[str, list[str]],
*, path_mapper: Optional[Callable[[Path], str]] = None) -> bool:
"""
删除指定种子任务,并按选项删除下载文件。
rTorrent 返回的内容路径在 MoviePilot 所在文件系统中删除。文件清理失败会记录警告;
返回 True 只说明任务删除流程完成,不保证文件全部移除。
先将rTorrent内容路径映射到MoviePilot本地文件系统,文件清理成功后才移除任务。
清理失败或映射为远程存储时保留任务,以便用户核对和重试。
:param delete_file: 是否同时删除下载文件
:param ids: 种子哈希或哈希列表
:return: 请求完成时返回 True;未连接或请求失败时返回 False,不代表任务已完成该动作
:param path_mapper: 将下载器内容路径映射为宿主本地路径;省略时保留直接客户端调用合同
:return: 文件清理及任务删除均完成时返回 True,失败时返回 False
"""
if not self._proxy:
return False
@@ -524,23 +526,23 @@ class Rtorrent:
ids = [ids]
for tid in ids:
if delete_file:
# 先获取base_path用于删除文件
try:
base_path = self._proxy.d.base_path(tid)
self._proxy.d.erase(tid)
if base_path:
import shutil
path = Path(_rpc_text(base_path))
if path.is_dir():
shutil.rmtree(str(path), ignore_errors=True)
elif path.is_file():
path.unlink(missing_ok=True)
except Exception as e:
logger.warning(f"删除种子文件出错:{str(e)}")
self._proxy.d.erase(tid)
else:
self._proxy.d.erase(tid)
base_path = self._proxy.d.base_path(tid)
if not base_path:
logger.warning("下载器未返回文件路径,保留任务以便人工处理")
return False
path = Path(_rpc_text(base_path))
mapped = path_mapper(path) if path_mapper else path.as_posix()
# 云存储URI不能交给本地Path删除;下载器任务也保留以便核对。
if ":" in mapped and not (len(mapped) > 2 and mapped[1] == ":"):
logger.warning("下载器文件映射为远程存储,拒绝本地删除")
return False
path = Path(mapped)
if path.is_dir():
import shutil
shutil.rmtree(path)
elif path.exists():
path.unlink()
self._proxy.d.erase(tid)
return True
except Exception as err:
logger.error(f"删除种子出错:{str(err)}")

View File

@@ -4,6 +4,7 @@ Transmission 客户端连接与下载任务操作封装。
import time
from typing import List, Optional, Sequence, Tuple, Union
from urllib.parse import urlsplit
import transmission_rpc
from transmission_rpc import Client, File, Torrent
@@ -32,7 +33,8 @@ class Transmission:
"trackerStats",
"leftUntilDone", "rateDownload", "rateUpload", "recheckProgress", "rateDownload", "rateUpload",
"peersGettingFromUs", "peersSendingToUs", "uploadRatio", "uploadedEver", "downloadedEver", "downloadDir",
"error", "errorString", "doneDate", "queuePosition", "activityDate", "trackers"]
"error", "errorString", "doneDate", "queuePosition", "activityDate", "trackers",
"downloadLimit", "uploadLimit", "seedRatioLimit", "seedIdleLimit"]
def __init__(self, host: Optional[str] = None, port: Optional[int] = None,
username: Optional[str] = None, password: Optional[str] = None,
@@ -51,12 +53,16 @@ class Transmission:
self._host: Optional[str] = None
self._port: Optional[int] = None
self._protocol: object
self._path = "/transmission/rpc"
if host and port:
self._protocol, self._host, self._port = kwargs.get("protocol", "http"), host, port
elif host:
result = UrlUtils.parse_url_params(url=host)
if result:
self._protocol, self._host, self._port, path = result
self._protocol, self._host, self._port, _path = result
self._path = urlsplit(host if "://" in host else f"http://{host}").path or self._path
if self._path == "/":
self._path = "/transmission/rpc"
else:
logger.error("Transmission配置不正确!")
return
@@ -102,6 +108,7 @@ class Transmission:
trt = transmission_rpc.Client(protocol=self._protocol, # noqa
host=self._host,
port=self._port,
path=self._path,
username=self._username,
password=self._password,
# transmission-rpc 运行时接受 Requests 的连接与读取超时二元组。
@@ -584,14 +591,14 @@ class Transmission:
https://github.com/trim21/transmission-rpc/blob/8eb82629492a0eeb0bb565f82c872bf9ccdcb313/transmission_rpc/client.py#L654
:param hash_string: 种子哈希
:param tracker_list: 要写入的 Tracker 地址列表,原样交给客户端
:param tracker_list: 要写入的 Tracker 地址列表,每个地址作为独立层级交给客户端
:return: 请求完成时返回 True;未连接或请求失败时返回 False,不代表任务已完成该动作
"""
if not self.trc:
return False
try:
self.trc.change_torrent(ids=hash_string,
tracker_list=tracker_list)
tracker_list=[[url] for url in tracker_list] if tracker_list is not None else None)
return True
except Exception as err:
logger.error(f"修改tracker出错:{str(err)}")

View File

@@ -2,6 +2,7 @@
缓存契约、进程内后端与装饰器,具体持久化后端由启动层注入。
"""
import asyncio
import contextvars
import inspect
import logging
@@ -53,6 +54,51 @@ _file_ttl_provider: Callable[[], int] = lambda: DEFAULT_CACHE_TTL
_redis_probe: Optional[Callable[[], bool]] = None
# 多文件业务缓存的读改写必须共享同一进程锁,锁名由有限的宿主缓存合同提供。
_mutation_locks: dict[str, threading.Lock] = {}
_mutation_locks_guard = threading.Lock()
def _cache_mutation_lock(name: str) -> threading.Lock:
"""
获取同步线程与异步任务共用的业务缓存写锁。
:param name: 宿主定义的有限业务缓存名称
:return: 当前进程该名称唯一的锁
"""
with _mutation_locks_guard:
return _mutation_locks.setdefault(name, threading.Lock())
@contextmanager
def cache_mutation(name: str) -> Generator[None, None, None]:
"""
在同步调用中串行化一个业务缓存的完整读改写。
:param name: 宿主定义的有限业务缓存名称
:yields: 本次读改写持有锁的作用域
"""
with _cache_mutation_lock(name):
yield
@asynccontextmanager
async def async_cache_mutation(name: str) -> AsyncGenerator[None, None]:
"""
非阻塞等待共享写锁,取消后不会有后台线程迟到取得锁。
:param name: 与同步调用共用的业务缓存名称
:yields: 本次异步读改写持有锁的作用域
"""
lock = _cache_mutation_lock(name)
while not lock.acquire(blocking=False):
await asyncio.sleep(0.01)
try:
yield
finally:
lock.release()
def configure_cache_factories(
*,
backend_type_provider: Callable[[], str],

View File

@@ -56,6 +56,12 @@ class BusinessRejectedError(Exception):
pass
class SiteDomainConflictError(BusinessRejectedError):
"""
站点域名已被另一持久化配置占用,当前事务应回滚并报告业务冲突。
"""
class OperationInterrupted(KeyboardInterrupt):
"""
用于表示操作被中断。

View File

@@ -7,6 +7,7 @@ from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Optional, Union, cast
from urllib.parse import urljoin, urlsplit
from app.adapters.network.doh import DohHelper
from app.adapters.network.http import AsyncRequestUtils, RequestUtils
@@ -59,6 +60,7 @@ from app.chain.system import (
configure_system_ports,
reset_system_ports,
)
from app.foundation.url import UrlUtils
from app.runtime.log import logger
@@ -406,12 +408,57 @@ class _DownloadHttpAdapter:
"""
发送下载链 GET 请求并原样保留响应三态。
"""
request = self._request(cookies=cookies, ua=ua, headers=headers, proxies=proxies, timeout=timeout)
kwargs: dict[str, Any] = {"raise_exception": raise_exception}
if params is not None:
kwargs["params"] = params
response = request.get_res(url, **kwargs)
return cast(Optional[DownloadResponsePort], response)
try:
return self._get_redirects(url, cookies=cookies, ua=ua, headers=headers, proxies=proxies,
timeout=timeout, params=params, raise_exception=raise_exception)
except ValueError:
if raise_exception:
raise
return None
def _get_redirects(
self, url: str, *, cookies: Optional[Union[str, dict[str, str]]], ua: Optional[str],
headers: Optional[dict[str, str]], proxies: Optional[dict[str, str]], timeout: Optional[int],
params: Optional[dict[str, Any]], raise_exception: bool,
) -> Optional[DownloadResponsePort]:
"""
跟随有界GET跳转;跨来源后不恢复Cookie、Authorization或Referer。
:param url: 当前下载地址
:param cookies: 仅供原始来源使用的Cookie
:param ua: 请求用户代理
:param headers: 原始来源额外请求头
:param proxies: 本次请求代理
:param timeout: 请求超时
:param params: 仅首跳附加的查询参数
:param raise_exception: 是否保留底层传输异常
:return: 最终响应或无响应
:raises ValueError: 跳转非法、重复或超过上限
"""
seen, request_headers = set(), dict(headers or {})
for _hop in range(9):
if url in seen:
raise ValueError("下载重定向出现环路")
seen.add(url)
request = self._request(cookies=cookies, ua=ua, headers=request_headers, proxies=proxies, timeout=timeout)
kwargs: dict[str, Any] = {"raise_exception": raise_exception, "allow_redirects": False}
if params is not None:
kwargs["params"] = params
response = cast(Optional[DownloadResponsePort], request.get_res(url, **kwargs))
if response is None or response.status_code not in (301, 302, 303, 307, 308):
return response
location = response.headers.get("Location") or response.headers.get("location")
response.close()
destination = urljoin(url, location or "")
target = urlsplit(destination)
if not location or UrlUtils.normalize_http_url(destination) is None or target.username or target.password:
raise ValueError("下载重定向目标无效")
if not UrlUtils.same_origin(url, destination):
cookies = None
request_headers = {key: value for key, value in request_headers.items()
if key.lower() not in ("cookie", "authorization", "proxy-authorization", "referer")}
url, params = destination, None
raise ValueError("下载重定向次数超过上限")
def post(
self,

View File

@@ -4,6 +4,7 @@
from contextlib import contextmanager
from typing import Any, Callable, Iterator, Mapping, Optional, cast
from urllib.parse import urljoin, urlsplit
from app.adapters.external.cookiecloud import CookieCloudHelper
from app.adapters.external.ocr import OcrHelper
@@ -42,6 +43,7 @@ from app.chain.site import (
configure_site_ports,
reset_site_ports,
)
from app.foundation.url import UrlUtils
class _RssHttpAdapter:
@@ -222,16 +224,38 @@ class _SiteHttpAdapter:
:param json_body: JSON 请求体,None 时保留无请求体行为
:yields: 在上下文有效期内提供响应或 None
"""
request = RequestUtils(
headers=dict(headers or {}),
cookies=cookie or "",
ua=ua or "",
proxies=dict(proxies or {}),
timeout=timeout,
)
request_options = {} if json_body is None else {"json": dict(json_body)}
with request.response_manager(method=method, url=url, **request_options) as response:
yield cast(Optional[SiteResponsePort], response)
request_headers = dict(headers or {})
seen = set()
for _hop in range(9):
if url in seen:
raise ValueError("站点请求重定向出现环路")
seen.add(url)
request = RequestUtils(
headers=request_headers, cookies=cookie or "", ua=ua or "",
proxies=dict(proxies or {}), timeout=timeout,
)
request_options: dict[str, Any] = {} if json_body is None else {"json": dict(json_body)}
if method.upper() == "GET":
request_options["allow_redirects"] = False
with request.response_manager(method=method, url=url, **request_options) as response:
if method.upper() != "GET" or response is None or response.status_code not in (301, 302, 303, 307, 308):
yield cast(Optional[SiteResponsePort], response)
return
location = response.headers.get("Location")
if not location:
raise ValueError("站点请求重定向缺少目标地址")
destination = urljoin(url, location)
target = urlsplit(destination)
if target.scheme not in ("http", "https") or not target.hostname or target.username or target.password:
raise ValueError("站点请求重定向目标无效")
if not UrlUtils.same_origin(url, destination):
cookie = None
request_headers = {
key: value for key, value in request_headers.items()
if key.lower() not in ("cookie", "authorization", "proxy-authorization", "referer")
}
url = destination
raise ValueError("站点请求重定向次数超过上限")
class _SiteBrowserAdapter: