From 3c2105c786bbf43f129e81f9d0524edf35d89cd1 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 25 Oct 2026 01:58:29 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=B0=86=E5=B7=A5=E5=85=B7=E6=9B=B4?= =?UTF-8?q?=E5=90=8D=E4=B8=BA=20VideosDownTools=EF=BC=8C=E5=B9=B6=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E9=BB=84=E8=B1=86=E7=99=BB=E5=BD=95=E4=B8=8E=E6=B8=85?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 +- package-lock.json | 4 +- package.json | 2 +- scripts/package.py | 6 +- server/app.py | 2 +- server/routes/huangdou.py | 95 +++++++- server/services/huangdou/accounts.py | 71 ++++++ server/services/huangdou/api.py | 59 ++++- server/services/huangdou/client.py | 182 ++++++++++++--- server/services/huangdou/coins.py | 109 +++++++++ server/services/huangdou/downloads.py | 27 ++- server/services/huangdou/login.py | 123 ++++++++-- server/services/huangdou/playlist.py | 253 +++++++++++++++------ src-tauri/Cargo.lock | 26 +-- src-tauri/Cargo.toml | 10 +- src-tauri/splash/index.html | 4 +- src-tauri/src/lib.rs | 2 +- src-tauri/src/main.rs | 2 +- src-tauri/tauri.conf.json | 6 +- tests/test_huangdou_coins.py | 130 +++++++++++ ui/index.html | 2 +- ui/package-lock.json | 4 +- ui/package.json | 2 +- ui/src/App.vue | 309 +++++++++++++++++++++++++- ui/src/views/PlayerPage.vue | 10 +- ui/src/views/SettingsPanel.vue | 2 - ui/src/views/VideoListPage.vue | 134 +++++++---- 27 files changed, 1349 insertions(+), 237 deletions(-) create mode 100644 server/services/huangdou/accounts.py create mode 100644 server/services/huangdou/coins.py create mode 100644 tests/test_huangdou_coins.py diff --git a/README.md b/README.md index 682c40a..6474365 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -# RaptDrama Download Tools +# VideosDownTools -Windows 桌面程序,用来登录 RaptDrama、浏览剧目、播放已缓存的分集,以及把剧集下载成 MP4。 +Windows 桌面程序,用来登录 RaptDrama、黄豆短剧和 DramaBox,浏览剧目、播放分集,以及把剧集下载成 MP4。 ## 使用分发包 -1. 解压 `dist/RaptDrama-Download-Tools-windows-x64.zip`。 -2. 进入 `RaptDrama-Download-Tools`,运行 `raptdrama.exe`。 +1. 解压 `dist/VideosDownTools-windows-x64.zip`。 +2. 进入 `VideosDownTools`,运行 `VideosDownTools.exe`。 3. 压缩包里已经带有 Python、adb、ffmpeg 和 WebView2 离线安装包。本机如果还没有 WebView2,程序启动时会静默安装。 程序会在自己的目录里写入: @@ -46,6 +46,6 @@ python scripts\package.py - `tools/ffmpeg/ffmpeg.exe` - `vendor/webview2/MicrosoftEdgeWebView2RuntimeInstallerX64.exe` -adb 和 WebView2 打包时不再下载。完成后得到 `dist/RaptDrama-Download-Tools-windows-x64.zip`。 +adb 和 WebView2 打包时不再下载。完成后得到 `dist/VideosDownTools-windows-x64.zip`。 打包脚本是 Python,公共步骤和平台相关的运行时是分开的。目前只接好了 Windows。macOS 和 Linux 以后把对应文件放进 `vendor` 即可。 diff --git a/package-lock.json b/package-lock.json index 89970de..01280e2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { - "name": "raptdrama", + "name": "videosdowntools", "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "raptdrama", + "name": "videosdowntools", "version": "0.1.0", "devDependencies": { "@tauri-apps/cli": "^2" diff --git a/package.json b/package.json index 522c55e..48a168f 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "raptdrama", + "name": "videosdowntools", "private": true, "version": "0.1.0", "scripts": { diff --git a/scripts/package.py b/scripts/package.py index 7cd8cc3..3ee23a5 100644 --- a/scripts/package.py +++ b/scripts/package.py @@ -23,7 +23,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] DIST = ROOT / "dist" CACHE = DIST / "cache" -STAGE_NAME = "RaptDrama-Download-Tools" +STAGE_NAME = "VideosDownTools" PYTHON_VERSION = "3.13.15" PYTHON_EMBED_URL = ( @@ -50,7 +50,7 @@ def download(url: str, dest: Path) -> None: dest.parent.mkdir(parents=True, exist_ok=True) temporary = dest.with_suffix(dest.suffix + ".part") log(f"下载 {url}") - request = urllib.request.Request(url, headers={"User-Agent": "RaptDrama"}) + request = urllib.request.Request(url, headers={"User-Agent": "VideosDownTools"}) try: with urllib.request.urlopen(request, timeout=120) as response, temporary.open("wb") as handle: total = int(response.headers.get("Content-Length") or 0) @@ -91,7 +91,7 @@ def build_desktop() -> Path: text=True, ) target = Path(json.loads(meta)["target_directory"]) / "release" - name = "raptdrama.exe" if sys.platform == "win32" else "raptdrama" + name = "VideosDownTools.exe" if sys.platform == "win32" else "VideosDownTools" exe = target / name if not exe.is_file(): raise SystemExit(f"没有找到桌面程序 {exe}") diff --git a/server/app.py b/server/app.py index 1510d65..20cef3e 100644 --- a/server/app.py +++ b/server/app.py @@ -23,7 +23,7 @@ from server.services.dramabox.downloads import downloads as dramabox_downloads def create_app() -> FastAPI: - app = FastAPI(title="RaptDrama") + app = FastAPI(title="VideosDownTools") app.add_middleware( CORSMiddleware, allow_origins=["*"], diff --git a/server/routes/huangdou.py b/server/routes/huangdou.py index 320897b..34eb2db 100644 --- a/server/routes/huangdou.py +++ b/server/routes/huangdou.py @@ -11,10 +11,12 @@ from server.services.http import http from server.services.huangdou import catalog as hd_catalog from server.services.huangdou import login as hd_login from server.services.huangdou import playlist as hd_playlist +from server.services.huangdou import accounts as hd_accounts from server.services.huangdou.client import client from server.services.huangdou.covers import covers from server.services.huangdou.crypto import USER_AGENT from server.services.huangdou.downloads import downloads as hd_downloads +from server.services.huangdou.downloads import enqueue_download from server.services.playlist import is_direct_media router = APIRouter(prefix="/api/huangdou") @@ -24,6 +26,37 @@ class TokenBody(BaseModel): token: str = "" refresh: bool = False keyword: str = "" + host: str = "" + + +class FingerprintBody(BaseModel): + browserName: str = "" + language: str = "" + userAgent: str = "" + platform: str = "" + + +class SavedAccountBody(BaseModel): + username: str = "" + password: str = "" + nickname: str = "" + + +class SavedAccountsBody(BaseModel): + accounts: list[SavedAccountBody] = [] + + +class LoginBody(BaseModel): + host: str = "" + username: str = "" + password: str = "" + + +class AccountBody(BaseModel): + token: str = "" + username: str = "" + password: str = "" + rotate_fingerprint: bool = False class DownloadItem(BaseModel): @@ -34,6 +67,7 @@ class DownloadItem(BaseModel): class DownloadStartBody(BaseModel): token: str = "" + download_points: bool = False items: list[DownloadItem] = [] @@ -59,9 +93,52 @@ def _require_token(token: str) -> None: client.token = token +@router.post("/fingerprint") +def adopt_fingerprint(body: FingerprintBody): + client.adopt_browser_fingerprint(body.model_dump()) + return {"ok": True} + + +@router.post("/fingerprint/roll") +def roll_fingerprint(): + client.roll_account_fingerprint() + return {"ok": True} + + +@router.get("/accounts") +def list_accounts(): + return {"accounts": hd_accounts.load()} + + +@router.put("/accounts") +def save_accounts(body: SavedAccountsBody): + return {"accounts": hd_accounts.replace([item.model_dump() for item in body.accounts])} + + +@router.post("/login") +def login(body: LoginBody): + def action(): + entered = hd_login.enter(body.host) + if body.username.strip() and body.password: + return hd_login.login_account(body.username, body.password) + return entered + + return call(action) + + @router.post("/login/device") -def login_device(): - return call(hd_login.enter) +def login_device(body: TokenBody | None = None): + host = body.host if body else "" + return call(lambda: hd_login.enter(host)) + + +@router.post("/login/account") +def login_account(body: AccountBody): + def action(): + _require_token(body.token) + return hd_login.login_account(body.username, body.password, body.rotate_fingerprint) + + return call(action) @router.post("/resume") @@ -131,7 +208,8 @@ def list_episodes(body: PlayBody): "cid": ep["cid"], "idx": ep["idx"], "title": ep["title"], - "playable": bool(ep.get("src")), + "playable": bool(ep.get("playable")), + "points": int(ep.get("points") or 0), "type": ep.get("type") or "", "media": "file" if (ep.get("src_kind") == "file" or is_direct_media(ep.get("src") or "")) else "hls", "is_preview": bool(ep.get("is_preview")), @@ -156,7 +234,7 @@ def _public_url(url: str) -> str: def play_segment(url: str): target = _public_url(url) try: - upstream = http.open_stream(target, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"}) + upstream = http.open_stream(target, headers={"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"}) except (httpx.HTTPError, TimeoutError, OSError, RuntimeError) as exc: raise HTTPException(status_code=502, detail="分片读取失败") from exc media = upstream.headers.get("content-type", "video/mp2t").split(";", 1)[0].strip() or "video/mp2t" @@ -179,7 +257,7 @@ def play_file(vid: str, cid: int): if not src: raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址") try: - upstream = http.open_stream(src, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"}) + upstream = http.open_stream(src, headers={"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"}) except (httpx.HTTPError, TimeoutError, OSError, RuntimeError) as exc: raise HTTPException(status_code=502, detail="分片读取失败") from exc media = upstream.headers.get("content-type", "video/mp4").split(";", 1)[0].strip() or "video/mp4" @@ -236,7 +314,12 @@ def list_downloads(): def start_downloads(body: DownloadStartBody): def action(): _require_token(body.token) - return hd_downloads.enqueue(body.token, None, [item.model_dump() for item in body.items]) + hd_downloads._headers["Referer"] = client.host.rstrip("/") + "/" + return enqueue_download( + body.token, + [item.model_dump() for item in body.items], + body.download_points, + ) return call(action) diff --git a/server/services/huangdou/accounts.py b/server/services/huangdou/accounts.py new file mode 100644 index 0000000..437d461 --- /dev/null +++ b/server/services/huangdou/accounts.py @@ -0,0 +1,71 @@ +import json +import threading +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +PATH = ROOT / "cache" / "huangdou" / "accounts.json" +_lock = threading.Lock() + + +def load() -> list[dict]: + with _lock: + return _parse() + + +def replace(rows: list) -> list[dict]: + cleaned = [] + seen: set[str] = set() + if isinstance(rows, list): + for item in rows: + if not isinstance(item, dict): + continue + username = str(item.get("username") or "").strip() + password = str(item.get("password") or "") + if not username or not password or username in seen: + continue + seen.add(username) + cleaned.append( + { + "username": username, + "password": password, + "nickname": str(item.get("nickname") or "").strip(), + } + ) + if len(cleaned) >= 30: + break + with _lock: + PATH.parent.mkdir(parents=True, exist_ok=True) + temporary = PATH.with_suffix(".json.tmp") + temporary.write_text(json.dumps({"accounts": cleaned}, ensure_ascii=False), encoding="utf-8") + temporary.replace(PATH) + return cleaned + + +def _parse() -> list[dict]: + if not PATH.is_file(): + return [] + try: + data = json.loads(PATH.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return [] + rows = data.get("accounts") if isinstance(data, dict) else None + if not isinstance(rows, list): + return [] + cleaned = [] + seen: set[str] = set() + for item in rows: + if not isinstance(item, dict): + continue + username = str(item.get("username") or "").strip() + password = str(item.get("password") or "") + if not username or not password or username in seen: + continue + seen.add(username) + cleaned.append( + { + "username": username, + "password": password, + "nickname": str(item.get("nickname") or "").strip(), + } + ) + return cleaned diff --git a/server/services/huangdou/api.py b/server/services/huangdou/api.py index 41ca536..aa87689 100644 --- a/server/services/huangdou/api.py +++ b/server/services/huangdou/api.py @@ -2,7 +2,16 @@ from server.services.huangdou.client import ApiError, TokenExpired, client from server.services.huangdou.crypto import USER_AGENT -def device_info() -> dict: +def device_info(identity: str = "guest") -> dict: + if identity == "account": + client._ensure_fingerprint() + info = client.device_info + else: + if not client.guest_device_id: + client.roll_guest_fingerprint() + info = client.guest_device_info + if isinstance(info, dict) and info: + return dict(info) return { "browserName": "Chrome", "language": "zh-CN", @@ -33,8 +42,34 @@ def login_device(*, force_new: bool = False) -> dict: return data -def user_info() -> dict: - data = client.request("/user/info", {}, auth=True) +def login_username(username: str, password: str, channel_code: str = "") -> dict: + data = client.request( + "/login/username", + { + "line_code": "china_1", + "share_code": "", + "channel_code": channel_code, + "username": username.strip(), + "password": password, + "clipboard_text": "", + "device_info": device_info("account"), + }, + auth=False, + identity="account", + ) + if not isinstance(data, dict): + raise RuntimeError("账号登录没有返回数据") + token = str(data.get("token") or "").strip() + if not token: + raise RuntimeError("账号登录没有返回 token") + client.account_token = token + client.account_username = username.strip() + client.save() + return data + + +def user_info(*, identity: str = "guest") -> dict: + data = client.request("/user/info", {}, auth=True, identity=identity) return data if isinstance(data, dict) else {} @@ -110,13 +145,21 @@ def limited_free(page: int = 1, size: int = 50) -> dict: return data if isinstance(data, dict) else {} -def drama_detail(drama_id: str) -> dict: - data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True) +def drama_detail(drama_id: str, *, identity: str = "guest") -> dict: + data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True, identity=identity) return data if isinstance(data, dict) else {} -def drama_play(drama_id: str, seq: int) -> dict: - data = client.request("/drama/play", {"id": str(drama_id), "seq": str(seq)}, auth=True) +def drama_play(drama_id: str, seq: int, *, identity: str = "guest") -> dict: + data = client.request("/drama/play", {"id": str(drama_id), "seq": str(seq)}, auth=True, identity=identity) + return data if isinstance(data, dict) else {} + + +def drama_buy(drama_id: str, seq: int, method: str = "") -> dict: + body = {"id": str(drama_id), "seq": str(seq)} + if method: + body["method"] = method + data = client.request("/drama/doBuy", body, auth=True, identity="account") return data if isinstance(data, dict) else {} @@ -141,7 +184,9 @@ __all__ = [ "drama_list", "drama_play", "limited_free", + "drama_buy", "login_device", + "login_username", "nav_block", "nav_list", "system_info", diff --git a/server/services/huangdou/client.py b/server/services/huangdou/client.py index 3735152..a6c41db 100644 --- a/server/services/huangdou/client.py +++ b/server/services/huangdou/client.py @@ -19,21 +19,15 @@ ROOT = Path(__file__).resolve().parents[3] STATE_DIR = ROOT / "cache" / "huangdou" SESSION_PATH = STATE_DIR / "session.json" -HOSTS = ( - "https://pmihlvee.cc", - "https://sxqirtho.top", - "https://qicuknlj.top", - "https://ferncider.cc", - "https://hvthtcpa.top", - "https://onyxripple.cc", - "https://vivifable.top", - "https://kucvcxrv.cc", - "https://larkgarden.top", - "https://niniharbor.top", - "https://larksummit.icu", -) +DEFAULT_HOST = "https://pmihlvee.cc" LINE_CODE = "china_1" +DEFAULT_DEVICE_INFO = { + "browserName": "Chrome", + "language": LANG, + "userAgent": USER_AGENT, + "platform": "Win32", +} class TokenExpired(RuntimeError): @@ -48,12 +42,20 @@ class ApiError(RuntimeError): class HuangdouClient: def __init__(self) -> None: - self.device_id = new_uuid() - self.session_id = session_id_of("") + 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.host = HOSTS[0] + 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(): @@ -65,10 +67,21 @@ class HuangdouClient: if not isinstance(data, dict): return self.device_id = str(data.get("device_id") or self.device_id) - self.session_id = session_id_of(str(data.get("session_id") or self.session_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("https://"): + if host.startswith("http://") or host.startswith("https://"): self.host = host.rstrip("/") profile = data.get("profile") if isinstance(profile, dict): @@ -79,7 +92,14 @@ class HuangdouClient: 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, } @@ -87,32 +107,123 @@ class HuangdouClient: 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 request(self, path: str, data: dict | None = None, *, auth: bool = True) -> dict | list | None: + 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 - hosts = [self.host, *[item for item in HOSTS if item != self.host]] - for host in hosts: + for _ in range(2): try: - payload = self._call(host, path, data or {}, auth=auth) - self.host = host - return payload + 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 _call(self, host: str, path: str, data: dict, *, auth: bool) -> dict | list | None: + 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": self.token if auth else "", - "deviceId": self.device_id, + "token": token, + "deviceId": device_id, "data": data, } headers = { @@ -121,13 +232,13 @@ class HuangdouClient: "Content-Type": "application/x-www-form-urlencoded", "Origin": host, "Referer": host + "/", - "User-Agent": USER_AGENT, + "User-Agent": user_agent, "version": APP_VERSION, "deviceType": DEVICE_TYPE, "time": now, - "sign": sign_header(self.session_id, request_id, now, url), + "sign": sign_header(session_id, request_id, now, url), "requestId": request_id, - "sessionId": self.session_id, + "sessionId": session_id, "deviceBrand": "", "deviceModel": "", "systemName": "", @@ -144,9 +255,18 @@ class HuangdouClient: if parsed.get("status") == "n": code = parsed.get("errorCode") if str(code) == "2002": - raise TokenExpired("登录已失效") + 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() diff --git a/server/services/huangdou/coins.py b/server/services/huangdou/coins.py new file mode 100644 index 0000000..c2dd075 --- /dev/null +++ b/server/services/huangdou/coins.py @@ -0,0 +1,109 @@ +PAID_TYPES = {"coin", "coins", "point", "points", "pay", "money"} +VIP_TYPES = {"vip"} +FREE_TYPES = {"", "free", "0", "none"} + + +def episode_kind(item: dict) -> str: + return str(item.get("type") or "free").strip().lower() + + +def already_bought(item: dict) -> bool: + value = item.get("is_buy") + if value is None or value is True: + return True + return str(value).strip().lower() in {"1", "y", "yes", "true"} + + +def price_of(item: dict) -> int: + for key in ("price", "points", "point", "integral"): + number = _int(item.get(key)) + if number: + return number + return 0 + + +def paid_cost(item: dict) -> int: + if episode_kind(item) in FREE_TYPES or already_bought(item): + return 0 + return price_of(item) + + +def episode_note(item: dict, *, account_vip: bool) -> tuple[bool, str, int]: + cost = paid_cost(item) + if cost > 0: + return False, f"{cost} 积分", cost + if episode_kind(item) in VIP_TYPES and not already_bought(item) and not account_vip: + return False, "需要 VIP", 0 + return True, "", 0 + + +def public_lock_reason(item: dict, message: str) -> str: + price = price_of(item) or _int(item.get("points")) + text = (message or "").strip() + if not already_bought(item) and price > 0: + return f"{price} 积分" + if any(word in text for word in ("不含", "权益", "解锁")): + return "这一集暂时不能播放" + return text or "这一集暂时不能播放" + + +def summarize(rows) -> dict: + coins = 0 + coin_count = 0 + free_count = 0 + vip_count = 0 + if isinstance(rows, list): + for item in rows: + if not isinstance(item, dict): + continue + cost = paid_cost(item) + if cost > 0: + coins += cost + coin_count += 1 + continue + kind = episode_kind(item) + if kind in VIP_TYPES: + vip_count += 1 + else: + free_count += 1 + return { + "coins": coins, + "coin_count": coin_count, + "free_count": free_count, + "vip_count": vip_count, + } + + +def allow_payment(pay: bool, has_account: bool, balance: int, coins: int) -> bool: + return bool(pay and has_account and coins > 0 and balance >= coins) + + +def keep_episode(item: dict, *, allow_paid: bool, account_vip: bool) -> bool: + if paid_cost(item) > 0: + return allow_paid + if episode_kind(item) in VIP_TYPES and not already_bought(item): + return account_vip + return True + + +def buy_method(item: dict) -> str: + methods = item.get("methods") + if not isinstance(methods, list): + return "" + for method in methods: + if isinstance(method, str) and method.strip(): + return method.strip() + if isinstance(method, dict): + for key in ("code", "method", "type", "id", "name"): + text = str(method.get(key) or "").strip() + if text: + return text + return "" + + +def _int(value) -> int: + try: + number = int(float(str(value))) + except (TypeError, ValueError): + return 0 + return number if number > 0 else 0 diff --git a/server/services/huangdou/downloads.py b/server/services/huangdou/downloads.py index e45cf8a..4be64db 100644 --- a/server/services/huangdou/downloads.py +++ b/server/services/huangdou/downloads.py @@ -1,3 +1,4 @@ +import threading from pathlib import Path from server.services.downloads import DownloadManager, _plain_text @@ -5,13 +6,31 @@ from server.services.huangdou import api from server.services.huangdou.client import client from server.services.huangdou.covers import covers from server.services.huangdou.crypto import USER_AGENT +from server.services.huangdou import login as hd_login from server.services.huangdou import playlist as hd_playlist +_pay_lock = threading.Lock() + ROOT = Path(__file__).resolve().parents[3] def _load_episodes(_token, _device, drama_id: str, _locale: str = "") -> list[dict]: - return hd_playlist.load_episodes(str(drama_id)) + return hd_playlist.load_for_download( + str(drama_id), + allow_paid=bool(getattr(downloads, "allow_paid", False)), + account_vip=bool(getattr(downloads, "account_vip", False)), + ) + + +def enqueue_download(token: str, items: list[dict], download_points: bool) -> dict: + with _pay_lock: + downloads.allow_paid = bool(download_points and client.account_token) + downloads.account_vip = hd_login.account_is_vip() + try: + return downloads.enqueue(token, None, items) + finally: + downloads.allow_paid = False + downloads.account_vip = False def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) -> None: @@ -20,8 +39,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) pay_type = "" free_episodes = "" vip_episodes = "" - points_price = "" - money = "" try: detail = api.drama_detail(str(drama_id)) fetched = str(detail.get("name") or "").strip() @@ -31,8 +48,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) pay_type = _field(detail.get("pay_type")) free_episodes = _field(detail.get("free_episodes")) vip_episodes = _field(detail.get("vip_episodes")) - points_price = _field(detail.get("points_price")) - money = _field(detail.get("money")) except Exception: pass lines = [ @@ -42,8 +57,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) f"付费类型: {pay_type or '—'}", f"免费集数: {free_episodes or '—'}", f"VIP 集: {vip_episodes or '—'}", - f"积分价格: {points_price or '—'}", - f"金额: {money or '—'}", "", ] (folder / "简介.txt").write_text("\n".join(lines), encoding="utf-8") diff --git a/server/services/huangdou/login.py b/server/services/huangdou/login.py index cfad214..1329e3e 100644 --- a/server/services/huangdou/login.py +++ b/server/services/huangdou/login.py @@ -3,23 +3,45 @@ from server.services.huangdou.client import TokenExpired, client from server.services.huangdou.covers import covers as huangdou_covers -def enter() -> dict: - try: - if client.token: - profile = _profile(api.user_info()) - client.profile = profile - client.save() - return {"token": client.token, "profile": profile} - except TokenExpired: - client.clear_token() - except RuntimeError: - pass +def enter(host: str = "") -> dict: + if host: + client.set_host(host) + client.account_token = "" + client.account_username = "" + client.roll_guest_fingerprint() raw = api.login_device(force_new=False) + guest = _user_from_login(raw) + if guest: + profile = _profile(guest) + profile["has_login"] = "" + profile["host"] = client.host + else: + profile = public_profile(None) + client.profile = profile + client.save() + return {"token": client.token, "profile": profile} + + +def login_account(username: str, password: str, rotate_fingerprint: bool = False) -> dict: + username = (username or "").strip() + password = password or "" + if not username or not password: + raise RuntimeError("请填写账号和密码") + if not client.token: + raise RuntimeError("请先进入") + previous = None + if rotate_fingerprint: + previous = (client.device_id, client.session_id, dict(client.device_info), client.account_token) + client.roll_account_fingerprint() try: - info = api.user_info() - except RuntimeError: - info = raw - profile = _profile(info if isinstance(info, dict) else raw) + raw = api.login_username(username, password) + info = _user_from_login(raw) or api.user_info(identity="account") + except Exception: + if previous is not None: + client.device_id, client.session_id, client.device_info, client.account_token = previous + client.save() + raise + profile = public_profile(info if isinstance(info, dict) else {}) client.profile = profile client.save() return {"token": client.token, "profile": profile} @@ -36,17 +58,76 @@ def current(token: str) -> dict: if not token: raise RuntimeError("请先登录") if token != client.token: - client.token = token - try: - profile = _profile(api.user_info()) - except TokenExpired as exc: - client.clear_token() - raise RuntimeError("登录已失效") from exc + raise RuntimeError("登录已失效") + account = _account_info() + profile = public_profile(account) client.profile = profile client.save() return {"token": client.token, "profile": profile} +def account_balance() -> int: + if not client.account_token: + return 0 + try: + info = api.user_info(identity="account") + except (TokenExpired, RuntimeError): + return _number(client.profile.get("balance") if isinstance(client.profile, dict) else 0) + return _number(info.get("balance") if isinstance(info, dict) else 0) + + +def account_is_vip() -> bool: + if not client.account_token: + return False + profile = client.profile if isinstance(client.profile, dict) else {} + return _truthy(profile.get("is_vip")) or bool(profile.get("badge")) + + +def _user_from_login(data: dict) -> dict: + if not isinstance(data, dict): + return {} + for key in ("user", "userInfo", "user_info", "info"): + nested = data.get(key) + if isinstance(nested, dict) and (nested.get("id") or nested.get("username") or nested.get("nickname")): + return nested + if data.get("id") or data.get("username") or data.get("nickname"): + return data + return {} + + +def _account_info() -> dict: + if not client.account_token: + return {} + try: + info = api.user_info(identity="account") + except TokenExpired: + client.account_token = "" + client.save() + return {} + except RuntimeError: + return {} + return info if isinstance(info, dict) else {} + + +def public_profile(account: dict | None = None) -> dict: + if account and client.account_token: + profile = _profile(account) + profile["has_login"] = "1" + profile["username"] = client.account_username or profile.get("username") or "" + else: + guest = {} + if client.token: + try: + fetched = api.user_info() + except (TokenExpired, RuntimeError): + fetched = {} + guest = fetched if isinstance(fetched, dict) else {} + profile = _profile(guest) + profile["has_login"] = "" + profile["host"] = client.host + return profile + + def logout(token: str) -> None: if token and token == client.token: client.clear_token() diff --git a/server/services/huangdou/playlist.py b/server/services/huangdou/playlist.py index 9fcd4f3..e6ce2b1 100644 --- a/server/services/huangdou/playlist.py +++ b/server/services/huangdou/playlist.py @@ -1,41 +1,70 @@ import json import re +import threading from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from urllib.parse import quote, urljoin from server.services.huangdou import api +from server.services.huangdou.client import client +from server.services.huangdou.coins import ( + PAID_TYPES, + VIP_TYPES, + already_bought, + buy_method, + episode_kind, + episode_note, + keep_episode, + price_of, + public_lock_reason, +) from server.services.http import http from server.services.huangdou.crypto import USER_AGENT from server.services.playlist import is_direct_media, looks_like_segment CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "playlists" -CDN_HEADERS = {"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"} +_cache_lock = threading.Lock() + + +def _cdn_headers() -> dict: + return {"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"} def load_episodes(drama_id: str) -> list[dict]: drama_id = str(drama_id or "").strip() if not drama_id: raise RuntimeError("没有这部剧") - cached = _read_cache(drama_id) - fresh = _fetch_episodes(drama_id) - merged, save = _merge(cached, fresh) - if save or (not cached and merged): - _write_cache(drama_id, merged) + detail = api.drama_detail(drama_id, identity=_viewer_identity()) + rows = detail.get("episodes") if isinstance(detail, dict) else None + if not isinstance(rows, list) or not rows: + raise RuntimeError("没有读到分集") + fresh = _menu_rows(rows) + if not fresh: + raise RuntimeError("没有读到分集") + merged = _keep_sources(_read_cache(drama_id), fresh) + _write_cache(drama_id, merged) return merged def episode_src(drama_id: str, cid: int) -> dict: - for ep in load_episodes(drama_id): - if int(ep.get("cid") or 0) == int(cid): - return ep - return {} + drama_id = str(drama_id or "").strip() + row = _cached_row(drama_id, cid) + if row is None: + row = _cached_row(drama_id, cid, refresh=True) + if not row: + return {} + if not row.get("playable") or row.get("src"): + return row + played = _play_rows(drama_id, [dict(row)], allow_buy=False) + updated = played[0] if played else row + _store_row(drama_id, updated) + return updated def playback_playlist(src: str) -> str: if is_direct_media(src): raise RuntimeError("这一集是整段视频") - text = http.read_text(src, headers=CDN_HEADERS) + text = http.read_text(src, headers=_cdn_headers()) variant_rel = next( (line.strip() for line in text.splitlines() if line.strip() and not line.startswith("#")), "", @@ -45,7 +74,7 @@ def playback_playlist(src: str) -> str: if looks_like_segment(variant_rel): return _rewrite_playlist(text, src) variant_url = urljoin(src, variant_rel) - return _rewrite_playlist(http.read_text(variant_url, headers=CDN_HEADERS), variant_url) + return _rewrite_playlist(http.read_text(variant_url, headers=_cdn_headers()), variant_url) def decode_key(value: str) -> bytes: @@ -122,8 +151,11 @@ def apply_hls_key(text: str, source_dir: Path, key: str) -> str: return "\n".join(result) + "\n" -def _fetch_episodes(drama_id: str) -> list[dict]: - detail = api.drama_detail(drama_id) +def load_for_download(drama_id: str, *, allow_paid: bool, account_vip: bool) -> list[dict]: + drama_id = str(drama_id or "").strip() + if not drama_id: + raise RuntimeError("没有这部剧") + detail = api.drama_detail(drama_id, identity=_viewer_identity()) rows = detail.get("episodes") if isinstance(detail, dict) else None if not isinstance(rows, list) or not rows: raise RuntimeError("没有读到分集") @@ -131,36 +163,89 @@ def _fetch_episodes(drama_id: str) -> list[dict]: for item in rows: if not isinstance(item, dict): continue - seq = _int(item.get("seq")) - if seq <= 0: + if not keep_episode(item, allow_paid=allow_paid, account_vip=account_vip): continue - kind = str(item.get("type") or "free").strip() or "free" - skeleton.append({ - "cid": seq, - "idx": seq, - "title": str(item.get("name") or f"第{seq}集").strip() or f"第{seq}集", - "src": "", - "type": kind, - "price": _int(item.get("price")), - "is_buy": item.get("is_buy") is True or item.get("is_buy") is None, - "cover": str(item.get("cover") or ""), - "duration": _int(item.get("duration")), - "methods": item.get("methods") if isinstance(item.get("methods"), list) else [], - "is_preview": False, - "preview_seconds": 0, - "preview_m3u8": "", - "hls_key": "", - "src_kind": "", - "locked_reason": "", - }) + row = _skeleton_row(item, account_vip=account_vip) + if row: + skeleton.append(row) + return _play_rows(drama_id, skeleton, allow_buy=allow_paid) + + +def _viewer_identity() -> str: + return "account" if client.account_token else "guest" + + +def _menu_rows(rows: list) -> list[dict]: + from server.services.huangdou.login import account_is_vip + + vip = account_is_vip() + skeleton = [] + for item in rows: + if not isinstance(item, dict): + continue + row = _skeleton_row(item, account_vip=vip) + if row: + skeleton.append(row) + return skeleton + + +def _skeleton_row(item: dict, *, account_vip: bool) -> dict | None: + seq = _int(item.get("seq")) + if seq <= 0: + return None + kind = str(item.get("type") or "free").strip() or "free" + playable, reason, points = episode_note(item, account_vip=account_vip) + return { + "cid": seq, + "idx": seq, + "title": str(item.get("name") or f"第{seq}集").strip() or f"第{seq}集", + "src": "", + "type": kind, + "price": price_of(item), + "points": points, + "playable": playable, + "needs_coin": points > 0, + "is_buy": item.get("is_buy"), + "cover": str(item.get("cover") or ""), + "duration": _int(item.get("duration")), + "methods": item.get("methods") if isinstance(item.get("methods"), list) else [], + "is_preview": False, + "preview_seconds": 0, + "preview_m3u8": "", + "hls_key": "", + "src_kind": "", + "locked_reason": reason, + } + + +def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[dict]: if not skeleton: - raise RuntimeError("没有读到分集") + return [] def play_one(row: dict) -> dict: + if row.get("needs_coin") and not already_bought(row): + if not allow_buy or not client.account_token: + row["src"] = "" + row["playable"] = False + row["locked_reason"] = public_lock_reason(row, row.get("locked_reason") or "") + return row + try: + api.drama_buy(drama_id, int(row["cid"]), buy_method(row)) + except RuntimeError as exc: + row["src"] = "" + row["playable"] = False + row["locked_reason"] = public_lock_reason(row, str(exc)) + return row + row["is_buy"] = True + row["needs_coin"] = False + row["points"] = 0 + identity = "account" if _uses_account(row) else "guest" try: - played = api.drama_play(drama_id, int(row["cid"])) + played = api.drama_play(drama_id, int(row["cid"]), identity=identity) except RuntimeError as exc: - row["locked_reason"] = str(exc) or "这一集暂时不能下载" + row["src"] = "" + row["playable"] = False + row["locked_reason"] = public_lock_reason(row, str(exc)) return row preview = str(played.get("preview_m3u8") or "").strip() row["hls_key"] = str(played.get("hls_key") or "").strip() @@ -171,10 +256,13 @@ def _fetch_episodes(drama_id: str) -> list[dict]: row["src"] = src row["src_kind"] = kind if src: + row["playable"] = True if kind == "file" or row["is_preview"]: row["is_preview"] = True - row["locked_reason"] = "当前账号只能下到试看" + row["locked_reason"] = "" + row["points"] = 0 else: + row["playable"] = False row["locked_reason"] = _lock_reason(row) return row @@ -190,41 +278,66 @@ def _fetch_episodes(drama_id: str) -> list[dict]: return updated +def _uses_account(row: dict) -> bool: + if not client.account_token: + return False + kind = episode_kind(row) + if kind in VIP_TYPES: + return True + if kind in PAID_TYPES or _int(row.get("price")) > 0: + return bool(already_bought(row) or row.get("needs_coin")) + return False + + def _lock_reason(row: dict) -> str: - kind = str(row.get("type") or "free") - if kind in {"vip", "VIP"}: + if _int(row.get("points") or row.get("price")) > 0 and not already_bought(row): + return public_lock_reason(row, "") + kind = episode_kind(row) + if kind in VIP_TYPES: return "需要 VIP" - if kind in {"coin", "points", "point", "pay"}: - return "需要积分或付费" - if not row.get("is_buy"): - return "尚未购买" - return "没有可下载的地址" + return "没有可播放的地址" -def _merge(cached: list[dict], fresh: list[dict]) -> tuple[list[dict], bool]: - by_cid: dict[int, dict] = {} - for source in (cached, fresh): - for ep in source: - cid = _int(ep.get("cid")) - if cid <= 0: - continue - current = by_cid.get(cid) - if current is None: - by_cid[cid] = dict(ep) - by_cid[cid]["cid"] = cid - by_cid[cid]["idx"] = _int(ep.get("idx") or cid) - continue - for key, value in ep.items(): - if key == "src": - if value: - current["src"] = value - continue - if value not in (None, "", [], {}): - current[key] = value - merged = sorted(by_cid.values(), key=lambda item: (int(item.get("idx") or 0), int(item["cid"]))) - filled_fresh = sum(1 for ep in fresh if ep.get("src")) - filled_cached = sum(1 for ep in cached if ep.get("src")) - return merged, filled_fresh >= filled_cached and filled_fresh > 0 +def _cached_row(drama_id: str, cid: int, *, refresh: bool = False) -> dict | None: + rows = load_episodes(drama_id) if refresh else _read_cache(drama_id) + for ep in rows: + if int(ep.get("cid") or 0) == int(cid): + return ep + return None + + +def _keep_sources(cached: list[dict], fresh: list[dict]) -> list[dict]: + previous = {int(ep.get("cid") or 0): ep for ep in cached if int(ep.get("cid") or 0) > 0} + merged = [] + for row in fresh: + old = previous.get(int(row["cid"])) + if old and old.get("is_preview"): + row["is_preview"] = True + if row.get("playable") and old and old.get("src") and not old.get("is_preview"): + row["src"] = old.get("src") or "" + row["src_kind"] = old.get("src_kind") or "" + row["hls_key"] = old.get("hls_key") or "" + row["preview_seconds"] = old.get("preview_seconds") or 0 + row["preview_m3u8"] = old.get("preview_m3u8") or "" + merged.append(row) + return merged + + +def _store_row(drama_id: str, row: dict) -> None: + with _cache_lock: + rows = _read_cache(drama_id) + cid = int(row.get("cid") or 0) + replaced = False + updated = [] + for item in rows: + if int(item.get("cid") or 0) == cid: + updated.append(row) + replaced = True + else: + updated.append(item) + if not replaced: + updated.append(row) + _write_cache(drama_id, updated) def _read_cache(drama_id: str) -> list[dict]: diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 3445e1c..5f3783d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2701,19 +2701,6 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" -[[package]] -name = "raptdrama" -version = "0.1.0" -dependencies = [ - "serde", - "serde_json", - "tauri", - "tauri-build", - "tauri-plugin-opener", - "webview2-com", - "windows-core 0.61.2", -] - [[package]] name = "raw-window-handle" version = "0.6.2" @@ -4129,6 +4116,19 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "videosdowntools" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tauri", + "tauri-build", + "tauri-plugin-opener", + "webview2-com", + "windows-core 0.61.2", +] + [[package]] name = "vswhom" version = "0.1.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index a6ab68f..51b3d3c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,17 +1,19 @@ [package] -name = "raptdrama" +name = "videosdowntools" version = "0.1.0" -description = "RaptDrama desktop shell" +description = "VideosDownTools desktop shell" authors = ["nixevol"] edition = "2021" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[[bin]] +name = "VideosDownTools" +path = "src/main.rs" [lib] # The `_lib` suffix may seem redundant but it is necessary # to make the lib name unique and wouldn't conflict with the bin name. # This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519 -name = "raptdrama_lib" +name = "videosdowntools_lib" crate-type = ["staticlib", "cdylib", "rlib"] [build-dependencies] diff --git a/src-tauri/splash/index.html b/src-tauri/splash/index.html index d7c830e..4a6474e 100644 --- a/src-tauri/splash/index.html +++ b/src-tauri/splash/index.html @@ -2,7 +2,7 @@ - RaptDrama Download Tools + VideosDownTools