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 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.account_token = "" self.account_username = "" 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.account_token = str(data.get("account_token") or "") self.account_username = str(data.get("account_username") or "") 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, "account_token": self.account_token, "account_username": self.account_username, "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.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.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_username = "" 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: 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 raise last_error or RuntimeError("网络请求异常") 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: 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()