Files
RaptDramaDump/server/services/huangdou/client.py
T

372 lines
13 KiB
Python

import json
import time
from pathlib import Path
from server.services.http import http
from server.services.huangdou.crypto import (
APP_VERSION,
DEVICE_TYPE,
LANG,
USER_AGENT,
decrypt_body,
encrypt_body,
new_uuid,
session_id_of,
sign_header,
)
ROOT = Path(__file__).resolve().parents[3]
STATE_DIR = ROOT / "cache" / "huangdou"
SESSION_PATH = STATE_DIR / "session.json"
DEFAULT_HOST = "https://pmihlvee.cc"
LINE_CODE = "china_1"
DEFAULT_DEVICE_INFO = {
"browserName": "Chrome",
"language": LANG,
"userAgent": USER_AGENT,
"platform": "Win32",
}
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)
self.code = code
class HuangdouClient:
def __init__(self) -> None:
self.device_id = ""
self.session_id = ""
self.device_info: dict = {}
self.device_info_source = ""
self.guest_device_id = ""
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()
self._ensure_fingerprint()
def _load(self) -> None:
if not SESSION_PATH.is_file():
return
try:
data = json.loads(SESSION_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return
if not isinstance(data, dict):
return
self.device_id = str(data.get("device_id") or self.device_id)
self.session_id = str(data.get("session_id") or self.session_id)
info = data.get("device_info")
if isinstance(info, dict) and info:
self.device_info = dict(info)
self.device_info_source = str(data.get("device_info_source") or "")
self.guest_device_id = str(data.get("guest_device_id") or "")
self.guest_session_id = str(data.get("guest_session_id") or "")
guest_info = data.get("guest_device_info")
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("/")
profile = data.get("profile")
if isinstance(profile, dict):
self.profile = profile
def save(self) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
payload = {
"device_id": self.device_id,
"session_id": self.session_id,
"device_info": self.device_info,
"device_info_source": self.device_info_source,
"guest_device_id": self.guest_device_id,
"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,
}
temporary = SESSION_PATH.with_suffix(".json.tmp")
temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
temporary.replace(SESSION_PATH)
def _ensure_fingerprint(self) -> None:
changed = False
if not self.device_id:
self.device_id = new_uuid()
changed = True
if not self.session_id:
self.session_id = session_id_of("")
changed = True
if not self.device_info:
self.device_info = dict(DEFAULT_DEVICE_INFO)
self.device_info_source = "default"
changed = True
if changed:
self.save()
def _new_device_info(self) -> dict:
return dict(self.device_info) if self.device_info else dict(DEFAULT_DEVICE_INFO)
def adopt_browser_fingerprint(self, info: dict) -> bool:
self._ensure_fingerprint()
if self.device_info_source in {"browser", "fixed"}:
return False
cleaned = {
"browserName": str((info or {}).get("browserName") or "").strip() or "Chrome",
"language": str((info or {}).get("language") or "").strip() or LANG,
"userAgent": str((info or {}).get("userAgent") or "").strip(),
"platform": str((info or {}).get("platform") or "").strip() or "Win32",
}
if not cleaned["userAgent"]:
return False
self.device_info = cleaned
self.device_info_source = "browser"
self.save()
return True
def roll_guest_fingerprint(self) -> None:
self.guest_device_id = new_uuid()
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:
self._ensure_fingerprint()
info = dict(self.device_info) if self.device_info else dict(DEFAULT_DEVICE_INFO)
self.device_id = new_uuid()
self.session_id = session_id_of("")
self.device_info = info
self.device_info_source = "fixed"
self.account_token = ""
self.account_user_id = ""
self.save()
def clear_token(self) -> None:
self.token = ""
self.guest_device_id = ""
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()
def set_host(self, host: str) -> str:
text = normalize_host(host)
if text:
self.host = text
self.save()
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
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()
token = self.account_token if auth else ""
return token, self.device_id, self.session_id, self.device_info
if not self.guest_device_id or not self.guest_session_id:
self.roll_guest_fingerprint()
token = self.token if auth else ""
return token, self.guest_device_id, self.guest_session_id, self.guest_device_info
def _call(
self,
host: str,
path: str,
data: dict,
*,
token: str,
device_id: str,
session_id: str,
user_agent: str,
) -> dict | list | None:
url = host.rstrip("/") + "/api" + path
request_id = new_uuid()
now = str(int(time.time()))
body = {
"token": token,
"deviceId": device_id,
"data": data,
}
headers = {
"Accept": "*/*",
"Accept-Language": LANG,
"Content-Type": "application/x-www-form-urlencoded",
"Origin": host,
"Referer": host + "/",
"User-Agent": user_agent,
"version": APP_VERSION,
"deviceType": DEVICE_TYPE,
"time": now,
"sign": sign_header(session_id, request_id, now, url),
"requestId": request_id,
"sessionId": session_id,
"deviceBrand": "",
"deviceModel": "",
"systemName": "",
"systemVersion": "",
"X-Lang": LANG,
}
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})")
parsed = decrypt_body(response.content, request_id)
if parsed.get("status") == "n":
code = parsed.get("errorCode")
if str(code) == "2002":
raise TokenExpired(str(parsed.get("error") or "登录已失效"))
raise ApiError(str(parsed.get("error") or "网络请求异常"), code)
return parsed.get("data")
def normalize_host(host: str) -> str:
text = (host or "").strip().rstrip("/")
if text and "://" not in text:
text = "https://" + text
if text and not (text.startswith("https://") or text.startswith("http://")):
raise RuntimeError("域名需要以 http 或 https 开头")
return text
client = HuangdouClient()