fix(douyu): reject invalid activity cookies
This commit is contained in:
@@ -7,7 +7,7 @@ import re
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs, unquote, urlsplit
|
||||
from urllib.parse import parse_qs, unquote, urlsplit, urlunsplit
|
||||
|
||||
import requests
|
||||
|
||||
@@ -118,6 +118,28 @@ class DouyuActivityClient:
|
||||
"Cookie": self.cookie,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _safe_url(url: str) -> str:
|
||||
"""移除 query/fragment,避免将 Cookie、签名或一次性参数写入日志。"""
|
||||
parsed = urlsplit(url)
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path, "", ""))
|
||||
|
||||
def _redirect_error(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
source: str,
|
||||
response: requests.Response,
|
||||
) -> DouyuActivityError:
|
||||
location = response.headers.get("Location", "")
|
||||
safe_location = self._safe_url(location) if location else "-"
|
||||
trace = (
|
||||
f"method={method.upper()} url={self._safe_url(url)} "
|
||||
f"location={safe_location} history={response.status_code}->{safe_location}"
|
||||
)
|
||||
self.logger(f"{source}: 已拦截重定向 | {trace}")
|
||||
return DouyuActivityError(f"{source} 请求被重定向,Cookie 已失效,请重新登录({trace})")
|
||||
|
||||
def _request(
|
||||
self,
|
||||
method: str,
|
||||
@@ -130,14 +152,24 @@ class DouyuActivityClient:
|
||||
req_headers = self._headers()
|
||||
if headers:
|
||||
req_headers.update(headers)
|
||||
response = self.session.request(
|
||||
method,
|
||||
url,
|
||||
headers=req_headers,
|
||||
timeout=kwargs.pop("timeout", self.timeout),
|
||||
**kwargs,
|
||||
)
|
||||
# 活动 JSON 接口不应自动跳到登录页;忽略调用方传入的覆盖值。
|
||||
kwargs.pop("allow_redirects", None)
|
||||
try:
|
||||
response = self.session.request(
|
||||
method,
|
||||
url,
|
||||
headers=req_headers,
|
||||
timeout=kwargs.pop("timeout", self.timeout),
|
||||
allow_redirects=False,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise DouyuActivityError(
|
||||
f"{source} 请求失败: {method.upper()} {self._safe_url(url)}: {exc}"
|
||||
) from exc
|
||||
self._merge_response_cookie(response)
|
||||
if 300 <= response.status_code < 400:
|
||||
raise self._redirect_error(method, url, source, response)
|
||||
self.logger(f"{source}: {response.status_code}")
|
||||
response.raise_for_status()
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user