import json import secrets import subprocess from pathlib import Path from server.services.dramabox.client import client from server.services.dramabox.locales import DEFAULT_LANGUAGE, public_list, resolve def languages() -> list[dict]: return public_list() def enter(language: str = "") -> dict: from server.services.dramabox.app_api import ensure_guest ensure_guest() if not client.has_guest(): raise RuntimeError("没有拿到访客身份,请检查网络后重试") return client.enter(language or client.language or DEFAULT_LANGUAGE) def import_adb(serial: str, language: str = "") -> dict: from server.services.dramabox.app_device import read_app_login return _install_app_login(read_app_login(serial), language) _CREDENTIAL_KIND = "dramabox-login" _CREDENTIAL_VERSION = 1 _CREDENTIAL_FIELDS = ( "token", "device_id", "android_id", "user_id", "name", "vip", "cid", "nchid", "mchid", "mbid", "language", "current_language", "country_code", "install_time", "instance_id", "device_score", "lat", "afid", "brand", "model", "manufacturer", "os_version", "build", "locale", "resolution", ) def export_credential() -> dict: if not client.has_app(): raise RuntimeError("还没有可导出的登录凭据") profile = client.profile if isinstance(client.profile, dict) else {} app = {} for key in _CREDENTIAL_FIELDS: if key == "name": value = str(profile.get("nickname") or profile.get("username") or client.app.get("name") or "") elif key == "vip": value = bool(profile.get("badge")) or client.app.get("vip") is True else: value = client.app.get(key) if value not in (None, ""): app[key] = value return {"kind": _CREDENTIAL_KIND, "version": _CREDENTIAL_VERSION, "app": app} def save_credential_file() -> dict: document = export_credential() chosen = _pick_credential_path() if not chosen: return {"path": ""} path = Path(chosen) if path.suffix.lower() != ".json": path = path.with_suffix(".json") path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(document, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") return {"path": str(path)} def _pick_credential_path() -> str: script = """ Add-Type -AssemblyName System.Windows.Forms $owner = New-Object System.Windows.Forms.Form $owner.TopMost = $true $owner.ShowInTaskbar = $false $owner.Opacity = 0 $owner.Show() $owner.Activate() $dialog = New-Object System.Windows.Forms.SaveFileDialog $dialog.Title = '导出登录凭据' $dialog.Filter = 'JSON 文件 (*.json)|*.json' $dialog.FileName = 'dramabox-login.json' $dialog.DefaultExt = 'json' $dialog.AddExtension = $true $dialog.OverwritePrompt = $true $downloads = Join-Path $env:USERPROFILE 'Downloads' if (Test-Path $downloads) { $dialog.InitialDirectory = $downloads } $result = $dialog.ShowDialog($owner) $owner.Close() if ($result -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false [Console]::Out.WriteLine($dialog.FileName) } """ completed = subprocess.run( ["powershell", "-NoProfile", "-STA", "-Command", script], capture_output=True, text=True, encoding="utf-8", check=False, ) return (completed.stdout or "").strip() def import_credential(payload: dict, language: str = "") -> dict: return _install_app_login(_credential_record(payload), language) def _install_app_login(record: dict, language: str = "") -> dict: try: locale = resolve(language or record.get("language") or client.language or DEFAULT_LANGUAGE) except RuntimeError: locale = resolve(DEFAULT_LANGUAGE) previous = { "token": client.token, "language": client.language, "app": dict(client.app), "profile": dict(client.profile) if isinstance(client.profile, dict) else {}, } if not client.token: client.token = secrets.token_hex(16) client.language = locale["id"] client.app = {key: value for key, value in record.items() if key not in {"name", "vip"}} client.app["language"] = locale["id"] client.app["current_language"] = locale["id"] client.profile = _profile_from_record(record, locale) client.save() try: _confirm_account(locale) except RuntimeError: client.token = previous["token"] client.language = previous["language"] client.app = previous["app"] client.profile = previous["profile"] client.save() raise from server.services.dramabox.app_api import ensure_guest ensure_guest() return {"token": client.token, "profile": client.profile} def _confirm_account(locale: dict) -> None: from server.services.dramabox.app_api import refresh_account try: fresh = refresh_account(client.app) except RuntimeError as exc: text = str(exc).strip() if "失效" in text: raise if any(word in text for word in ("拦截", "没有响应", "没有返回", "网络")): raise RuntimeError("暂时读不到个人信息,请检查网络后再导入") from exc raise RuntimeError("登录凭据已失效") from exc if fresh.get("token"): client.app["token"] = fresh["token"] if fresh.get("user_id"): client.app["user_id"] = fresh["user_id"] record = dict(client.app) record["name"] = fresh.get("name") or "" record["vip"] = fresh.get("vip") is True client.profile = _profile_from_record(record, locale) client.save() def _profile_from_record(record: dict, locale: dict) -> dict: nickname = str(record.get("name") or record.get("user_id") or "DramaBox") return { "id": record.get("user_id") or "", "username": nickname, "nickname": nickname, "email": "", "phone": "", "badge": "VIP" if record.get("vip") else "", "vipday": 1 if record.get("vip") else 0, "score": 0, "watched": 0, "rewards": 0, "login_day": 0, "country": locale.get("country") or "", "language": locale.get("language") or "", "native": locale.get("native") or "", "locale": locale.get("id") or "", "loginType": "app", "has_login": "1", "app_login": "1", "avatarNumUrl": "", } def _credential_record(payload: dict) -> dict: if not isinstance(payload, dict) or payload.get("kind") != _CREDENTIAL_KIND: raise RuntimeError("这不是 DramaBox 登录凭据文件") if int(payload.get("version") or 0) != _CREDENTIAL_VERSION: raise RuntimeError("这份凭据文件无法识别") app = payload.get("app") if not isinstance(app, dict): raise RuntimeError("凭据文件里没有登录信息") token = str(app.get("token") or "").strip() if token and not token.startswith("Bearer "): token = f"Bearer {token}" record = {key: app.get(key) for key in _CREDENTIAL_FIELDS} record["token"] = token record["vip"] = app.get("vip") is True or str(app.get("vip") or "").lower() in {"1", "true", "y", "yes"} missing = [name for name in ("token", "device_id", "android_id", "user_id") if not str(record.get(name) or "").strip()] if missing: raise RuntimeError("凭据文件不完整") return record def resume() -> dict: if not client.token or not client.profile: raise RuntimeError("还没有登录") return {"token": client.token, "profile": client.profile} def current(token: str) -> dict: token = (token or "").strip() if not token: raise RuntimeError("请先选择地区") if token != client.token or not client.profile: raise RuntimeError("登录已失效") return {"token": client.token, "profile": client.profile} def logout(token: str) -> None: if token and token == client.token: client.clear() return if not token: client.clear()