fix: 黄豆按站点方式保持登录并自动切换播放线路

This commit is contained in:
Nixevol
2026-10-25 05:40:19 +08:00
parent 3fe936fe70
commit f53498f6e6
11 changed files with 444 additions and 197 deletions
+111 -15
View File
@@ -34,6 +34,36 @@ class TokenExpired(RuntimeError):
pass
def _connection_error(exc: BaseException) -> bool:
text = str(exc).lower()
return any(
word in text
for word in (
"ssl",
"unexpected_eof",
"connection",
"timed out",
"timeout",
"10054",
"10060",
"连接",
"重置",
"强迫关闭",
)
)
def present_token(token: str, user_id: str) -> str:
token = (token or "").strip()
user_id = (user_id or "").strip()
if not token or not user_id:
return token
suffix = f"_{user_id}"
if token.endswith(suffix):
return token
return token + suffix
class ApiError(RuntimeError):
def __init__(self, message: str, code=None) -> None:
super().__init__(message)
@@ -50,9 +80,16 @@ class HuangdouClient:
self.guest_session_id = ""
self.guest_device_info: dict = {}
self.token = ""
self.user_id = ""
self.account_token = ""
self.account_user_id = ""
self.account_username = ""
self.renew_account = None
self.renew_guest = None
self._renewing = False
self._renew_blocked: set[str] = set()
self.play_line = ""
self.api_lines: list[str] = []
self.host = DEFAULT_HOST
self.profile: dict = {}
self._load()
@@ -79,9 +116,14 @@ class HuangdouClient:
if isinstance(guest_info, dict) and guest_info:
self.guest_device_info = dict(guest_info)
self.token = str(data.get("token") or "")
self.user_id = str(data.get("user_id") or "")
self.account_token = str(data.get("account_token") or "")
self.account_user_id = str(data.get("account_user_id") or "")
self.account_username = str(data.get("account_username") or "")
self.play_line = str(data.get("play_line") or "")
lines = data.get("api_lines")
if isinstance(lines, list):
self.api_lines = [str(item).rstrip("/") for item in lines if str(item).startswith("https://")]
host = str(data.get("host") or "")
if host.startswith("http://") or host.startswith("https://"):
self.host = host.rstrip("/")
@@ -100,9 +142,12 @@ class HuangdouClient:
"guest_session_id": self.guest_session_id,
"guest_device_info": self.guest_device_info,
"token": self.token,
"user_id": self.user_id,
"account_token": self.account_token,
"account_user_id": self.account_user_id,
"account_username": self.account_username,
"play_line": self.play_line,
"api_lines": self.api_lines,
"host": self.host,
"profile": self.profile,
}
@@ -150,6 +195,7 @@ class HuangdouClient:
self.guest_session_id = session_id_of("")
self.guest_device_info = self._new_device_info()
self.token = ""
self.user_id = ""
self.save()
def roll_account_fingerprint(self) -> None:
@@ -160,6 +206,7 @@ class HuangdouClient:
self.device_info = info
self.device_info_source = "fixed"
self.account_token = ""
self.account_user_id = ""
self.save()
def clear_token(self) -> None:
@@ -168,7 +215,9 @@ class HuangdouClient:
self.guest_session_id = ""
self.guest_device_info = {}
self.account_token = ""
self.account_user_id = ""
self.account_username = ""
self.user_id = ""
self.profile = {}
self.save()
@@ -180,26 +229,71 @@ class HuangdouClient:
return self.host
def request(self, path: str, data: dict | None = None, *, auth: bool = True, identity: str = "guest") -> dict | list | None:
try:
return self._dispatch(path, data, auth=auth, identity=identity)
except TokenExpired:
if not auth or self._renewing or identity in self._renew_blocked:
raise
self._renewing = True
try:
renew = self.renew_account if identity == "account" else self.renew_guest
renewed = bool(renew and renew())
finally:
self._renewing = False
if not renewed:
self._renew_blocked.add(identity)
raise
self._renew_blocked.discard(identity)
return self._dispatch(path, data, auth=auth, identity=identity)
def _dispatch(self, path: str, data: dict | None, *, auth: bool, identity: str) -> dict | list | None:
token, device_id, session_id, info = self._identity(identity, auth)
user_agent = str((info or {}).get("userAgent") or USER_AGENT)
last_error: Exception | None = None
for _ in range(2):
try:
return self._call(
self.host,
path,
data or {},
token=token,
device_id=device_id,
session_id=session_id,
user_agent=user_agent,
)
except (TokenExpired, ApiError):
raise
except RuntimeError as exc:
last_error = exc
hosts = [self.host] if token else self._request_hosts()
for host in hosts:
for _ in range(2):
try:
payload = self._call(
host,
path,
data or {},
token=self._presented_token(token, identity) if auth else "",
device_id=device_id,
session_id=session_id,
user_agent=user_agent,
)
if host != self.host:
self.host = host
self.save()
return payload
except (TokenExpired, ApiError):
raise
except RuntimeError as exc:
last_error = exc
if not _connection_error(exc):
raise
raise last_error or RuntimeError("网络请求异常")
def _presented_token(self, token: str, identity: str) -> str:
if identity == "account":
user_id = self.account_user_id
if not user_id and self.account_token:
profile = self.profile if isinstance(self.profile, dict) else {}
if str(profile.get("has_login") or "") == "1":
user_id = str(profile.get("id") or "")
else:
user_id = self.user_id
return present_token(token, user_id)
def _request_hosts(self) -> list[str]:
hosts = []
for host in [self.host, *self.api_lines]:
text = str(host or "").rstrip("/")
if text.startswith("https://") and text not in hosts:
hosts.append(text)
return hosts or [self.host]
def _identity(self, identity: str, auth: bool) -> tuple[str, str, str, dict]:
if identity == "account":
self._ensure_fingerprint()
@@ -251,6 +345,8 @@ class HuangdouClient:
try:
response = http.send("POST", url, headers=headers, content=encrypt_body(body, request_id), timeout=30.0)
except Exception as exc:
if _connection_error(exc):
raise RuntimeError("连接中断,请再试一次") from exc
raise RuntimeError(f"请求失败: {exc}") from exc
if response.status_code != 200:
raise RuntimeError(f"网络请求异常 ({response.status_code})")