diff --git a/server/requirements.txt b/server/requirements.txt index 755e6f3..e243b50 100644 --- a/server/requirements.txt +++ b/server/requirements.txt @@ -3,3 +3,4 @@ uvicorn>=0.32 websockets>=14 httpx[socks]>=0.28 cryptography>=44 +curl_cffi>=0.16 diff --git a/server/routes/dramabox.py b/server/routes/dramabox.py index 76cdcef..32da40b 100644 --- a/server/routes/dramabox.py +++ b/server/routes/dramabox.py @@ -1,8 +1,10 @@ import json +import threading +from collections import OrderedDict from urllib.parse import urlsplit import httpx -from fastapi import APIRouter, HTTPException, Query +from fastapi import APIRouter, HTTPException, Query, Request from fastapi.responses import Response, StreamingResponse from pydantic import BaseModel @@ -15,6 +17,7 @@ from server.services.dramabox.api import cdn_headers from server.services.dramabox.client import client from server.services.dramabox.covers import covers from server.services.dramabox.downloads import downloads as db_downloads +from server.services.dramabox.private_mp4 import decrypt_if_needed from server.services.playlist import is_direct_media router = APIRouter(prefix="/api/dramabox") @@ -24,9 +27,9 @@ class EnterBody(BaseModel): language: str = "" -class AccountBody(BaseModel): +class AdbLoginBody(BaseModel): + serial: str = "" language: str = "" - user: dict = {} class TokenBody(BaseModel): @@ -36,6 +39,10 @@ class TokenBody(BaseModel): language: str = "" +class CatalogSettingsBody(BaseModel): + max_pages: int | None = None + + class DownloadItem(BaseModel): id: str | int title: str = "" @@ -80,9 +87,9 @@ def login_device(body: EnterBody | None = None): return call(lambda: db_login.enter(language)) -@router.post("/login/account") -def login_account(body: AccountBody): - return call(lambda: db_login.apply_account(body.language, body.user)) +@router.post("/login/adb") +def login_adb(body: AdbLoginBody): + return call(lambda: db_login.import_adb(body.serial, body.language)) @router.post("/resume") @@ -101,6 +108,18 @@ def logout(body: TokenBody): return {"ok": True} +@router.get("/catalog/settings") +def get_catalog_settings(): + return {"max_pages": db_catalog.page_limit()} + + +@router.post("/catalog/settings") +def update_catalog_settings(body: CatalogSettingsBody): + if body.max_pages is None: + return {"max_pages": db_catalog.page_limit()} + return {"max_pages": db_catalog.set_page_limit(body.max_pages)} + + @router.post("/catalog") async def load_catalog(body: TokenBody): try: @@ -199,27 +218,105 @@ def play_segment(url: str, vid: str = Query(default="")): return StreamingResponse(chunks(), media_type=media) +_play_files: OrderedDict[tuple[str, int], bytes] = OrderedDict() +_play_lock = threading.Lock() +_play_inflight: dict[tuple[str, int], threading.Event] = {} +_PLAY_KEEP = 2 + + +def _load_play_file(vid: str, cid: int, src: str) -> bytes: + key = (str(vid), int(cid)) + while True: + with _play_lock: + hit = _play_files.get(key) + if hit is not None: + _play_files.move_to_end(key) + return hit + waiter = _play_inflight.get(key) + if waiter is None: + waiter = threading.Event() + _play_inflight[key] = waiter + owner = True + else: + owner = False + if owner: + break + if not waiter.wait(timeout=120): + raise HTTPException(status_code=502, detail="视频读取失败") + try: + try: + upstream = http.open_stream(src, headers=cdn_headers(book_id=vid), timeout=httpx.Timeout(90.0)) + try: + data = b"".join(chunk for chunk in upstream.iter_bytes(64 * 1024) if chunk) + finally: + upstream.close() + data = decrypt_if_needed(data) + except (httpx.HTTPError, TimeoutError, OSError, RuntimeError, ValueError) as exc: + raise HTTPException(status_code=502, detail="视频读取失败") from exc + with _play_lock: + _play_files[key] = data + _play_files.move_to_end(key) + while len(_play_files) > _PLAY_KEEP: + _play_files.popitem(last=False) + return data + finally: + with _play_lock: + event = _play_inflight.pop(key, None) + if event is not None: + event.set() + + +def _parse_byte_range(header: str | None, total: int) -> tuple[int, int] | None: + text = (header or "").strip() + if not text: + return None + if not text.lower().startswith("bytes="): + raise ValueError("range") + spec = text.split("=", 1)[1].split(",", 1)[0].strip() + if "-" not in spec: + raise ValueError("range") + left, right = spec.split("-", 1) + try: + if left == "": + length = int(right) + if length <= 0: + raise ValueError("range") + start = max(0, total - length) + end = total - 1 + else: + start = int(left) + end = int(right) if right else total - 1 + except ValueError as exc: + raise ValueError("range") from exc + if start < 0 or end < start or start >= total: + raise ValueError("range") + return start, min(end, total - 1) + + +def _ranged_mp4(data: bytes, range_header: str | None) -> Response: + total = len(data) + headers = {"Accept-Ranges": "bytes", "Cache-Control": "no-store"} + try: + parsed = _parse_byte_range(range_header, total) + except ValueError: + return Response(status_code=416, headers={**headers, "Content-Range": f"bytes */{total}"}) + if parsed is None: + headers["Content-Length"] = str(total) + return Response(content=data, media_type="video/mp4", headers=headers) + start, end = parsed + chunk = data[start:end + 1] + headers["Content-Range"] = f"bytes {start}-{end}/{total}" + headers["Content-Length"] = str(len(chunk)) + return Response(content=chunk, status_code=206, media_type="video/mp4", headers=headers) + + @router.get("/play/{vid}/{cid}/file") -def play_file(vid: str, cid: int): +def play_file(vid: str, cid: int, request: Request): row = db_playlist.episode_src(vid, cid) src = str(row.get("src") or "").strip() if not src: raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址") - try: - upstream = http.open_stream(src, headers=cdn_headers(book_id=vid)) - 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" - - def chunks(): - try: - for chunk in upstream.iter_bytes(64 * 1024): - if chunk: - yield chunk - finally: - upstream.close() - - return StreamingResponse(chunks(), media_type=media) + return _ranged_mp4(_load_play_file(vid, cid, src), request.headers.get("range")) @router.get("/play/{vid}/{cid}/index.m3u8") diff --git a/server/routes/proxy.py b/server/routes/proxy.py index cce8be9..ee6016c 100644 --- a/server/routes/proxy.py +++ b/server/routes/proxy.py @@ -7,6 +7,11 @@ from server.services.http import http router = APIRouter(prefix="/api") +@router.get("/proxy") +def get_proxy(): + return http.proxy_view() + + @router.post("/proxy") def set_proxy(body: ProxyBody): return call(lambda: _apply(body)) @@ -14,4 +19,4 @@ def set_proxy(body: ProxyBody): def _apply(body: ProxyBody) -> dict: http.configure_proxy(body.model_dump()) - return {"ok": True} + return {"ok": True, "url": http.webview_proxy_url()} diff --git a/server/services/adb.py b/server/services/adb.py index c3310f9..c74b94f 100644 --- a/server/services/adb.py +++ b/server/services/adb.py @@ -27,6 +27,7 @@ class Adb: candidates = [ REPO_ROOT / "tools" / "platform-tools" / name, REPO_ROOT / "vendor" / "platform-tools" / name, + Path(r"D:\Program Files\Netease\MuMu Player 12\shell") / name, ] for path in candidates: if path.is_file(): diff --git a/server/services/catalog_cache.py b/server/services/catalog_cache.py index d36c1f5..0feddaf 100644 --- a/server/services/catalog_cache.py +++ b/server/services/catalog_cache.py @@ -2,7 +2,7 @@ 只缓存分类和剧目清单,不缓存封面。封面仍由 cache/covers 负责。 手动刷新会删掉这份缓存并重新请求。 -正式打包时 Tauri 会把 RAPTD_CATALOG_CACHE 设为 0,从而关闭这里。 +开发模式 Tauri 把 RAPTD_CATALOG_CACHE 设为 1;正式打包设为 0,清单实时获取。 """ import json diff --git a/server/services/downloads.py b/server/services/downloads.py index c631319..510f292 100644 --- a/server/services/downloads.py +++ b/server/services/downloads.py @@ -70,6 +70,7 @@ class DownloadManager: read_cover=None, current_auth=None, headers: dict | None = None, + prepare_file=None, ) -> None: self._lock = threading.Lock() self._jobs: dict[str, dict] = {} @@ -83,6 +84,7 @@ class DownloadManager: self._read_cover_fn = read_cover self._current_auth = current_auth self._headers = dict(headers or {}) + self._prepare_file = prepare_file self._worker_limit = DEFAULT_WORKERS self._alive_workers = 0 self._wake = threading.Event() @@ -723,18 +725,22 @@ class DownloadManager: self._set_phase(drama_id, row["cid"], "downloading") source_dir.mkdir(parents=True, exist_ok=True) target = source_dir / "video.mp4" - if not target.is_file() or target.stat().st_size <= 0: - http.download_file( - row["src"], - target, - on_chunk=lambda size, job_id=drama_id: self._note_bytes(job_id, size), - stop=lambda job_id=drama_id: self._stopped(job_id), - headers=self._headers or None, - ) + # 成品不存在时,半截文件重新下,不把不完整的视频当成已经下完。 + if target.is_file(): + target.unlink() + http.download_file( + row["src"], + target, + on_chunk=lambda size, job_id=drama_id: self._note_bytes(job_id, size), + stop=lambda job_id=drama_id: self._stopped(job_id), + headers=self._headers or None, + ) if self._stopped(drama_id): raise RuntimeError("已停止") if not target.is_file() or target.stat().st_size <= 0: raise RuntimeError("试看文件没有下下来") + if self._prepare_file is not None: + self._prepare_file(target) mp4_path.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(target, mp4_path) if not has_audio(mp4_path): diff --git a/server/services/dramabox/api.py b/server/services/dramabox/api.py index 9c0c39f..b9c4a40 100644 --- a/server/services/dramabox/api.py +++ b/server/services/dramabox/api.py @@ -1,93 +1,5 @@ -import json -import re - -from server.services.dramabox.client import SITE, USER_AGENT, WEBFIC, client +from server.services.dramabox.client import SITE, USER_AGENT, client from server.services.dramabox.locales import film_path, resolve -from server.services.http import http - -_NEXT_DATA = re.compile(r'', re.S) - - -def home_index(language: str | None = None) -> list[dict]: - data = _webfic("POST", "/webfic/home/index", {}, language) - return data if isinstance(data, list) else [] - - -_ALL_LABELS: dict[str, str] = {} - - -def all_label(language: str | None = None) -> str: - locale = resolve(language or client.language)["id"] - cached = _ALL_LABELS.get(locale) - if cached: - return cached - url = f"https://infocdn.dramaboxdb.com/seo/dramaboxapp/locales/{locale}/common.json" - label = "" - try: - response = http.send( - "GET", - url, - headers={"User-Agent": USER_AGENT, "Referer": f"{SITE}/", "Accept": "application/json"}, - timeout=20.0, - ) - response.raise_for_status() - payload = response.json() - browse_text = payload.get("browse") if isinstance(payload, dict) else None - if isinstance(browse_text, dict): - label = str(browse_text.get("all") or "").strip() - except Exception: - label = "" - if not label: - label = "All" - _ALL_LABELS[locale] = label - return label - - -def browse(page: int, type_id: int, language: str | None = None, page_size: int = 18) -> dict: - data = _webfic( - "POST", - "/webfic/home/browse", - {"pageNo": page, "pageSize": page_size, "typeTwoId": int(type_id)}, - language, - ) - return data if isinstance(data, dict) else {} - - -def home_more(name: str, page: int = 1, page_size: int = 18, language: str | None = None) -> dict: - data = _webfic( - "POST", - "/webfic/home/more", - {"name": name, "pageNum": page, "pageSize": page_size}, - language, - ) - return data if isinstance(data, dict) else {} - - -def search_books(keyword: str, page: int = 1, page_size: int = 20, language: str | None = None) -> dict: - data = _webfic( - "POST", - "/webfic/book/search", - {"keyword": keyword, "pageNo": page, "pageSize": page_size}, - language, - ) - return data if isinstance(data, dict) else {} - - -def book_detail(book_id: str, language: str | None = None) -> dict: - data = _webfic("POST", "/webfic/book/detail", {"bookId": str(book_id)}, language) - return data if isinstance(data, dict) else {} - - -def film(book_id: str, language: str | None = None) -> dict: - locale = resolve(language or client.language)["id"] - book_id = str(book_id or "").strip() - if not book_id: - raise RuntimeError("没有这部剧") - path = film_path(locale, book_id) - payload = _next_data(path) or _html_data(path) - if not payload: - raise RuntimeError("没有读到这部剧") - return payload def cdn_headers(language: str | None = None, book_id: str = "") -> dict: @@ -99,76 +11,3 @@ def cdn_headers(language: str | None = None, book_id: str = "") -> dict: "Origin": SITE, "Accept": "*/*", } - - -def _webfic(method: str, path: str, body: dict, language: str | None) -> object: - locale = resolve(language or client.language)["id"] - headers = { - "User-Agent": USER_AGENT, - "Accept": "application/json", - "Content-Type": "application/json", - "pline": "DRAMABOX", - "language": locale, - "Referer": f"{SITE}/", - "Origin": SITE, - } - url = WEBFIC + path - content = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8") if method != "GET" else None - try: - response = http.send(method, url, headers=headers, content=content, timeout=30.0) - response.raise_for_status() - payload = response.json() - except Exception as exc: - raise RuntimeError("DramaBox 接口请求失败") from exc - if not isinstance(payload, dict): - raise RuntimeError("接口没有返回数据") - if payload.get("success") is False or payload.get("status") not in (0, None, "0"): - raise RuntimeError(str(payload.get("message") or "请求失败")) - return payload.get("data") - - -def _next_data(path: str) -> dict: - build = (client.build_id or "").strip() - if not build: - return {} - url = f"{SITE}/_next/data/{build}{path}.json" - try: - response = http.send("GET", url, headers=_site_headers(path), timeout=30.0) - response.raise_for_status() - payload = response.json() - except Exception: - return {} - props = payload.get("pageProps") if isinstance(payload, dict) else None - return props if isinstance(props, dict) else {} - - -def _html_data(path: str) -> dict: - url = SITE + path - try: - response = http.send("GET", url, headers=_site_headers(path), timeout=30.0) - response.raise_for_status() - text = response.text - except Exception as exc: - raise RuntimeError("DramaBox 页面读取失败") from exc - match = _NEXT_DATA.search(text) - if not match: - raise RuntimeError("没有读到这部剧") - try: - payload = json.loads(match.group(1)) - except json.JSONDecodeError as exc: - raise RuntimeError("这部剧的数据无效") from exc - build = str(payload.get("buildId") or "").strip() - if build and build != client.build_id: - client.build_id = build - client.save() - props = payload.get("props", {}).get("pageProps") if isinstance(payload, dict) else None - return props if isinstance(props, dict) else {} - - -def _site_headers(path: str) -> dict: - return { - "User-Agent": USER_AGENT, - "Accept": "text/html,application/json", - "Referer": SITE + (path if path.startswith("/") else f"/{path}"), - "Origin": SITE, - } diff --git a/server/services/dramabox/app_api.py b/server/services/dramabox/app_api.py new file mode 100644 index 0000000..cd8e59b --- /dev/null +++ b/server/services/dramabox/app_api.py @@ -0,0 +1,456 @@ +"""用 App 协议读取正片地址。播放地址不落盘。""" +import datetime +import json +import threading +import time +import uuid +from urllib.parse import urlencode + +import httpx + +from server.services.dramabox.app_sign import native_sign, rsa_sign, sign_material +from server.services.dramabox.client import client +from server.services.dramabox.locales import DEFAULT_LANGUAGE, resolve +from server.services.http import http +from server.services.playlist import is_direct_media + +HOSTS = ( + "https://sapi.dramaboxvideo.com/", + "https://sapi.dramaboxdb.com/", + "https://sapi.dramaboxapp.com/", +) +_CHANNEL = "CODE00001" +_started = time.time() +_preferred = "" +_guest_lock = threading.Lock() + + +def new_device(template: dict | None = None) -> dict: + source = template if isinstance(template, dict) else {} + now = str(int(time.time() * 1000)) + language = client.language or source.get("language") or DEFAULT_LANGUAGE + try: + locale = resolve(language) + language = locale["id"] + tag = locale.get("tag") or "en_US" + except RuntimeError: + tag = "en_US" + return { + "token": "", + "user_id": "", + "device_id": str(uuid.uuid4()), + "android_id": uuid.uuid4().hex, + "cid": _CHANNEL, + "nchid": _CHANNEL, + "mchid": "", + "mbid": "", + "language": language, + "current_language": language, + "country_code": source.get("country_code") or "", + "locale": source.get("locale") or tag, + "brand": source.get("brand") or "google", + "model": source.get("model") or "Pixel 8", + "manufacturer": source.get("manufacturer") or source.get("brand") or "Google", + "os_version": source.get("os_version") or "14", + "build": source.get("build") or "", + "resolution": source.get("resolution") or "1080x2400", + "install_time": now, + "instance_id": uuid.uuid4().hex, + "device_score": str(source.get("device_score") or "8"), + "lat": source.get("lat") or "0", + "afid": "", + "vip": False, + } + + +def create_guest(template: dict | None = None) -> dict: + device = new_device(template) + data = _post("drama-box/ap001/bootstrap", { + "distinctId": str(uuid.uuid4()), + "installTime": device["install_time"], + }, device) + return _guest_from_bootstrap(device, data) + + +def ensure_guest() -> dict: + if client.has_guest(): + return client.guest + with _guest_lock: + if client.has_guest(): + return client.guest + try: + guest = create_guest(client.app if client.has_app() else None) + except RuntimeError: + return {} + client.guest = guest + client.save() + return guest + + +def browse_app() -> dict: + return ensure_guest() or client.app + + +def vip_app() -> dict: + return client.app + + +def _guest_from_bootstrap(device: dict, data: dict) -> dict: + user = data.get("user") if isinstance(data, dict) else None + if not isinstance(user, dict): + raise RuntimeError("没有拿到访客身份") + token = str(user.get("token") or "").strip() + uid = str(user.get("uid") or "").strip() + if not token or uid in ("", "0"): + raise RuntimeError("没有拿到访客身份") + if user.get("isVip") == 1: + raise RuntimeError("访客身份异常") + if not token.startswith("Bearer "): + token = f"Bearer {token}" + guest = dict(device) + guest["token"] = token + guest["user_id"] = uid + guest["vip"] = False + return guest + + +def load_app_episodes(drama_id: str) -> list[dict]: + drama_id = str(drama_id or "").strip() + if not drama_id: + raise RuntimeError("没有这部剧") + if not client.can_browse(): + raise RuntimeError("请先进入 DramaBox") + browse = browse_app() + order = _chapter_rows(drama_id, browse) + by_id = _playable_chapters(drama_id, order, browse) + missing = [item for item in order if not _choose_media(by_id.get(item["chapterId"], {}))] + charged = [item["chapterId"] for item in missing if _charged(item)] + if charged and client.has_app(): + _merge_download(drama_id, charged, by_id, vip_app()) + episodes = [] + for position, item in enumerate(order, start=1): + detail = by_id.get(item["chapterId"]) or item + src = _choose_media(detail) + raw_index = detail.get("chapterIndex") + if raw_index is None: + raw_index = item.get("chapterIndex") + idx = position if raw_index is None else _int(raw_index) + 1 + title = str(detail.get("chapterName") or item.get("chapterName") or f"第{idx}集").strip() or f"第{idx}集" + cover = str(detail.get("chapterImg") or item.get("chapterImg") or "") + if src: + reason = "" + elif _charged(item) or _charged(detail): + reason = "需要解锁" + else: + reason = "没有可播放的地址" + episodes.append({ + "cid": _int(item["chapterId"]) or position, + "idx": idx, + "title": title, + "src": src, + "src_kind": "file" if src and is_direct_media(src) else ("hls" if src else ""), + "type": "free" if src else "lock", + "price": 0, + "cover": cover, + "duration": 0, + "is_preview": False, + "preview_seconds": 0, + "hls_key": "", + "locked_reason": reason, + }) + if not episodes: + raise RuntimeError("没有读到分集") + return episodes + + +def book_brief(drama_id: str) -> dict: + data = _play_window(str(drama_id), 0, 0, False, browse_app()) + tags = data.get("tags") if isinstance(data, dict) else None + return { + "name": str((data or {}).get("bookName") or ""), + "introduction": str((data or {}).get("introduction") or ""), + "tags": "、".join(str(item) for item in tags if item) if isinstance(tags, list) else "", + "count": str((data or {}).get("chapterCount") or ""), + } + + +def _chapter_rows(drama_id: str, app: dict) -> list[dict]: + listed = _post("drama-box/chapterv2/list", {"bookId": drama_id}, app) + rows = listed.get("list") if isinstance(listed, dict) else None + order = [] + for item in rows or []: + if not isinstance(item, dict): + continue + chapter_id = str(item.get("chapterId") or item.get("id") or "").strip() + if not chapter_id: + continue + item["chapterId"] = chapter_id + order.append(item) + if not order: + raise RuntimeError("没有读到分集") + return order + + +def _charged(item: dict) -> bool: + return _int(item.get("isCharge")) == 1 or item.get("chargeChapter") is True + + +def _playable_chapters(drama_id: str, order: list[dict], app: dict) -> dict: + found = {} + free_ids = {item["chapterId"] for item in order if not _charged(item)} + index = 0 + direction = 0 + preload = False + seen = set() + for _ in range(12): + try: + data = _play_window(drama_id, index, direction, preload, app) + except RuntimeError: + break + chapters = data.get("chapterList") if isinstance(data, dict) else None + if not isinstance(chapters, list) or not chapters: + break + highest = index + progressed = False + for chapter in chapters: + if not isinstance(chapter, dict): + continue + chapter_id = str(chapter.get("chapterId") or "").strip() + marker = chapter_id or str(chapter.get("chapterIndex")) + if marker not in seen: + progressed = True + seen.add(marker) + if chapter_id: + found[chapter_id] = chapter + raw_index = _int(chapter.get("chapterIndex")) + if raw_index >= highest: + highest = raw_index + if not progressed: + break + if free_ids and all(_choose_media(found.get(chapter_id, {})) for chapter_id in free_ids): + break + index = highest + 1 + direction = 0 + preload = False + return found + + +def _play_window(drama_id: str, index: int, direction: int, preload: bool, app: dict) -> dict: + # 打开播放页时 AlbumFragment.i0 的首包:boundaryIndex=0,index 为当前集,loadDirection 随后用 2 向后取。 + return _post("drama-box/chapterv2/batch/load", { + "bookId": drama_id, + "boundaryIndex": 0, + "currencyPlaySource": "discover", + "currencyPlaySourceName": "discover", + "index": index, + "loadDirection": direction, + "preLoad": preload, + "pullCid": "", + "rid": "", + "startUpKey": "raptdrama", + "needEndRecommend": 0, + }, app) + + +def _merge_download(drama_id: str, chapter_ids: list[str], found: dict, app: dict) -> None: + if not chapter_ids: + return + try: + downloaded = _post("drama-box/chapterv2/batchDownload", {"bookId": drama_id, "chapterIdList": chapter_ids}, app) + except RuntimeError: + return + chapters = downloaded.get("chapterVoList") if isinstance(downloaded, dict) else None + if not isinstance(chapters, list): + return + for chapter in chapters: + if not isinstance(chapter, dict): + continue + chapter_id = str(chapter.get("chapterId") or "").strip() + if chapter_id and _choose_media(chapter): + found[chapter_id] = chapter + + +def _choose_media(chapter: dict) -> str: + found = [] + groups = [] + for key in ("cdnList", "m3u8CdnList"): + rows = chapter.get(key) + if isinstance(rows, list): + groups.extend(item for item in rows if isinstance(item, dict)) + for cdn in groups: + for key in ("videoPathList", "qualitys"): + rows = cdn.get(key) + if not isinstance(rows, list): + continue + for item in rows: + if not isinstance(item, dict): + continue + _add_candidate(found, item.get("videoPath"), item.get("quality")) + _add_candidate(found, cdn.get("videoPath"), 0) + if not found: + return "" + found.sort(key=lambda item: (item[0], 0 if item[1] else 1), reverse=True) + return found[0][2] + + +def _add_candidate(found: list, path, quality) -> None: + url = str(path or "").strip() + if not url.startswith(("http://", "https://")) or _preview(url): + return + found.append((_rank(quality, url), ".m3u8" in url.lower(), url)) + + +def _preview(url: str) -> bool: + name = url.split("?", 1)[0].lower() + return "15s" in name or "preview" in name + + +def _rank(quality, path: str) -> int: + name = path.lower() + for label in (1080, 720, 540): + if str(label) in name: + return label + number = _int(quality) + if number in (1080, 720, 540): + return number + return number if number > 0 else 1 + + +def _post(path: str, payload: dict, app: dict | None = None) -> dict: + body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + chosen = app if app is not None else browse_app() + last = "DramaBox 接口没有响应" + for host in _hosts(): + for transport in _transports(): + try: + status, data = _send(host, path, body, transport, chosen) + except RuntimeError as exc: + last = str(exc) + continue + if status == 0 and isinstance(data, dict): + global _preferred + _preferred = host + return data + message = "" + if isinstance(data, dict): + message = str(data.get("message") or data.get("msg") or "") + last = message or f"DramaBox 接口返回 {status}" + raise RuntimeError(last) + + +def _send(host: str, path: str, body: bytes, transport: dict, app: dict) -> tuple[int, object]: + timestamp = str(int(time.time() * 1000)) + text = body.decode("utf-8") + material = sign_material(timestamp, text, app.get("device_id", ""), app.get("android_id", ""), app.get("token", "")) + headers = _headers(app, material) + url = f"{host}{path}?{urlencode({'timestamp': timestamp})}" + response = _request(url, headers, body, transport) + content_type = response.headers.get("content-type", "") + if response.status_code == 403: + raise RuntimeError("DramaBox 接口被当前网络拦截。请把 sapi.dramaboxdb.com、sapi.dramaboxvideo.com、sapi.dramaboxapp.com 设为直连。") + if response.status_code >= 400: + raise RuntimeError(f"DramaBox 接口返回 {response.status_code}") + try: + payload = response.json() + except ValueError as exc: + raise RuntimeError("DramaBox 接口没有返回数据") from exc + if not isinstance(payload, dict): + raise RuntimeError("DramaBox 接口没有返回数据") + return _int(payload.get("status")), payload.get("data") if "data" in payload else payload + + +def _headers(app: dict, material: str) -> dict: + now = datetime.datetime.now().astimezone() + local = now.strftime("%Y-%m-%d %H:%M:%S.") + f"{now.microsecond // 1000:03d} " + now.strftime("%z") + offset = now.utcoffset() or datetime.timedelta(0) + zone = str(-int(offset.total_seconds() // 60)) + headers = { + "Accept": "application/json", + "Content-Type": "application/json; charset=UTF-8", + "User-Agent": "okhttp/4.12.0", + "version": "693", + "vn": "6.9.3", + "package-name": "com.storymatrix.drama", + "p": "77", + "pline": "ANDROID", + "cid": app.get("cid") or "", + "nchid": app.get("nchid") or "", + "mchid": app.get("mchid") or "", + "mbid": app.get("mbid") or "", + "userId": app.get("user_id") or "", + "device-id": app.get("device_id") or "", + "android-id": app.get("android_id") or "", + "tn": app.get("token") or "", + "language": (client.language or app.get("language") or ""), + "current-language": (client.language or app.get("current_language") or ""), + "country-code": app.get("country_code") or "", + "locale": app.get("locale") or "", + "local-time": local, + "time-zone": local[24:], + "tz": zone, + "brand": app.get("brand") or "", + "md": app.get("model") or "", + "mf": app.get("manufacturer") or "", + "ov": app.get("os_version") or "", + "build": app.get("build") or "", + "srn": app.get("resolution") or "", + "installTime": app.get("install_time") or "", + "instanceId": app.get("instance_id") or "", + "device-score": app.get("device_score") or "", + "apn": "2", + "lat": app.get("lat") or "0", + "store-source": "store_google", + "over-flow": "new-fly", + "afid": app.get("afid") or "", + "sn": rsa_sign(material), + "st": native_sign(material), + "active-time": str(max(1, int((time.time() - _started) * 1000))), + } + return {key: value for key, value in headers.items() if value != ""} + + +def _hosts() -> list[str]: + if _preferred: + return [_preferred, *[host for host in HOSTS if host != _preferred]] + return list(HOSTS) + + +def _transports() -> list[dict]: + # chapterv2/batch/load 对 Chrome 指纹返回边缘 403,Safari 指纹能拿到 JSON。首页两种都可以,先走能播的指纹。 + transports = [ + {"kind": "chrome", "impersonate": "safari18_0", "proxy": None}, + {"kind": "chrome", "impersonate": "chrome131", "proxy": None}, + ] + view = http.proxy_view() + if view.get("mode") != "off" and view.get("url"): + transports.append({"kind": "chrome", "impersonate": "safari18_0", "proxy": view["url"]}) + return transports + + +def _request(url: str, headers: dict, body: bytes, transport: dict): + proxy = transport.get("proxy") + try: + if transport.get("kind") == "chrome": + from curl_cffi import requests + + return requests.post( + url, + data=body, + headers=headers, + impersonate=transport.get("impersonate") or "chrome131", + proxy=proxy, + timeout=25, + ) + with httpx.Client(proxy=proxy, trust_env=False, timeout=25, follow_redirects=True) as session: + return session.post(url, headers=headers, content=body) + except RuntimeError: + raise + except Exception as exc: + raise RuntimeError("DramaBox 接口没有连上") from exc + + +def _int(value) -> int: + try: + return int(float(str(value))) + except (TypeError, ValueError): + return 0 diff --git a/server/services/dramabox/app_device.py b/server/services/dramabox/app_device.py new file mode 100644 index 0000000..a9405b3 --- /dev/null +++ b/server/services/dramabox/app_device.py @@ -0,0 +1,208 @@ +"""从已登录的 DramaBox App 读取设备身份。令牌只进入本地会话文件。""" +import re +import tempfile +import time +from pathlib import Path + +from server.services.adb import Adb + +PACKAGE = "com.storymatrix.drama" +PREFS = f"/data/data/{PACKAGE}/files/drama.datastore.preferences_pb" +APPSFLYER = f"/data/data/{PACKAGE}/shared_prefs/appsflyer-data.xml" + + +def read_app_login(serial: str) -> dict: + serial = (serial or "").strip() + if not serial: + raise RuntimeError("请选择设备") + adb = Adb.locate() + adb._ready(serial) + with tempfile.TemporaryDirectory(prefix="dramabox-login-") as tmp: + root = Path(tmp) + prefs_path = root / "drama.pb" + flyer_path = root / "af.xml" + _pull(adb, serial, PREFS, prefs_path) + prefs = _parse_prefs(prefs_path.read_bytes()) + try: + _pull(adb, serial, APPSFLYER, flyer_path) + afid = _xml_string(flyer_path.read_text(encoding="utf-8", errors="replace"), "AF_INSTALLATION") + except RuntimeError: + afid = "" + token = str(prefs.get("sp.user.token") or "") + if not token.startswith("Bearer "): + raise RuntimeError("这台设备上的 DramaBox 还没有登录,请先在 App 里登录后再读取") + device_id = str(prefs.get("google.ad.id") or "") + android_id = str(prefs.get("google.android.id") or "") + user_id = str(prefs.get("sp.user.id") or "") + if not device_id or not android_id or not user_id: + raise RuntimeError("登录信息不完整,请在 App 里重新打开一次后再读取") + brand = _prop(adb, serial, "ro.product.brand") or "OPPO" + model = _prop(adb, serial, "ro.product.model") or "PJJ110" + manufacturer = _prop(adb, serial, "ro.product.manufacturer") or brand + release = _prop(adb, serial, "ro.build.version.release") or "12" + build_id = _prop(adb, serial, "ro.build.id") + locale = _prop(adb, serial, "persist.sys.locale") or _prop(adb, serial, "ro.product.locale") + language = str(prefs.get("language.origin") or "zhHans") + current = str(prefs.get("sp.current.user_language") or "") + if not locale or "_" not in locale: + locale = "zh_CN" if current.startswith("zh") or language.startswith("zh") else (current or "en_US") + resolution = _resolution(adb, serial) + status = str(prefs.get(f"user.membership.status.uid.{user_id}") or "") + vip = prefs.get(f"user.vip.uid.{user_id}") is True or "paid" in status.lower() + return { + "token": token, + "device_id": device_id, + "android_id": android_id, + "user_id": user_id, + "name": str(prefs.get("sp.user.name") or ""), + "cid": str(prefs.get("sp.tf.chid") or ""), + "nchid": str(prefs.get("sp.native.channel.code") or "DRA1000042"), + "mchid": str(prefs.get("sp.tf.m.chid") or ""), + "mbid": str(prefs.get("sp.tf.m.bid") or prefs.get("sp.tf.chbid") or ""), + "language": language, + "current_language": current or (language[:2] if language else "en"), + "country_code": str(prefs.get("google.country.code") or ""), + "install_time": str(prefs.get("sp.app.install.time.stamp") or ""), + "instance_id": str(prefs.get("firebase.analytics.app_instance_id") or ""), + "device_score": str(prefs.get("device.score") if prefs.get("device.score") is not None else ""), + "lat": "1" if prefs.get("google.ad.is.tracking") else "0", + "afid": afid, + "brand": brand, + "model": model, + "manufacturer": manufacturer, + "os_version": release, + "build": f"Build/{build_id}" if build_id else "", + "locale": locale, + "resolution": resolution, + "vip": vip, + } + + +def _pull(adb: Adb, serial: str, remote: str, dest: Path) -> None: + last = _pull_once(adb, serial, remote, dest) + if last is None: + return + adb._run(["-s", serial, "root"], timeout=20) + if ":" in serial: + adb._run(["connect", serial], timeout=15) + for _ in range(6): + last = _pull_once(adb, serial, remote, dest) + if last is None: + return + time.sleep(0.4) + staged = _stage_with_su(adb, serial, remote) + if staged: + pulled = _pull_once(adb, serial, staged, dest) + adb._run(["-s", serial, "shell", f"rm -f {staged}"], timeout=10) + if pulled is None: + return + last = pulled or last + detail = "读不到应用私有目录。未 root 的设备无法获取登录信息。请使用已 root 的手机,或带 root 的模拟器。" + if last: + detail = f"{detail} {last}" + raise RuntimeError(detail) + + +def _pull_once(adb: Adb, serial: str, remote: str, dest: Path) -> str | None: + if dest.is_file(): + dest.unlink() + proc = adb._run(["-s", serial, "pull", remote, str(dest)], timeout=30) + if dest.is_file() and dest.stat().st_size > 0: + return None + return (proc.stderr or b"").decode("utf-8", "replace").strip() or "pull 失败" + + +def _stage_with_su(adb: Adb, serial: str, remote: str) -> str: + tmp = "/data/local/tmp/dramabox-login.bin" + command = f"cp {remote} {tmp} && chmod 644 {tmp}" + for line in (f"su -c '{command}'", f"su 0 sh -c '{command}'"): + adb._run(["-s", serial, "shell", line], timeout=15) + _, text, _ = adb._shell(serial, ["stat", "-c", "%s", tmp], timeout=8) + size = text.strip() + if size.isdigit() and int(size) > 0: + return tmp + return "" + + +def _prop(adb: Adb, serial: str, name: str) -> str: + _, text, _ = adb._shell(serial, ["getprop", name], timeout=8) + return text.strip() + + +def _resolution(adb: Adb, serial: str) -> str: + _, text, _ = adb._shell(serial, ["wm", "size"], timeout=8) + match = re.search(r"(\d+)x(\d+)", text) + if not match: + return "" + return f"{match.group(1)}x{match.group(2)}" + + +def _xml_string(text: str, name: str) -> str: + match = re.search(rf'(.*?)', text, re.S) + return match.group(1).strip() if match else "" + + +def _varint(buf: bytes, index: int) -> tuple[int, int]: + value = 0 + shift = 0 + while index < len(buf) and shift <= 63: + byte = buf[index] + index += 1 + value |= (byte & 0x7F) << shift + if byte < 128: + return value, index + shift += 7 + raise ValueError("登录信息格式无法识别") + + +def _fields(buf: bytes) -> list[tuple[int, object]]: + index = 0 + found = [] + while index < len(buf): + try: + key, index = _varint(buf, index) + except ValueError: + break + field, wire = key >> 3, key & 7 + if wire == 0: + value, index = _varint(buf, index) + found.append((field, value)) + elif wire == 2: + length, index = _varint(buf, index) + found.append((field, buf[index : index + length])) + index += length + elif wire == 5 and index + 4 <= len(buf): + found.append((field, buf[index : index + 4])) + index += 4 + elif wire == 1 and index + 8 <= len(buf): + found.append((field, buf[index : index + 8])) + index += 8 + else: + break + return found + + +def _parse_prefs(data: bytes) -> dict: + result = {} + for field, payload in _fields(data): + if field != 1 or not isinstance(payload, (bytes, bytearray)): + continue + name = None + value = None + for part_field, part in _fields(payload): + if part_field == 1 and isinstance(part, (bytes, bytearray)): + name = part.decode("utf-8", "replace") + elif part_field == 2 and isinstance(part, (bytes, bytearray)): + inner = _fields(part) + if not inner: + continue + value_field, raw = inner[0] + if value_field == 1: + value = bool(raw) + elif value_field in (3, 4): + value = int(raw) + elif value_field == 5 and isinstance(raw, (bytes, bytearray)): + value = raw.decode("utf-8", "replace") + if name: + result[name] = value + return result diff --git a/server/services/dramabox/app_sign.py b/server/services/dramabox/app_sign.py new file mode 100644 index 0000000..f402da6 --- /dev/null +++ b/server/services/dramabox/app_sign.py @@ -0,0 +1,122 @@ +# DramaBox 6.9.3 请求签名。材料来自安装包里的公开实现,令牌不写在这里。 +import base64 + +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding + +_PREFIX = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC9Q4Y5QX5j08HrnbY3irfKdkEllAU2OORnAjlXDyCzcm2Z6ZRrGvtTZUAMelfU5PWS6XGEm3d4kJEKbXi4Crl8o2E/E3YJPk1lQD1d0JTdrvZleETN1ViHZFSQwS3L94Woh0E3TPebaEYq88eExvKu1tDdjSoFjBbgMezySnas5Nc2xF28" +_MASK = "l|d,WL$EI,?xyw+*)^#?U`[whXlG`-GZif,.jCxbKkaY\"{w*y]_jax^/1iVDdyg(Wbz+z/$xVjCiH0lZf/d|%gZglW)\"~J,^~}w\"}m(E'eEunz)eyEy`XGaVF|_(Kw)|awUG\"'{{e#%$0E.ffHVU++$giHzdvC0ZLXG|U{aVUUYW{{YVU^x),J'If`nG|C[`ZF),xLv(-H'}ZIEyCfke0dZ%aU[V)\"V0}mhKvZ]Gw%-^a|m'`\\f}{(~kzi&zjG+|fXX0$IH#j`+hfnME\"|fa/{.j.xf,\"LZ.K^bZy%c.W^/v{x#(J},Ua,ew#.##K(ki)$LX{a-1\\MG/zL&JlEKEw'Hg|D&{EfuKYM[nGKx1V#lFu^V_LjVzw+n%+,Xd" +_SUFFIX = "x52e71nafqfbjXxZuEtpu92oJd6A9mWbd0BZTk72ZHUmDcKcqjfcEH19SWOphMJFYkxU5FRoIEr3/zisyTO4Mt33ZmwELOrY9PdlyAAyed7ZoH+hlTr7c025QROvb2LmqgRiUT56tMECgYEA+jH5m6iMRK6XjiBhSUnlr3DzRybwlQrtIj5sZprWe2my5uYHG3jbViYIO7GtQvMTnDrBCxNhuM6dPrL0cRnbsp/iBMXe3pyjT/aWveBkn4R+UpBsnbtDn28r1MZpCDtr5UNc0TPj4KFJvjnV/e8oGoyYEroECqcw1LqNOGDiLhkCgYEAwaemNePYrXW+MVX/hatfLQ96tpxwf7yuHdENZ2q5AFw73GJWYvC8VY+TcoKPAmeoCUMltI3TrS6K5Q/GoLd5K2BsoJrSxQNQFd3ehWAtdOuPDvQ5rn/2fsvgvc3rOvJh7uNnwEZCI/45WQg+UFWref4PPc+ArNtp9Xj2y7LndwkCgYARojIQeXmhYZjG6JtSugWZLuHGkwUDzChYcIPdW25gdluokG/RzNvQn4+W/XfTryQjr7RpXm1VxCIrCBvYWNU2KrSYV4XUtL+B5ERNj6In6AOrOAifuVITy5cQQQeoD+AT4YKKMBkQfO2gnZzqb8+ox130e+3K/mufoqJPZeyrCQKBgC2fobjwhQvYwYY+DIUharri+rYrBRYTDbJYnh/PNOaw1CmHwXJt5PEDcml3+NlIMn58I1X2U/hpDrAIl3MlxpZBkVYFI8LmlOeR7ereTddN59ZOE4jY/OnCfqA480Jf+FKfoMHby5lPO5OOLaAfjtae1FhrmpUe3EfIx9wVuhKBAoGBAPFzHKQZbGhkqmyPW2ctTEIWLdUHyO37fm8dj1WjN4wjRAI4ohNiKQJRh3QE11E1PzBTl9lZVWT8QtEsSjnrA/tpGr378fcUT7WGBgTmBRaAnv1P1n/Tp0TSvh5XpIhhMuxcitIgrhYMIG3GbP9JNAarxO/qPW6Gi0xWaF7il7Or" +_TABLES = ["kL3mN4oP5qR6sT7uV8wX9yZ0aB1cD2eF-GHIJ_KMOQSUWYbdfhjlnprtvxzACEgi@[\\]^:;<=>?", "7uV8wX9yZ0aB1cD2eF-GHIJ_KMOQSUWYbdfhjlnprtvxzACEgikL3mN4oP5qR6sT^:;<=>?@[\\]", "bdfhjlnprtvxzACEgikL3mN4oP5qR6sT7uV8wX9yZ0aB1cD2eF-GHIJ_KMOQSUWY<=>?@[\\]^:;", "1cD2eF-GHIJ_KMOQSUWYbdfhjlnprtvxzACEgikL3mN4oP5qR6sT7uV8wX9yZ0aB;:^]\\[@?>=<", "MOQSUWYbdfhjlnprtvxzACEgikL3mN4oP5qR6sT7uV8wX9yZ0aB1cD2eF-GHIJ_K[\\]^:;<=>?@", "R6sT7uV8wX9yZ0aB1cD2eF-GHIJ_KMOQSUWYbdfhjlnprtvxzACEgikL3mN4oP5q?@[\\]^:;<=>", "eF-GHIJ_KMOQSUWYbdfhjlnprtvxzACEgikL3mN4oP5qR6sT7uV8wX9yZ0aB1cD2=>?@[\\]^:;<", "xzACEgikL3mN4oP5qR6sT7uV8wX9yZ0aB1cD2eF-GHIJ_KMOQSUWYbdfhjlnprtv]\\[@?>=<;:^", "yZ0aB1cD2eF-GHIJ_KMOQSUWYbdfhjlnprtvxzACEgikL3mN4oP5qR6sT7uV8wX9>?@[\\]^:;<=", "lnprtvxzACEgikL3mN4oP5qR6sT7uV8wX9yZ0aB1cD2eF-GHIJ_KMOQSUWYbdfhj\\^][:;@?>=<"] +_ST_PREFIX = "cK4n10B_0tTQBrxF" +_SALT = "MySuperSecretSalt_DoNotLeak" +_PACKAGE = "com.storymatrix.drama" +_CERT_SHA256 = "003cc4921e198429f7dd7066244bfe5efccdfeea01adf25e91c96d64478c00a1" +_MASK64 = 0xFFFFFFFFFFFFFFFF + + +def _private_key(): + middle = [] + for char in _MASK: + if char < "!" or char > "~": + middle.append(char) + continue + shifted = chr(ord(char) - 20) + middle.append(shifted if shifted >= "!" else chr(ord(shifted) + ord("]"))) + raw = _PREFIX + "".join(middle) + _SUFFIX + return serialization.load_der_private_key(base64.b64decode(raw), password=None) + + +_KEY = _private_key() + + +def rsa_sign(text: str) -> str: + signature = _KEY.sign(text.encode("utf-8"), padding.PKCS1v15(), hashes.SHA256()) + return base64.b64encode(signature).decode("ascii") + + +def fixed_part() -> str: + return f"{_SALT}|{_PACKAGE}|{_CERT_SHA256}|" + + +def sign_material(timestamp: str, body: str, device_id: str, android_id: str, token: str) -> str: + text = f"timestamp={timestamp}{body}" + if device_id: + text += device_id + if android_id: + text += android_id + if token: + text += token + return text + + +def _table(table: bytes | str) -> bytes: + return table.encode("latin1") if isinstance(table, str) else table + + +def _mix(seed: int, text: str, table: bytes | str) -> int: + raw = _table(table) + value = seed & _MASK64 + for byte in text.encode("utf-8"): + mapped = byte + index = (byte - 0x30) & 0xFFFFFFFF + if index <= 0x4A: + mapped = raw[index] + value = (value * 33 + mapped) & _MASK64 + return value + + +def _low_mod10(value: int) -> int: + low = value & 0xFF + quot = (low * 0xCD) >> 11 + return (value - quot * 10) & 0xFF + + +def _encode6(data: bytes, alphabet: bytes | str) -> bytes: + alphabet = _table(alphabet) + out = bytearray(12) + cursor = 3 + index = 0 + src = data + b"\x00\x00\x00" + while True: + if index <= 4: + second = src[index + 1] + if index == 4: + third = 0 + nxt = 6 + first = src[index] + else: + third = src[index + 2] + nxt = index + 3 + first = src[index] + else: + second = 0 + third = 0 + nxt = 6 + first = src[index] + mixed = ((second << 8) | (first << 16)) & 0xFFFFFFFF + packed = (third & 0xFF) | ((second & 0xFF) << 8) + out[cursor - 3] = alphabet[first >> 2] + out[cursor - 2] = alphabet[(mixed >> 12) & 0x3F] + out[cursor - 1] = alphabet[(packed >> 6) & 0x3F] + out[cursor] = alphabet[third & 0x3F] + cursor += 4 + index = nxt + if nxt >= 6: + break + return bytes(out[:8]) + + +def native_sign(payload: str) -> str: + hashed = _mix(0x1505, payload, _TABLES[0]) + table = _TABLES[_low_mod10(hashed)] + hashed = _mix(hashed, fixed_part(), table) + block = bytes(( + 0x00, + 0x01, + (hashed >> 56) & 0xFF, + (hashed >> 48) & 0xFF, + (hashed >> 40) & 0xFF, + (hashed >> 32) & 0xFF, + )) + return _ST_PREFIX + _encode6(block, table).decode("ascii") diff --git a/server/services/dramabox/catalog.py b/server/services/dramabox/catalog.py index 3788d0a..bc4f210 100644 --- a/server/services/dramabox/catalog.py +++ b/server/services/dramabox/catalog.py @@ -1,13 +1,17 @@ import asyncio +import hashlib import json import os +import threading +import time from pathlib import Path -from server.services.dramabox import api from server.services.dramabox.client import client from server.services.dramabox.covers import covers ROOT = Path(__file__).resolve().parents[3] +DEFAULT_MAX_PAGES = 300 +MAX_MAX_PAGES = 999 def enabled_cache() -> bool: @@ -16,7 +20,49 @@ def enabled_cache() -> bool: def cache_path() -> Path: - return ROOT / "cache" / "dramabox" / f"catalog-browse-{client.language}.json" + return ROOT / "cache" / "dramabox" / f"catalog-app-channels-{client.language}.json" + + +def settings_path() -> Path: + return ROOT / "cache" / "dramabox" / "catalog-settings.json" + + +def page_limit() -> int: + path = settings_path() + if path.is_file(): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + data = None + if isinstance(data, dict) and "max_pages" in data: + return clamp_page_limit(data.get("max_pages")) + return DEFAULT_MAX_PAGES + + +def set_page_limit(value) -> int: + pages = clamp_page_limit(value) + path = settings_path() + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".json.tmp") + temporary.write_text(json.dumps({"max_pages": pages}, ensure_ascii=False), encoding="utf-8") + temporary.replace(path) + _drop_catalog_cache() + return pages + + +def clamp_page_limit(value) -> int: + number = _int(value) + if number < 1: + return DEFAULT_MAX_PAGES + return min(number, MAX_MAX_PAGES) + + +def _drop_catalog_cache() -> None: + folder = ROOT / "cache" / "dramabox" + if not folder.is_dir(): + return + for path in folder.glob("catalog-app-channels-*.json"): + path.unlink(missing_ok=True) async def stream(refresh: bool = False): @@ -41,44 +87,56 @@ async def stream(refresh: bool = False): _write_cache(path, collected) -PAGE_SIZE = 60 - - async def _fetch(): - language = client.language - first = await asyncio.to_thread(api.browse, 1, 0, language, PAGE_SIZE) - all_name = await asyncio.to_thread(api.all_label, language) - types = [item for item in (first.get("types") or []) if isinstance(item, dict)] - jobs: list[tuple[str, str, int]] = [("browse-0", all_name, 0)] - sections = [{"key": "browse-0", "name": all_name, "note": "", "loading": True}] - for item in types: - type_id = _int(item.get("id")) - name = str(item.get("name") or "").strip() - if type_id <= 0 or not name or name.lower() == "all": - continue - key = f"browse-{type_id}" - sections.append({"key": key, "name": name, "note": "", "loading": True}) - jobs.append((key, name, type_id)) - if not sections: - raise RuntimeError("没有获取到分类") + session = _rec_session() + home = await asyncio.to_thread(_home, session) + channels = [item for item in (home.get("channelList") or []) if isinstance(item, dict) and str(item.get("channelName") or "").strip()] + sections = [] + jobs: list[tuple] = [] + if channels: + for index, channel in enumerate(channels): + key = f"channel-{channel.get('channelId')}" + name = str(channel.get("channelName") or "").strip() + sections.append({"key": key, "name": name, "note": "", "loading": True}) + jobs.append((key, name, channel, index, home if index == 0 else None)) + else: + books = _dramas_from_feed(home) + if not books: + raise RuntimeError("没有获取到剧目") + sections.append({"key": "home", "name": "推荐", "note": "", "loading": True}) + jobs.append(("home", "推荐", None, 0, home)) yield {"type": "outline", "sections": sections} loop = asyncio.get_running_loop() queue: asyncio.Queue = asyncio.Queue() limit = asyncio.Semaphore(6) + stop = threading.Event() async def run(job): - key, name, type_id = job + key, name = job[0], job[1] def work(): try: - items = _browse_items(type_id) - loop.call_soon_threadsafe(queue.put_nowait, _page(key, name, items, done=True)) + page_no = 0 + page_cap = page_limit() + for items in _iter_channel_pages(job[2], job[3], job[4], session, stop): + if stop.is_set(): + break + if not items: + continue + page_no += 1 + loop.call_soon_threadsafe( + queue.put_nowait, + _page(key, name, items, done=False, page=page_no, pages=page_cap), + ) + if not stop.is_set(): + loop.call_soon_threadsafe(queue.put_nowait, _page(key, name, [], done=True)) except Exception as exc: - loop.call_soon_threadsafe( - queue.put_nowait, - _page(key, name, [], str(exc) or "获取清单失败", done=True, failed=True), - ) + if not stop.is_set(): + loop.call_soon_threadsafe( + queue.put_nowait, + _page(key, name, [], str(exc) or "获取清单失败", done=True, failed=True), + ) finally: loop.call_soon_threadsafe(queue.put_nowait, None) @@ -96,6 +154,7 @@ async def _fetch(): yield event yield {"type": "done"} finally: + stop.set() for task in tasks: if not task.done(): task.cancel() @@ -103,63 +162,326 @@ async def _fetch(): def search(keyword: str) -> list[dict]: - text = (keyword or "").strip() + text = (keyword or "").strip()[:80] if not text: return [] - items = [] + _require_app() + session = _rec_session() + found = [] seen: set[str] = set() - page = 1 - page_size = 60 - previous: tuple[str, ...] | None = None - while True: - payload = api.search_books(text, page=page, page_size=page_size) - rows = payload.get("records") if isinstance(payload, dict) else None - if not isinstance(rows, list) or not rows: + for page in range(1, 41): + try: + payload = _post("drama-box/search/search", _bind({ + "from": "search_sug", + "keyword": text, + "searchSource": "搜索按钮", + "sortType": 1, + "synSwitch": 0, + "pageNo": page, + "pageSize": 20, + }, session)) + except RuntimeError: break - signature = tuple(str(item.get("bookId") or "") for item in rows if isinstance(item, dict)) - if signature == previous: + rows = payload.get("searchList") if isinstance(payload, dict) else None + fresh = [item for item in _dramas(rows) if item["id"] not in seen] + if not fresh: break - previous = signature - for item in rows: - drama = _drama(item) - if not drama or drama["id"] in seen: - continue - seen.add(drama["id"]) - items.append(drama) - total = _int(payload.get("total")) if isinstance(payload, dict) else 0 - if len(rows) < page_size or (total and page * page_size >= total): + seen.update(item["id"] for item in fresh) + found.extend(fresh) + if not _more(payload): break - page += 1 - return items + if found: + return found + payload = _post("drama-box/search/suggest", {"keyword": text}) + rows = payload.get("suggestList") if isinstance(payload, dict) else None + return _dramas(rows) -def _browse_items(type_id: int) -> list[dict]: - items = [] +def _require_app() -> None: + if not client.can_browse(): + raise RuntimeError("请先进入 DramaBox") + + +def _post(path: str, payload: dict) -> dict: + from server.services.dramabox.app_api import browse_app, _post as post + + _require_app() + return post(path, payload, browse_app()) + + +def _home(session: str = "") -> dict: + return _post("drama-box/he001/theater", _bind({"type": 0, "isNeedNewChannel": 1, "isNeedRank": 1}, session)) + + +def _rec_session() -> str: + from server.services.dramabox.app_api import browse_app + + app = browse_app() or {} + raw = f"{app.get('android_id') or ''}_{int(time.time() * 1000)}_{app.get('user_id') or ''}" + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + +def _bind(payload: dict, session: str) -> dict: + if not session: + return payload + body = dict(payload) + body["recSessionId"] = session + return body + + +def _halted(stop: threading.Event | None) -> bool: + return bool(stop and stop.is_set()) + + +def _iter_channel_pages(channel: dict | None, index: int, home: dict | None, session: str = "", stop: threading.Event | None = None): seen: set[str] = set() - page = 1 - total_pages = 1 - previous: tuple[str, ...] | None = None - while page <= total_pages: - data = api.browse(page, type_id, page_size=PAGE_SIZE) - rows = data.get("bookList") if isinstance(data, dict) else None - reported = _int(data.get("pages")) if isinstance(data, dict) else 0 - if reported > 0: - total_pages = reported - if not isinstance(rows, list) or not rows: - break - signature = tuple(str(item.get("bookId") or "") for item in rows if isinstance(item, dict)) - if signature == previous: - break - previous = signature - for item in rows: - drama = _drama(item) - if not drama or drama["id"] in seen: + + def fresh(rows: list[dict]) -> list[dict]: + page = [] + for drama in rows: + if drama["id"] in seen: continue seen.add(drama["id"]) - items.append(drama) - if len(rows) < PAGE_SIZE or page >= total_pages: - break - page += 1 + page.append(drama) + return page + + if not isinstance(channel, dict): + if isinstance(home, dict): + first = fresh(_dramas_from_feed(home)) + if first: + yield first + return + channel_type = _int(channel.get("channelType")) + channel_id = _int(channel.get("channelId")) + if channel_type == 2: + yield from _new_theater_pages(channel_id, index, fresh, session, stop) + return + if channel_type == 3: + yield from _rank_pages(fresh, session, stop) + return + if channel_type == 4: + yield from _classify_pages(fresh, session, stop) + return + if channel_type in (5, 6, 7, 8): + yield from _grid_pages(channel_id, index, fresh, session, stop) + return + first_payload = home if index == 0 and isinstance(home, dict) else None + yield from _explore_pages(channel_id, index, channel_type, first_payload, fresh, session, stop) + + +def _new_theater_pages(channel_id: int, index: int, fresh, session: str, stop: threading.Event | None = None): + style = 1 + page_no = 1 + limit = page_limit() + while page_no <= limit: + if _halted(stop): + return + try: + data = _post("drama-box/he001/theater", _bind({ + "channelId": channel_id, + "index": index, + "pageNo": page_no, + "isNeedRank": 1, + "newChannelStyle": style, + }, session)) + except RuntimeError: + return + records = _records(data, "newTheaterList") + if not records and page_no == 1 and style == 1: + style = 0 + continue + page = fresh(_dramas(records)) + if page: + yield page + if not records: + return + page_no += 1 + + +def _rank_pages(fresh, session: str, stop: threading.Event | None = None): + if _halted(stop): + return + try: + data = _post("drama-box/he001/rank", _bind({}, session)) + except RuntimeError: + return + page = fresh(_dramas(data.get("rankList") if isinstance(data, dict) else None)) + if page: + yield page + asked: set[int] = set() + for item in (data.get("rankTypeVoList") if isinstance(data, dict) else None) or []: + if not isinstance(item, dict): + continue + rank_type = _int(item.get("rankType")) + if rank_type in asked: + continue + if _halted(stop): + return + asked.add(rank_type) + try: + ranked = _post("drama-box/he001/rank", _bind({"rankType": rank_type}, session)) + except RuntimeError: + return + page = fresh(_dramas(ranked.get("rankList") if isinstance(ranked, dict) else None)) + if page: + yield page + + +def _classify_pages(fresh, session: str, stop: threading.Event | None = None): + filters: list[dict] = [] + show_labels = True + for page_no in range(1, page_limit() + 1): + if _halted(stop): + return + try: + data = _post("drama-box/he001/classify", _bind({ + "typeList": filters, + "showLabels": show_labels, + "pageNo": page_no, + "pageSize": 15, + }, session)) + except RuntimeError: + return + if show_labels: + filters = _classify_filters(data) + show_labels = False + block = data.get("classifyBookList") if isinstance(data, dict) else None + records = block.get("records") if isinstance(block, dict) else None + page = fresh(_dramas(records)) + if page: + yield page + if not isinstance(records, list) or not records: + return + if isinstance(block, dict) and "isMore" in block and not _more(block): + return + + +def _grid_pages(channel_id: int, index: int, fresh, session: str, stop: threading.Event | None = None): + for page_no in range(1, page_limit() + 1): + if _halted(stop): + return + try: + data = _post("drama-box/he001/theater", _bind({ + "channelId": channel_id, + "index": index, + "pageNo": page_no, + "pageSize": 10, + }, session)) + except RuntimeError: + return + records = _records(data, "recommendList") + rows = _dramas_from_feed(data) if page_no == 1 else _dramas(records) + page = fresh(rows) + if page: + yield page + if not records: + return + + +def _explore_pages(channel_id: int, index: int, channel_type: int, home: dict | None, fresh, session: str, stop: threading.Event | None = None): + if isinstance(home, dict): + data = home + else: + if _halted(stop): + return + try: + data = _post("drama-box/he001/theater", _bind({ + "channelId": channel_id, + "index": index, + "type": channel_type, + "isNeedRank": 1, + }, session)) + except RuntimeError: + return + page = fresh(_dramas_from_feed(data)) + if page: + yield page + special = _int(data.get("specialColumnId") if isinstance(data, dict) else 0) + for page_no in range(2, page_limit() + 1): + if _halted(stop): + return + try: + data = _post("drama-box/he001/recommendBook", _bind({ + "pageNo": page_no, + "specialColumnId": special, + "isNeedRank": 1, + }, session)) + except RuntimeError: + return + records = _records(data, "recommendList") + page = fresh(_dramas(records)) + if page: + yield page + if not records: + return + + +def _classify_filters(data: dict) -> list[dict]: + filters = [] + if not isinstance(data, dict): + return filters + for item in data.get("classifyList") or []: + if not isinstance(item, dict): + continue + tags = item.get("showList") or [] + if not tags or not isinstance(tags[0], dict): + continue + filters.append({"type": _int(item.get("type")), "value": tags[0].get("value")}) + return filters + + +def _records(data: dict, key: str) -> list: + block = data.get(key) if isinstance(data, dict) else None + records = block.get("records") if isinstance(block, dict) else None + return records if isinstance(records, list) else [] + + +def _more(block) -> bool: + if not isinstance(block, dict) or "isMore" not in block: + return False + return _int(block.get("isMore")) != 0 + + +def _dramas_from_feed(data: dict) -> list[dict]: + found = [] + if not isinstance(data, dict): + return found + for column in data.get("columnVoList") or []: + if isinstance(column, dict): + found.extend(_dramas(column.get("bookList"))) + for key in ("recommendList", "newTheaterList"): + block = data.get(key) + records = block.get("records") if isinstance(block, dict) else None + found.extend(_dramas(records)) + if isinstance(records, list): + for record in records: + if not isinstance(record, dict): + continue + card = record.get("tagCardVo") + if isinstance(card, dict): + found.extend(_dramas(card.get("tagBooks"))) + found.extend(_dramas(data.get("bannerList"))) + seen: set[str] = set() + unique = [] + for item in found: + if item["id"] in seen: + continue + seen.add(item["id"]) + unique.append(item) + return unique + + +def _dramas(rows) -> list[dict]: + items = [] + seen: set[str] = set() + if not isinstance(rows, list): + return items + for item in rows: + drama = _drama(item) + if not drama or drama["id"] in seen: + continue + seen.add(drama["id"]) + items.append(drama) return items @@ -170,7 +492,7 @@ def _drama(item: dict) -> dict | None: title = str(item.get("bookName") or item.get("name") or "").strip() if not drama_id or not title: return None - image = str(item.get("cover") or item.get("_originalCover") or "").strip() + image = str(item.get("coverWap") or item.get("cover") or item.get("_originalCover") or "").strip() count = item.get("chapterCount") tags = item.get("typeTwoNames") if isinstance(item.get("typeTwoNames"), list) else [] corner = str(item.get("typeTwoName") or (tags[0] if tags else "")).strip() @@ -188,8 +510,20 @@ def _drama(item: dict) -> dict | None: } -def _page(key: str, name: str, items: list[dict], note: str = "", done: bool = False, failed: bool = False) -> dict: +def _page( + key: str, + name: str, + items: list[dict], + note: str = "", + done: bool = False, + failed: bool = False, + page: int = 0, + pages: int = 0, +) -> dict: event = {"type": "page", "key": key, "name": name, "note": note, "items": items, "done": done} + if page: + event["page"] = page + event["pages"] = pages if failed: event["failed"] = True return event diff --git a/server/services/dramabox/client.py b/server/services/dramabox/client.py index e8cfdbf..e52e7b5 100644 --- a/server/services/dramabox/client.py +++ b/server/services/dramabox/client.py @@ -1,5 +1,6 @@ import json import secrets +import threading from pathlib import Path from server.services.dramabox.locales import DEFAULT_LANGUAGE, resolve @@ -9,7 +10,6 @@ STATE_DIR = ROOT / "cache" / "dramabox" SESSION_PATH = STATE_DIR / "session.json" SITE = "https://www.dramaboxapp.com" -WEBFIC = "https://www.webfic.com" USER_AGENT = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36" @@ -20,9 +20,13 @@ class DramaBoxClient: def __init__(self) -> None: self.token = "" self.web_token = "" + self.web_user: dict = {} self.language = DEFAULT_LANGUAGE self.build_id = "" self.profile: dict = {} + self.app: dict = {} + self.guest: dict = {} + self._lock = threading.Lock() self._load() def _load(self) -> None: @@ -36,6 +40,9 @@ class DramaBoxClient: return self.token = str(data.get("token") or "") self.web_token = str(data.get("web_token") or "") + web_user = data.get("web_user") + if isinstance(web_user, dict): + self.web_user = web_user language = str(data.get("language") or "").strip() if language: try: @@ -46,19 +53,29 @@ class DramaBoxClient: profile = data.get("profile") if isinstance(profile, dict): self.profile = profile + app = data.get("app") + if isinstance(app, dict): + self.app = app + guest = data.get("guest") + if isinstance(guest, dict): + self.guest = guest def save(self) -> None: - STATE_DIR.mkdir(parents=True, exist_ok=True) - payload = { - "token": self.token, - "web_token": self.web_token, - "language": self.language, - "build_id": self.build_id, - "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) + with self._lock: + STATE_DIR.mkdir(parents=True, exist_ok=True) + payload = { + "token": self.token, + "web_token": self.web_token, + "web_user": self.web_user, + "language": self.language, + "build_id": self.build_id, + "profile": self.profile, + "app": self.app, + "guest": self.guest, + } + temporary = SESSION_PATH.with_suffix(".json.tmp") + temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + temporary.replace(SESSION_PATH) def enter(self, language: str) -> dict: locale = resolve(language) @@ -66,11 +83,17 @@ class DramaBoxClient: if not self.token: self.token = secrets.token_hex(16) self.web_token = "" + self.web_user = {} + self.app = {} + if self.has_guest(): + self.guest["language"] = locale["id"] + self.guest["current_language"] = locale["id"] + self.guest["locale"] = locale.get("tag") or self.guest.get("locale") or "en_US" self.profile = { "id": locale["id"], "username": locale["id"], "nickname": locale["country"], - "email": locale["language"], + "email": "", "phone": "", "badge": "", "vipday": 0, @@ -90,8 +113,25 @@ class DramaBoxClient: def clear(self) -> None: self.token = "" self.web_token = "" + self.web_user = {} self.profile = {} + self.app = {} + self.guest = {} self.save() + def has_app(self) -> bool: + token = str(self.app.get("token") or "") + return token.startswith("Bearer ") and bool(self.app.get("device_id")) and bool(self.app.get("android_id")) + + def has_guest(self) -> bool: + guest = self.guest if isinstance(self.guest, dict) else {} + token = str(guest.get("token") or "") + if guest.get("vip") is True: + return False + return token.startswith("Bearer ") and bool(guest.get("device_id")) and bool(guest.get("android_id")) + + def can_browse(self) -> bool: + return self.has_app() or self.has_guest() + client = DramaBoxClient() diff --git a/server/services/dramabox/downloads.py b/server/services/dramabox/downloads.py index 698870d..10c6dfa 100644 --- a/server/services/dramabox/downloads.py +++ b/server/services/dramabox/downloads.py @@ -1,9 +1,10 @@ from pathlib import Path from server.services.downloads import DownloadManager, _plain_text -from server.services.dramabox import api +from server.services.dramabox.app_api import book_brief from server.services.dramabox.client import USER_AGENT, client from server.services.dramabox.covers import covers +from server.services.dramabox.private_mp4 import decrypt_file_if_needed from server.services.dramabox import playlist as db_playlist ROOT = Path(__file__).resolve().parents[3] @@ -21,16 +22,13 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) tags = "" count = "" try: - detail = api.book_detail(str(drama_id)) - book = detail.get("book") if isinstance(detail, dict) else None - if isinstance(book, dict): - fetched = str(book.get("bookName") or "").strip() - if fetched: - name = fetched - desc = _plain_text(book.get("introduction") or "") - language = str(book.get("simpleLanguage") or language) - tags = "、".join(str(item) for item in (book.get("typeTwoNames") or []) if item) - count = str(book.get("chapterCount") or "") + detail = book_brief(str(drama_id)) + fetched = detail.get("name") or "" + if fetched: + name = fetched + desc = _plain_text(detail.get("introduction") or "") + tags = detail.get("tags") or "" + count = detail.get("count") or "" profile = client.profile or {} country = str(profile.get("country") or "") except Exception: @@ -65,4 +63,5 @@ downloads = DownloadManager( read_cover=_read_cover, current_auth=_auth, headers={"User-Agent": USER_AGENT, "Referer": "https://www.dramaboxapp.com/", "Origin": "https://www.dramaboxapp.com"}, + prepare_file=decrypt_file_if_needed, ) diff --git a/server/services/dramabox/locales.py b/server/services/dramabox/locales.py index 8cf588d..f4577fb 100644 --- a/server/services/dramabox/locales.py +++ b/server/services/dramabox/locales.py @@ -1,21 +1,21 @@ LOCALES = ( - {"id": "en", "country": "美国", "language": "英语", "native": "English"}, - {"id": "zhHans", "country": "中国大陆", "language": "简体中文", "native": "简体中文"}, - {"id": "ko", "country": "韩国", "language": "韩语", "native": "한국어"}, - {"id": "zh", "country": "中国台湾", "language": "繁体中文", "native": "繁體中文"}, - {"id": "es", "country": "西班牙", "language": "西班牙语", "native": "Español"}, - {"id": "in", "country": "印度尼西亚", "language": "印尼语", "native": "Bahasa Indonesia"}, - {"id": "ja", "country": "日本", "language": "日语", "native": "日本語"}, - {"id": "de", "country": "德国", "language": "德语", "native": "Deutsch"}, - {"id": "fr", "country": "法国", "language": "法语", "native": "Français"}, - {"id": "pt", "country": "巴西", "language": "葡萄牙语", "native": "Português"}, - {"id": "ar", "country": "阿拉伯", "language": "阿拉伯语", "native": "العربية"}, - {"id": "th", "country": "泰国", "language": "泰语", "native": "ไทย"}, - {"id": "tl", "country": "菲律宾", "language": "菲律宾语", "native": "Filipino"}, - {"id": "vi", "country": "越南", "language": "越南语", "native": "Tiếng Việt"}, - {"id": "it", "country": "意大利", "language": "意大利语", "native": "Italiano"}, - {"id": "tr", "country": "土耳其", "language": "土耳其语", "native": "Türkçe"}, - {"id": "pl", "country": "波兰", "language": "波兰语", "native": "Polski"}, + {"id": "en", "country": "美国", "language": "英语", "native": "English", "tag": "en_US"}, + {"id": "zhHans", "country": "中国大陆", "language": "简体中文", "native": "简体中文", "tag": "zh_CN"}, + {"id": "ko", "country": "韩国", "language": "韩语", "native": "한국어", "tag": "ko_KR"}, + {"id": "zh", "country": "中国台湾", "language": "繁体中文", "native": "繁體中文", "tag": "zh_TW"}, + {"id": "es", "country": "西班牙", "language": "西班牙语", "native": "Español", "tag": "es_ES"}, + {"id": "in", "country": "印度尼西亚", "language": "印尼语", "native": "Bahasa Indonesia", "tag": "in_ID"}, + {"id": "ja", "country": "日本", "language": "日语", "native": "日本語", "tag": "ja_JP"}, + {"id": "de", "country": "德国", "language": "德语", "native": "Deutsch", "tag": "de_DE"}, + {"id": "fr", "country": "法国", "language": "法语", "native": "Français", "tag": "fr_FR"}, + {"id": "pt", "country": "巴西", "language": "葡萄牙语", "native": "Português", "tag": "pt_BR"}, + {"id": "ar", "country": "阿拉伯", "language": "阿拉伯语", "native": "العربية", "tag": "ar_SA"}, + {"id": "th", "country": "泰国", "language": "泰语", "native": "ไทย", "tag": "th_TH"}, + {"id": "tl", "country": "菲律宾", "language": "菲律宾语", "native": "Filipino", "tag": "tl_PH"}, + {"id": "vi", "country": "越南", "language": "越南语", "native": "Tiếng Việt", "tag": "vi_VN"}, + {"id": "it", "country": "意大利", "language": "意大利语", "native": "Italiano", "tag": "it_IT"}, + {"id": "tr", "country": "土耳其", "language": "土耳其语", "native": "Türkçe", "tag": "tr_TR"}, + {"id": "pl", "country": "波兰", "language": "波兰语", "native": "Polski", "tag": "pl_PL"}, ) DEFAULT_LANGUAGE = "th" diff --git a/server/services/dramabox/login.py b/server/services/dramabox/login.py index 6ec7a9a..3a21048 100644 --- a/server/services/dramabox/login.py +++ b/server/services/dramabox/login.py @@ -9,72 +9,54 @@ def languages() -> list[dict]: 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 apply_account(language: str, user: dict) -> dict: - if not isinstance(user, dict): - raise RuntimeError("还没有登录成功") - web_token = str(user.get("token") or "").strip() - if not web_token or not _logged_in(user.get("isLogin")): - raise RuntimeError("还没有登录成功") +def import_adb(serial: str, language: str = "") -> dict: + from server.services.dramabox.app_device import read_app_login + + record = read_app_login(serial) try: - locale = resolve(language or client.language or DEFAULT_LANGUAGE) + locale = resolve(language or record.get("language") or client.language or DEFAULT_LANGUAGE) except RuntimeError: locale = resolve(DEFAULT_LANGUAGE) if not client.token: client.token = secrets.token_hex(16) client.language = locale["id"] - client.web_token = web_token - profile = _account_profile(locale, user) - client.profile = profile - client.save() - return {"token": client.token, "profile": profile} - - -def _logged_in(value) -> bool: - if value is True: - return True - if isinstance(value, (int, float)) and int(value) == 1: - return True - text = str(value or "").strip().lower() - return text in {"1", "true", "yes"} - - -def _account_profile(locale: dict, user: dict) -> dict: - nickname = str(user.get("nickname") or user.get("name") or user.get("email") or locale.get("country") or "").strip() - email = str(user.get("email") or "").strip() - avatar = str(user.get("avatar") or user.get("userLogo") or user.get("avatarNumUrl") or "").strip() - if not avatar.startswith(("http://", "https://")): - avatar = "" - vip = _logged_in(user.get("isVip")) - return { - "id": user.get("uid") or user.get("id") or "", - "username": email or nickname, - "nickname": nickname or "DramaBox", - "email": email, + 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"] + nickname = str(record.get("name") or record.get("user_id") or "DramaBox") + client.profile = { + "id": record.get("user_id") or "", + "username": nickname, + "nickname": nickname, + "email": "", "phone": "", - "badge": "VIP" if vip else "", - "vipday": 1 if vip else 0, - "score": _number(user.get("coins")), + "badge": "VIP" if record.get("vip") else "", + "vipday": 1 if record.get("vip") else 0, + "score": 0, "watched": 0, - "rewards": _number(user.get("bonus")), + "rewards": 0, "login_day": 0, "country": locale.get("country") or "", "language": locale.get("language") or "", "native": locale.get("native") or "", - "locale": locale.get("locale") or locale.get("id") or "", - "loginType": str(user.get("loginType") or ""), + "locale": locale.get("id") or "", + "loginType": "app", "has_login": "1", - "avatarNumUrl": avatar, + "app_login": "1", + "avatarNumUrl": "", } - - -def _number(value) -> int: - try: - return int(float(str(value or "0"))) - except (TypeError, ValueError): - return 0 + client.save() + from server.services.dramabox.app_api import ensure_guest + ensure_guest() + return {"token": client.token, "profile": client.profile} def resume() -> dict: diff --git a/server/services/dramabox/playlist.py b/server/services/dramabox/playlist.py index 60c9a9b..7bc3e6b 100644 --- a/server/services/dramabox/playlist.py +++ b/server/services/dramabox/playlist.py @@ -1,6 +1,4 @@ -import json import re -from pathlib import Path from urllib.parse import quote, urljoin from server.services.dramabox import api @@ -8,20 +6,18 @@ from server.services.dramabox.client import client from server.services.http import http from server.services.playlist import is_direct_media, looks_like_segment -CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "dramabox" / "playlists" - def load_episodes(drama_id: str, language: str = "") -> list[dict]: drama_id = str(drama_id or "").strip() language = (language or client.language).strip() if not drama_id: raise RuntimeError("没有这部剧") - cached = _read_cache(drama_id, language) - fresh = _fetch_episodes(drama_id, language) - merged, save = _merge(cached, fresh) - if save or (not cached and merged): - _write_cache(drama_id, language, merged) - return merged + # 分集只走 App 接口。登录页选的地区决定请求语言。 + if not client.can_browse(): + raise RuntimeError("请先进入 DramaBox") + from server.services.dramabox.app_api import load_app_episodes + + return load_app_episodes(drama_id) def episode_src(drama_id: str, cid: int) -> dict: @@ -48,106 +44,6 @@ def playback_playlist(src: str, drama_id: str = "") -> str: return _rewrite_playlist(http.read_text(variant_url, headers=headers), variant_url) -def _fetch_episodes(drama_id: str, language: str = "") -> list[dict]: - data = api.film(drama_id, language or None) - rows = data.get("chapterList") if isinstance(data, dict) else None - if not isinstance(rows, list) or not rows: - raise RuntimeError("没有读到分集") - episodes = [] - for item in rows: - if not isinstance(item, dict): - continue - cid = _int(item.get("id")) - idx = _int(item.get("index")) + 1 - if cid <= 0: - continue - if idx <= 0: - idx = len(episodes) + 1 - src, kind = _choose_src(item) - unlocked = item.get("unlock") is True - row = { - "cid": cid, - "idx": idx, - "title": str(item.get("name") or f"第{idx}集").strip() or f"第{idx}集", - "src": src, - "src_kind": kind, - "type": "free" if unlocked else "lock", - "price": _int(item.get("chapterPrice")), - "cover": str(item.get("cover") or ""), - "duration": _int(item.get("duration")), - "is_preview": False, - "preview_seconds": 0, - "hls_key": "", - "locked_reason": "" if src else ("需要解锁" if not unlocked else "没有可下载的地址"), - } - episodes.append(row) - if not episodes: - raise RuntimeError("没有读到分集") - return episodes - - -def _choose_src(item: dict) -> tuple[str, str]: - m3u8 = str(item.get("m3u8Url") or "").strip() - mp4 = str(item.get("mp4") or "").strip() - if m3u8 and not is_direct_media(m3u8): - return m3u8, "hls" - if mp4: - return mp4, "file" - if m3u8: - return m3u8, "file" if is_direct_media(m3u8) else "hls" - 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 _cache_file(drama_id: str, language: str = "") -> Path: - return CACHE_DIR / (language or client.language) / f"{drama_id}.json" - - -def _read_cache(drama_id: str, language: str = "") -> list[dict]: - path = _cache_file(drama_id, language) - if not path.is_file(): - return [] - try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return [] - rows = data.get("episodes") if isinstance(data, dict) else None - return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else [] - - -def _write_cache(drama_id: str, language: str, episodes: list[dict]) -> None: - path = _cache_file(drama_id, language) - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_suffix(".json.tmp") - temporary.write_text(json.dumps({"episodes": episodes}, ensure_ascii=False), encoding="utf-8") - temporary.replace(path) - - def _rewrite_playlist(text: str, base: str) -> str: lines = [] for line in text.splitlines(): @@ -171,10 +67,3 @@ def _rewrite_tag(line: str, base: str) -> str: def _proxy_url(url: str) -> str: return "/api/dramabox/play/segment?url=" + quote(url, safe="") - - -def _int(value) -> int: - try: - return int(float(str(value))) - except (TypeError, ValueError): - return 0 diff --git a/server/services/dramabox/private_mp4.py b/server/services/dramabox/private_mp4.py new file mode 100644 index 0000000..c211e6e --- /dev/null +++ b/server/services/dramabox/private_mp4.py @@ -0,0 +1,241 @@ +"""阿里云 License 私有加密 MP4:从文件里的 AliyunPrivateKeyUri 解开样本后才能播。""" +import base64 +import hashlib +import json +import struct +from pathlib import Path + +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + +# DramaBox 播放器 LicenseKey(APK AndroidManifest com.aliyun.alivc_license.licensekey_SEA) +_LICENSE_KEY = b"8PfuCPCwtaTqTB00lca1b30cbaa074865b30efce2c7108498" +_KEY_URI = b"AliyunPrivateKeyUri" +_CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"udta", b"meta"} + + +def is_aliyun_private_mp4(data: bytes) -> bool: + return bool(data) and data[4:8] == b"ftyp" and _KEY_URI in data + + +def decrypt_if_needed(data: bytes) -> bytes: + if not is_aliyun_private_mp4(data): + return data + return decrypt_mp4(data) + + +def decrypt_file_if_needed(path) -> bool: + target = Path(path) + data = target.read_bytes() + if not is_aliyun_private_mp4(data): + return False + decrypted = decrypt_mp4(data) + temporary = target.with_name(target.name + ".dec") + temporary.write_bytes(decrypted) + temporary.replace(target) + return True + + +def decrypt_mp4(data: bytes) -> bytes: + key = _content_key(data) + out = bytearray(data) + _decrypt_samples(out, key) + return bytes(out) + + +def _content_key(data: bytes) -> bytes: + uri = _aliyun_key_uri(data) + envelope = _aes_cbc(_md5_key(_LICENSE_KEY), _md5_key(_LICENSE_KEY), base64.b64decode(uri)) + obj = json.loads(_pkcs7(envelope).decode("utf-8")) + client_rand = str(obj.get("ClientRand") or "").encode("utf-8") + server_b64 = str(obj.get("ServerRand") or "") + plain_b64 = str(obj.get("PlainText") or "") + if not client_rand or not server_b64 or not plain_b64: + raise RuntimeError("加密视频缺少密钥字段") + k1 = _md5_key(client_rand) + server = _pkcs7(_aes_cbc(k1, k1, base64.b64decode(server_b64))) + k2 = _md5_key(client_rand + server) + content = _pkcs7(_aes_cbc(k2, k1, base64.b64decode(plain_b64))) + key = base64.b64decode(content) + if len(key) != 16: + raise RuntimeError("加密视频密钥长度不对") + return key + + +def _aliyun_key_uri(data: bytes) -> str: + moov = _find_top(data, b"moov") + if moov is None: + raise RuntimeError("加密视频没有 moov") + start, size = moov + keys = _find_box(data, start + 8, start + size, b"keys") + ilst = _find_box(data, start + 8, start + size, b"ilst") + if not keys or not ilst: + raise RuntimeError("没有读到加密密钥") + index = _meta_key_index(data, keys, _KEY_URI) + if index <= 0: + raise RuntimeError("没有读到加密密钥") + value = _ilst_text(data, ilst, index) + if len(value) < 80: + raise RuntimeError("没有读到加密密钥") + return value + + +def _meta_key_index(data, box, name: bytes) -> int: + offset, size = box + count = struct.unpack(">I", data[offset + 12:offset + 16])[0] + pos = offset + 16 + end = offset + size + for index in range(1, count + 1): + if pos + 8 > end: + break + key_size = struct.unpack(">I", data[pos:pos + 4])[0] + if key_size < 8 or pos + key_size > end: + break + if bytes(data[pos + 8:pos + key_size]) == name: + return index + pos += key_size + return 0 + + +def _ilst_text(data, box, index: int) -> str: + offset, size = box + tag = struct.pack(">I", index) + for item_at, item_size, kind in _walk(data, offset + 8, offset + size): + if kind != tag: + continue + for data_at, data_size, data_kind in _walk(data, item_at + 8, item_at + item_size): + if data_kind != b"data" or data_size <= 16: + continue + return bytes(data[data_at + 16:data_at + data_size]).decode("ascii", "ignore") + return "" + + +def _md5_key(buf: bytes) -> bytes: + return hashlib.md5(buf).digest()[4:12].hex().encode("ascii") + + +def _aes_cbc(key: bytes, iv: bytes, data: bytes) -> bytes: + if len(data) < 16 or len(data) % 16: + data = data[: len(data) - (len(data) % 16)] + decryptor = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor() + return decryptor.update(data) + decryptor.finalize() + + +def _aes_ecb(key: bytes, data: bytes) -> bytes: + decryptor = Cipher(algorithms.AES(key), modes.ECB()).decryptor() + return decryptor.update(data) + decryptor.finalize() + + +def _pkcs7(data: bytes) -> bytes: + if not data: + return data + pad = data[-1] + if 1 <= pad <= 16 and data.endswith(bytes([pad]) * pad): + return data[:-pad] + return data.rstrip(b"\x00") + + +def _decrypt_samples(data: bytearray, key: bytes) -> None: + moov = _find_top(data, b"moov") + if moov is None: + raise RuntimeError("加密视频没有 moov") + start, size = moov + for offset, box_size, kind in _walk(data, start + 8, start + size): + if kind != b"trak": + continue + for sample_at, sample_size in _iter_samples(data, offset, box_size): + aligned = sample_size - (sample_size % 16) + if aligned < 16: + continue + data[sample_at:sample_at + aligned] = _aes_ecb(key, bytes(data[sample_at:sample_at + aligned])) + + +def _find_top(data: bytes, name: bytes): + for offset, size, kind in _walk(data, 0, len(data)): + if kind == name: + return offset, size + return None + + +def _walk(data, start: int, end: int): + index = start + while index + 8 <= end: + size = struct.unpack(">I", data[index:index + 4])[0] + kind = bytes(data[index + 4:index + 8]) + header = 8 + if size == 1: + if index + 16 > end: + break + size = struct.unpack(">Q", data[index + 8:index + 16])[0] + header = 16 + if size < header or index + size > end: + break + yield index, size, kind + index += size + + +def _find_nested(data, start: int, end: int, name: bytes): + return _find_box(data, start, end, name, {b"mdia", b"minf", b"stbl", b"trak"}) + + +def _find_box(data, start: int, end: int, name: bytes, containers=None): + containers = _CONTAINERS if containers is None else containers + for offset, size, kind in _walk(data, start, end): + if kind == name: + return offset, size + if kind in containers: + inner = offset + (12 if kind == b"meta" else 8) + found = _find_box(data, inner, offset + size, name, containers) + if found: + return found + return None + + +def _iter_samples(data, trak_at: int, trak_size: int): + start, end = trak_at + 8, trak_at + trak_size + stsz = _find_nested(data, start, end, b"stsz") + stsc = _find_nested(data, start, end, b"stsc") + stco = _find_nested(data, start, end, b"stco") or _find_nested(data, start, end, b"co64") + if not stsz or not stsc or not stco: + return + sizes = _stsz(data, stsz) + chunks = _stco(data, stco) + rows = _stsc(data, stsc) + sample = 0 + for index, (first, per_chunk, _desc) in enumerate(rows): + last = rows[index + 1][0] - 1 if index + 1 < len(rows) else len(chunks) + for chunk in range(first - 1, last): + at = chunks[chunk] + for _ in range(per_chunk): + if sample >= len(sizes): + return + yield at, sizes[sample] + at += sizes[sample] + sample += 1 + + +def _stsz(data, box): + offset, _size = box + default = struct.unpack(">I", data[offset + 12:offset + 16])[0] + count = struct.unpack(">I", data[offset + 16:offset + 20])[0] + if default: + return [default] * count + return [struct.unpack(">I", data[offset + 20 + 4 * i:offset + 24 + 4 * i])[0] for i in range(count)] + + +def _stco(data, box): + offset, _size = box + kind = bytes(data[offset + 4:offset + 8]) + count = struct.unpack(">I", data[offset + 12:offset + 16])[0] + if kind == b"co64": + return [struct.unpack(">Q", data[offset + 16 + 8 * i:offset + 24 + 8 * i])[0] for i in range(count)] + return [struct.unpack(">I", data[offset + 16 + 4 * i:offset + 20 + 4 * i])[0] for i in range(count)] + + +def _stsc(data, box): + offset, _size = box + count = struct.unpack(">I", data[offset + 12:offset + 16])[0] + rows = [] + for i in range(count): + first, per_chunk, desc = struct.unpack(">III", data[offset + 16 + 12 * i:offset + 28 + 12 * i]) + rows.append((first, per_chunk, desc)) + return rows diff --git a/server/services/http.py b/server/services/http.py index ad4922f..e20d5f2 100644 --- a/server/services/http.py +++ b/server/services/http.py @@ -1,5 +1,7 @@ +import json import threading import time +from pathlib import Path from urllib.parse import quote from urllib.request import getproxies @@ -7,21 +9,17 @@ import httpx from server.services.device import DeviceProfile +PROXY_PATH = Path(__file__).resolve().parents[2] / "cache" / "proxy.json" + class HttpClient: def __init__(self) -> None: - self._proxy = { - "mode": "off", - "scheme": "http", - "host": "", - "port": "", - "username": "", - "password": "", - } + self._proxy = _empty_proxy() self._client: httpx.Client | None = None self._lock = threading.Lock() + self._load_proxy() - def configure_proxy(self, proxy: dict) -> None: + def configure_proxy(self, proxy: dict, *, persist: bool = True) -> None: data = proxy or {} mode = data.get("mode") or "off" if mode not in ("off", "system", "custom"): @@ -46,6 +44,41 @@ class HttpClient: "password": data.get("password") or "", } self._close_locked() + if persist: + self._save_proxy_locked() + + def proxy_view(self) -> dict: + with self._lock: + data = dict(self._proxy) + data["url"] = self.webview_proxy_url() + return data + + def _load_proxy(self) -> None: + try: + data = json.loads(PROXY_PATH.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return + if not isinstance(data, dict): + return + try: + self.configure_proxy(data, persist=False) + except RuntimeError: + return + + def _save_proxy_locked(self) -> None: + PROXY_PATH.parent.mkdir(parents=True, exist_ok=True) + temporary = PROXY_PATH.with_suffix(".json.tmp") + temporary.write_text(json.dumps(self._proxy, ensure_ascii=False), encoding="utf-8") + temporary.replace(PROXY_PATH) + + def webview_proxy_url(self) -> str: + mode = self._proxy["mode"] + if mode == "off": + return "" + if mode == "custom": + return _webview_proxy(self._proxy_url()) + http_proxy, https_proxy = self._system_proxies() + return _webview_proxy(https_proxy or http_proxy) def request_json(self, method: str, url: str, token: str, device: DeviceProfile, body: dict | None) -> dict: data = self.request_data(method, url, token, device, body) @@ -160,12 +193,12 @@ class HttpClient: time.sleep(0.4) raise RuntimeError(f"下载失败: {last_error}") - def open_stream(self, url: str, headers: dict | None = None) -> httpx.Response: + def open_stream(self, url: str, headers: dict | None = None, timeout=None) -> httpx.Response: client = self._client_locked() hdrs = {"User-Agent": "RaptDrama"} if headers: hdrs.update(headers) - request = client.build_request("GET", url, headers=hdrs) + request = client.build_request("GET", url, headers=hdrs, timeout=timeout) response = client.send(request, stream=True) try: response.raise_for_status() @@ -217,6 +250,17 @@ class HttpClient: return _with_scheme(found.get("http")), _with_scheme(found.get("https")) +def _empty_proxy() -> dict: + return { + "mode": "off", + "scheme": "http", + "host": "", + "port": "", + "username": "", + "password": "", + } + + def _with_scheme(value: str | None) -> str: text = (value or "").strip() if text and "://" not in text: @@ -224,4 +268,11 @@ def _with_scheme(value: str | None) -> str: return text +def _webview_proxy(value: str) -> str: + text = (value or "").strip() + if text.startswith("socks5h://"): + return "socks5://" + text[len("socks5h://") :] + return text + + http = HttpClient() diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 92c0e8c..da52084 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,7 +1,7 @@ fn main() { tauri_build::try_build( tauri_build::Attributes::new().app_manifest( - tauri_build::AppManifest::new().commands(&["dramabox_login", "dramabox_clear_login"]), + tauri_build::AppManifest::new().commands(&["dramabox_clear_login"]), ), ) .expect("failed to run tauri-build"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 58ea834..8208c98 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -2,12 +2,10 @@ use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::process::{Child, Command}; -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; use std::time::{Duration, Instant}; -use tauri::webview::{NewWindowFeatures, NewWindowResponse}; -use tauri::{AppHandle, Manager, Url, WebviewUrl, WebviewWindowBuilder}; +use tauri::{AppHandle, Manager, Url}; struct Backend { child: Mutex>, @@ -204,212 +202,6 @@ fn disable_browser_chrome(window: &tauri::WebviewWindow) { } } -const DRAMABOX_LOGIN_LABEL: &str = "dramabox-login"; -const DRAMABOX_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"; -static DRAMABOX_POPUP_SEQ: AtomicU64 = AtomicU64::new(1); -const DRAMABOX_LOGIN_SCRIPT: &str = r#" -(function () { - if (window.__raptDramaLogin) return; - window.__raptDramaLogin = true; - var opened = false; - var attempts = 0; - var clickedAt = 0; - var stableSince = 0; - var lastMark = ""; - var cookiesDismissed = false; - var loaded = document.readyState === "complete"; - window.addEventListener("load", function () { loaded = true; }); - function dismissCookies() { - if (cookiesDismissed || opened) return; - var reject = document.querySelector('[class*="rejectBtn"]'); - if (!reject) return; - var rect = reject.getBoundingClientRect(); - if (rect.width < 2 || rect.height < 2) return; - cookiesDismissed = true; - reject.click(); - lastMark = ""; - stableSince = 0; - } - function onUserCenter() { - var path = location.pathname.replace(/\/+$/, "") || "/"; - return path === "/uc" || /\/uc$/.test(path); - } - function enterUserCenter() { - var data = window.__NEXT_DATA__; - if (!data || !data.locale) return; - var locale = data.locale; - var fallback = data.defaultLocale || "en"; - var target = locale === fallback ? "/uc" : "/" + locale + "/uc"; - var path = location.pathname.replace(/\/+$/, "") || "/"; - if (path !== target) location.assign(target); - } - function idNode() { - var marked = document.querySelectorAll('[class*="userId"]'); - var i; - for (i = 0; i < marked.length; i++) { - if (/^ID\s*\d+$/.test((marked[i].textContent || "").trim())) return marked[i]; - } - var nodes = document.querySelectorAll("div, span, p"); - for (i = 0; i < nodes.length; i++) { - var el = nodes[i]; - if (el.children.length) continue; - if (/^ID\s*\d+$/.test((el.textContent || "").trim())) return el; - } - return marked[0] || null; - } - function clickNode(el) { - ["pointerdown", "mousedown", "pointerup", "mouseup", "click"].forEach(function (type) { - el.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window })); - }); - } - function choicesOpen() { - return !!document.querySelector('[class*="loginBox"], [class*="loginCard"]'); - } - function nameMark(idEl) { - var name = idEl.previousElementSibling || idEl.parentElement; - if (!name) return ""; - var rect = name.getBoundingClientRect(); - if (rect.width < 2 || rect.height < 2) return ""; - return [Math.round(rect.left), Math.round(rect.top), Math.round(rect.width), Math.round(rect.height)].join("|"); - } - function pageAnimating() { - if (!document.getAnimations) return false; - var list = document.getAnimations(); - for (var i = 0; i < list.length; i++) { - var anim = list[i]; - if (anim.playState !== "running") continue; - var timing = anim.effect && anim.effect.getTiming ? anim.effect.getTiming() : null; - if (timing && timing.iterations === Infinity) continue; - return true; - } - return false; - } - function ensureConfirmBar() { - if (document.getElementById("rapt-logged-in")) return; - var bar = document.createElement("div"); - bar.id = "rapt-logged-in"; - bar.style.cssText = "position:fixed;left:0;right:0;bottom:0;z-index:2147483647;display:flex;justify-content:flex-end;gap:12px;padding:10px 16px;background:#2b2b2b;border-top:1px solid rgba(255,255,255,.08);"; - var button = document.createElement("button"); - button.type = "button"; - button.textContent = "已登录"; - button.style.cssText = "height:34px;min-width:120px;padding:0 16px;border:0;border-radius:6px;background:#3c3c3c;color:#f2f2f2;cursor:pointer;"; - button.addEventListener("click", function () { - try { sessionStorage.setItem("rapt_confirm_login", "1"); } catch (err) {} - location.reload(); - }); - bar.appendChild(button); - (document.body || document.documentElement).appendChild(bar); - } - function openChoices() { - ensureConfirmBar(); - if (!document.querySelector('[class*="toLogin"]') && idNode()) { - opened = true; - return; - } - if (choicesOpen()) { - opened = true; - return; - } - if (opened || !onUserCenter()) { - if (!onUserCenter()) enterUserCenter(); - return; - } - if (!loaded || document.readyState !== "complete" || attempts >= 2) return; - if (clickedAt && Date.now() - clickedAt < 3000) return; - dismissCookies(); - var idEl = idNode(); - var target = idEl && (idEl.previousElementSibling || idEl.parentElement); - var mark = idEl ? nameMark(idEl) : ""; - var now = Date.now(); - if (!target || !mark) { - lastMark = ""; - stableSince = 0; - return; - } - if (mark !== lastMark) { - lastMark = mark; - stableSince = now; - return; - } - var settled = now - stableSince; - if (settled < 1600) return; - if (pageAnimating() && settled < 4000) return; - attempts += 1; - clickedAt = now; - lastMark = ""; - stableSince = 0; - clickNode(target); - } - openChoices(); - setInterval(openChoices, 400); -})(); -"#; - -const DRAMABOX_ACCOUNT_SCRIPT: &str = r#"(function () { - function displayedName() { - if (document.querySelector('[class*="toLogin"]')) return ""; - var idNode = document.querySelector('[class*="userId"]'); - var name = idNode && idNode.previousElementSibling; - return name ? String(name.textContent || "").trim() : ""; - } - function match(user, displayed, confirmed) { - if (!user || typeof user !== "object" || !user.token) return null; - var flag = user.isLogin; - var kind = String(user.loginType || "").toLowerCase(); - var loggedIn = flag === true || flag === 1 || flag === "1" || String(flag).toLowerCase() === "true"; - var oauth = kind === "google" || kind === "facebook" || kind === "apple"; - var storedName = String(user.nickname || user.name || user.userName || "").trim(); - var samePerson = Boolean(displayed) && storedName === displayed; - var confirmedLogin = confirmed && Boolean(displayed); - if (!loggedIn && !oauth && !samePerson && !confirmedLogin) return null; - user.isLogin = true; - return user; - } - function parse(raw, displayed, confirmed) { - if (!raw) return null; - try { - var value = JSON.parse(raw); - return match(value, displayed, confirmed) || match(value.userInfo, displayed, confirmed) || match(value.user, displayed, confirmed) || match(value.data, displayed, confirmed); - } catch (err) { - return null; - } - } - function scan(store, displayed, confirmed) { - var direct = parse(store.getItem("dz_seo_user_info"), displayed, confirmed); - if (direct) return direct; - for (var i = 0; i < store.length; i++) { - var key = store.key(i) || ""; - if (key.indexOf("user_info") === -1 && key.indexOf("userInfo") === -1) continue; - var found = parse(store.getItem(key), displayed, confirmed); - if (found) return found; - } - return null; - } - var displayed = displayedName(); - var confirmed = false; - try { confirmed = sessionStorage.getItem("rapt_confirm_login") === "1"; } catch (err) {} - var found = null; - try { - found = scan(localStorage, displayed, confirmed) || scan(sessionStorage, displayed, confirmed); - } catch (err) {} - if (!found) { - var parts = String(document.cookie || "").split(";"); - for (var i = 0; i < parts.length; i++) { - var part = parts[i].replace(/^\s+/, ""); - var key = "dz_seo_user_info="; - if (part.indexOf(key) !== 0) continue; - var value = part.slice(key.length); - try { value = decodeURIComponent(value); } catch (err) {} - found = parse(value, displayed, confirmed); - if (found) break; - } - } - if (found && confirmed) { - try { sessionStorage.removeItem("rapt_confirm_login"); } catch (err) {} - } - return found; -})()"#; - fn dramabox_webview_dir() -> PathBuf { app_root().join("cache").join("dramabox").join("webview") } @@ -427,223 +219,12 @@ fn discard_dramabox_browser() { } } -fn dramabox_login_url(language: &str) -> Result { - let lang = language.trim(); - let allowed = [ - "en", "zhHans", "ko", "zh", "es", "in", "ja", "de", "fr", "pt", "ar", "th", "tl", "vi", "it", "tr", "pl", - ]; - if !allowed.contains(&lang) { - return Err("不支持这个语言地区".to_string()); - } - Ok(format!("https://www.dramaboxapp.com/{lang}/uc")) -} - -fn open_oauth_popup(app: &AppHandle, url: Url, features: NewWindowFeatures) -> NewWindowResponse { - let id = DRAMABOX_POPUP_SEQ.fetch_add(1, Ordering::Relaxed); - let label = format!("dramabox-popup-{id}"); - let nested = app.clone(); - let title = url.host_str().unwrap_or("登录").to_string(); - let blank = Url::parse("about:blank").expect("about:blank"); - let builder = WebviewWindowBuilder::new(app, &label, WebviewUrl::External(blank)) - .title(title) - .inner_size(520.0, 760.0) - .center() - .background_color(tauri::window::Color(54, 54, 54, 255)) - .user_agent(DRAMABOX_UA) - .window_features(features) - .on_document_title_changed(|window, title| { - let _ = window.set_title(&title); - }) - .on_new_window(move |next_url, next_features| open_oauth_popup(&nested, next_url, next_features)); - match builder.build() { - Ok(window) => { - let _ = window.set_focus(); - NewWindowResponse::Create { window } - } - Err(err) => { - eprintln!("DramaBox 登录弹窗失败: {err}"); - NewWindowResponse::Deny - } - } -} - -fn logged_in_account(value: &serde_json::Value) -> bool { - let Some(user) = value.as_object() else { - return false; - }; - let token = user.get("token").and_then(|item| item.as_str()).unwrap_or(""); - if token.is_empty() { - return false; - } - match user.get("isLogin") { - Some(serde_json::Value::Bool(flag)) => *flag, - Some(serde_json::Value::Number(number)) => number.as_i64() == Some(1), - Some(serde_json::Value::String(text)) => text == "1" || text.eq_ignore_ascii_case("true"), - _ => false, - } -} - -fn account_from_script(result: &str) -> Option { - let text = result.trim(); - if text.is_empty() || text == "null" { - return None; - } - let value: serde_json::Value = serde_json::from_str(text).ok()?; - let value = match value.as_str() { - Some(inner) => serde_json::from_str(inner).unwrap_or(value), - None => value, - }; - if logged_in_account(&value) { - Some(value) - } else { - None - } -} - -fn read_login_account(window: &tauri::WebviewWindow) -> Option { - let (tx, rx) = std::sync::mpsc::channel(); - let started = window.with_webview(move |webview| { - #[cfg(windows)] - unsafe { - use webview2_com::ExecuteScriptCompletedHandler; - use windows_core::HSTRING; - let Ok(core) = webview.controller().CoreWebView2() else { - let _ = tx.send(String::new()); - return; - }; - let script = HSTRING::from(DRAMABOX_ACCOUNT_SCRIPT); - let callback = tx.clone(); - let handler = ExecuteScriptCompletedHandler::create(Box::new(move |_, result| { - let _ = callback.send(result); - Ok(()) - })); - if core.ExecuteScript(&script, &handler).is_err() { - let _ = tx.send(String::new()); - } - } - #[cfg(not(windows))] - { - let _ = webview; - let _ = tx.send(String::new()); - } - }); - if started.is_err() { - return None; - } - let result = rx.recv_timeout(Duration::from_secs(3)).unwrap_or_default(); - account_from_script(&result) -} - -fn close_login_windows(app: &AppHandle) { - if let Some(current) = app.get_webview_window(DRAMABOX_LOGIN_LABEL) { - let _ = current.close(); - } - for (label, window) in app.webview_windows() { - if label.starts_with("dramabox-popup-") { - let _ = window.close(); - } - } -} - -fn open_login_window(app: &AppHandle, url: Url) -> Result<(), String> { - close_login_windows(app); - let popup_app = app.clone(); - let window = WebviewWindowBuilder::new(app, DRAMABOX_LOGIN_LABEL, WebviewUrl::External(url)) - .title("DramaBox 登录") - .inner_size(1100.0, 820.0) - .center() - .background_color(tauri::window::Color(54, 54, 54, 255)) - .user_agent(DRAMABOX_UA) - .data_directory(dramabox_webview_dir()) - .on_new_window(move |next_url, features| open_oauth_popup(&popup_app, next_url, features)) - .on_page_load(|webview, payload| { - if payload.event() == tauri::webview::PageLoadEvent::Finished { - let _ = webview.eval(DRAMABOX_LOGIN_SCRIPT); - } - }) - .build() +// 退出时清掉以前网页登录留下的浏览数据。 +#[tauri::command] +async fn dramabox_clear_login() -> Result<(), String> { + tauri::async_runtime::spawn_blocking(discard_dramabox_browser) + .await .map_err(|err| err.to_string())?; - let _ = window.set_focus(); - Ok(()) -} - -#[tauri::command] -async fn dramabox_login(app: AppHandle, language: String) -> Result { - let page = dramabox_login_url(&language)?; - let url = Url::parse(&page).map_err(|err| err.to_string())?; - let (tx, rx) = std::sync::mpsc::channel(); - let opener = app.clone(); - app.run_on_main_thread(move || { - close_login_windows(&opener); - let _ = tx.send(()); - }) - .map_err(|err| err.to_string())?; - tauri::async_runtime::spawn_blocking(move || rx.recv()) - .await - .map_err(|err| err.to_string())? - .map_err(|_| "登录窗口没有打开".to_string())?; - - let (tx, rx) = std::sync::mpsc::channel(); - let opener = app.clone(); - app.run_on_main_thread(move || { - let _ = tx.send(open_login_window(&opener, url)); - }) - .map_err(|err| err.to_string())?; - tauri::async_runtime::spawn_blocking(move || rx.recv()) - .await - .map_err(|err| err.to_string())? - .map_err(|_| "登录窗口没有打开".to_string())??; - - let watcher = app.clone(); - tauri::async_runtime::spawn_blocking(move || { - let deadline = Instant::now() + Duration::from_secs(10 * 60); - loop { - if Instant::now() >= deadline { - if let Some(current) = watcher.get_webview_window(DRAMABOX_LOGIN_LABEL) { - let _ = current.close(); - } - return Err("登录超时".to_string()); - } - std::thread::sleep(Duration::from_millis(400)); - let Some(current) = watcher.get_webview_window(DRAMABOX_LOGIN_LABEL) else { - return Err("登录已取消".to_string()); - }; - let mut windows = vec![current]; - for (label, popup) in watcher.webview_windows() { - if label.starts_with("dramabox-popup-") { - windows.push(popup); - } - } - for window in windows { - if let Some(account) = read_login_account(&window) { - close_login_windows(&watcher); - return Ok(account); - } - } - } - }) - .await - .map_err(|err| err.to_string())? -} - -#[tauri::command] -async fn dramabox_clear_login(app: AppHandle) -> Result<(), String> { - let (tx, rx) = std::sync::mpsc::channel(); - let opener = app.clone(); - app.run_on_main_thread(move || { - close_login_windows(&opener); - let _ = tx.send(()); - }) - .map_err(|err| err.to_string())?; - tauri::async_runtime::spawn_blocking(move || rx.recv()) - .await - .map_err(|err| err.to_string())? - .map_err(|_| "没有清掉登录凭据".to_string())?; - tauri::async_runtime::spawn_blocking(move || { - discard_dramabox_browser(); - }) - .await - .map_err(|err| err.to_string())?; Ok(()) } @@ -683,7 +264,7 @@ pub fn run() { prepare_webview_runtime(&root); tauri::Builder::default() .plugin(tauri_plugin_opener::init()) - .invoke_handler(tauri::generate_handler![dramabox_login, dramabox_clear_login]) + .invoke_handler(tauri::generate_handler![dramabox_clear_login]) .setup(|app| { app.manage(Backend { child: Mutex::new(None), diff --git a/tests/test_dramabox.py b/tests/test_dramabox.py index 74c758a..b9ad6f9 100644 --- a/tests/test_dramabox.py +++ b/tests/test_dramabox.py @@ -1,5 +1,21 @@ +import base64 +import json +import struct +from pathlib import Path + +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + +from server.services.dramabox.app_api import _choose_media +from server.services.dramabox.app_sign import native_sign, rsa_sign from server.services.dramabox.locales import film_path, public_list, resolve -from server.services.dramabox.playlist import _choose_src +from server.services.dramabox.private_mp4 import ( + _LICENSE_KEY, + _md5_key, + decrypt_file_if_needed, + decrypt_if_needed, + decrypt_mp4, + is_aliyun_private_mp4, +) from server.services.playlist import is_direct_media @@ -12,6 +28,8 @@ def test_locales_and_film_path() -> None: thai = resolve("th") assert thai["country"] == "泰国" assert thai["language"] == "泰语" + assert thai["tag"] == "th_TH" + assert resolve("zhHans")["tag"] == "zh_CN" assert film_path("en", "41000119953") == "/film/41000119953" assert film_path("th", "41000119953") == "/th/film/41000119953" try: @@ -22,26 +40,79 @@ def test_locales_and_film_path() -> None: raise AssertionError("未知语言应拒绝") +def test_app_sign_matches_the_native_samples() -> None: + assert native_sign("hello") == "cK4n10B_0tTQBrxFeeHFRDTW" + assert native_sign("hello!") == "cK4n10B_0tTQBrxF11GlpwK_" + assert len(rsa_sign("hello-sign")) == 344 + + +def test_guest_device_matches_app_first_open() -> None: + from server.services.dramabox.app_api import _guest_from_bootstrap, new_device + + device = new_device({ + "brand": "vivo", + "model": "PJJ110", + "manufacturer": "vivo", + "os_version": "12", + "language": "th", + "locale": "zh_CN", + "device_score": 8, + }) + assert len(device["device_id"]) == 36 + assert "-" in device["device_id"] + assert len(device["android_id"]) == 32 + assert "-" not in device["android_id"] + assert device["android_id"] == device["android_id"].lower() + assert len(device["instance_id"]) == 32 + assert device["cid"] == "CODE00001" + assert device["nchid"] == "CODE00001" + assert device["brand"] == "vivo" + assert device["model"] == "PJJ110" + assert device["token"] == "" + assert device["install_time"].isdigit() + assert device["locale"] == "zh_CN" + fresh = new_device(None) + assert len(fresh["android_id"]) == 32 + assert "-" not in fresh["android_id"] + assert len(fresh["device_id"]) == 36 + assert fresh["cid"] == "CODE00001" + assert fresh["nchid"] == "CODE00001" + assert fresh["token"] == "" + assert fresh["brand"] == "google" + guest = _guest_from_bootstrap(device, {"user": {"token": "abc", "uid": 99, "isVip": 0}}) + assert guest["token"] == "Bearer abc" + assert guest["user_id"] == "99" + assert guest["vip"] is False + try: + _guest_from_bootstrap(device, {"user": {"token": "abc", "uid": 1, "isVip": 1}}) + except RuntimeError as exc: + assert "访客" in str(exc) + else: + raise AssertionError("VIP 身份不能当访客") + try: + _guest_from_bootstrap(device, {"user": {"token": "", "uid": 0, "isVip": 0}}) + except RuntimeError: + pass + else: + raise AssertionError("空令牌不能当访客") + + def test_chapter_source_choice() -> None: - src, kind = _choose_src({ - "m3u8Url": "https://cdn.example/ep1.m3u8?sig=1", - "mp4": "https://cdn.example/ep1.mp4?sig=1", - "unlock": True, + src = _choose_media({ + "cdnList": [{ + "videoPathList": [ + {"quality": 720, "videoPath": "https://cdn.example/ep2.720p.mp4?sig=1"}, + {"quality": 1080, "videoPath": "https://cdn.example/ep2.1080p.mp4?sig=1"}, + {"quality": 1080, "videoPath": "https://cdn.example/ep2.15s.mp4?sig=1"}, + ], + }], }) - assert kind == "hls" - assert src.endswith(".m3u8?sig=1") - - src, kind = _choose_src({ - "m3u8Url": "", - "mp4": "https://cdn.example/ep2.mp4?sig=1", - "unlock": True, - }) - assert kind == "file" + assert src.endswith("1080p.mp4?sig=1") assert is_direct_media(src) - - src, kind = _choose_src({"unlock": False}) - assert src == "" - assert kind == "" + assert _choose_media({ + "cdnList": [{"videoPathList": [{"quality": 720, "videoPath": "https://cdn.example/preview.mp4"}]}], + }) == "" + assert _choose_media({}) == "" def test_download_keeps_region_and_rejects_silent_file() -> None: @@ -105,27 +176,6 @@ def test_download_keeps_region_and_rejects_silent_file() -> None: assert not (folder / "MP4" / "第1集.mp4").exists() -def test_account_profile_does_not_keep_the_site_token() -> None: - from server.services.dramabox.login import _account_profile - - profile = _account_profile( - {"country": "泰国", "language": "泰语", "native": "ไทย", "locale": "th"}, - { - "token": "site-token-value", - "isLogin": True, - "isVip": True, - "email": "reader@example.com", - "name": "Reader", - "uid": 42, - }, - ) - assert profile["nickname"] == "Reader" - assert profile["email"] == "reader@example.com" - assert profile["badge"] == "VIP" - assert profile["has_login"] == "1" - assert "site-token-value" not in profile.values() - - def test_download_workers_stay_on_their_own_platform() -> None: import tempfile from pathlib import Path @@ -145,9 +195,394 @@ def test_download_workers_stay_on_their_own_platform() -> None: assert reloaded.settings_view()["workers"] == 2 +def test_plain_mp4_is_left_alone() -> None: + plain = b"\x00\x00\x00\x18ftypisom" + bytes(8) + assert not is_aliyun_private_mp4(plain) + assert decrypt_if_needed(plain) is plain + + +def test_aliyun_private_mp4_roundtrip() -> None: + data, plain_sample = _private_clip() + assert is_aliyun_private_mp4(data) + out = decrypt_mp4(data) + moov = out.find(b"mdat") + payload = out[moov + 4:] + size = struct.unpack(">I", out[moov - 4:moov])[0] + sample = payload[: size - 8] + assert sample == plain_sample + assert sample[4] == 0x65 + + +def test_download_decrypts_private_file() -> None: + import tempfile + from pathlib import Path as Dest + + import server.services.downloads as downloads + from server.services.downloads import DownloadManager + + data, plain_sample = _private_clip() + with tempfile.TemporaryDirectory() as tmp: + root = Dest(tmp) + folder = root / "drama" + row = {"cid": 1, "idx": 1, "title": "第1集", "src": "https://cdn.example/a.mp4", "phase": "pending"} + manager = DownloadManager( + state_dir=root / "state", + default_directory=str(root / "out"), + prepare_file=decrypt_file_if_needed, + ) + manager._jobs["1"] = { + "id": "1", + "status": "downloading", + "command": "", + "folder": str(folder), + "episodes": [dict(row)], + } + + def fake_download(_url, dest, on_chunk=None, stop=None, headers=None): + Dest(dest).parent.mkdir(parents=True, exist_ok=True) + Dest(dest).write_bytes(data) + return len(data) + + original_download = downloads.http.download_file + original_audio = downloads.has_audio + downloads.http.download_file = fake_download + downloads.has_audio = lambda _path: True + try: + manager._download_direct("1", folder, row) + finally: + downloads.http.download_file = original_download + downloads.has_audio = original_audio + saved = (folder / "MP4" / "第1集.mp4").read_bytes() + assert saved[4:8] == b"ftyp" + assert plain_sample in saved + + +def test_play_file_decrypts_and_caches() -> None: + from server.routes import dramabox as route + + data, plain_sample = _private_clip() + + class Upstream: + def iter_bytes(self, _size): + yield data + + def close(self): + return None + + original = route.http.open_stream + route._play_files.clear() + calls = {"n": 0} + + def fake_stream(*_args, **_kwargs): + calls["n"] += 1 + return Upstream() + + route.http.open_stream = fake_stream + try: + first = route._load_play_file("42000028209", 701724013, "https://cdn.example/a.mp4") + second = route._load_play_file("42000028209", 701724013, "https://cdn.example/a.mp4") + finally: + route.http.open_stream = original + route._play_files.clear() + assert first == second + assert calls["n"] == 1 + assert plain_sample in first + assert first[4:8] == b"ftyp" + + +def test_play_file_accepts_byte_ranges() -> None: + from server.routes.dramabox import _parse_byte_range, _ranged_mp4 + + data = b"0123456789" * 10 + full = _ranged_mp4(data, None) + assert full.status_code == 200 + assert full.headers["accept-ranges"] == "bytes" + assert full.body == data + + probe = _ranged_mp4(data, "bytes=0-1") + assert probe.status_code == 206 + assert probe.body == b"01" + assert probe.headers["content-range"] == "bytes 0-1/100" + assert probe.headers["content-length"] == "2" + + tail = _ranged_mp4(data, "bytes=90-") + assert tail.status_code == 206 + assert tail.body == data[90:] + assert tail.headers["content-range"] == "bytes 90-99/100" + + suffix = _ranged_mp4(data, "bytes=-10") + assert suffix.body == data[-10:] + + whole = _ranged_mp4(data, "bytes=0-") + assert whole.status_code == 206 + assert whole.body == data + assert whole.headers["content-range"] == "bytes 0-99/100" + + missing = _ranged_mp4(data, "bytes=1000-1001") + assert missing.status_code == 416 + assert missing.headers["content-range"] == "bytes */100" + assert _parse_byte_range("", 100) is None + + +def test_live_encrypted_episode_if_present() -> None: + path = Path(r"C:\Users\Administrator\AppData\Local\Temp\dbx_enc.mp4") + if not path.is_file(): + return + data = path.read_bytes() + assert is_aliyun_private_mp4(data) + out = decrypt_mp4(data) + assert len(out) == len(data) + from server.services.dramabox import private_mp4 as mp4 + moov = mp4._find_top(out, b"moov") + assert moov is not None + start, size = moov + tracks = [item for item in mp4._walk(out, start + 8, start + size) if item[2] == b"trak"] + assert tracks + offset, box_size, _kind = tracks[0] + ok = 0 + for at, sample_size in mp4._iter_samples(out, offset, box_size): + if _avc_sample(out, at, sample_size): + ok += 1 + else: + raise AssertionError("视频样本解开后不是有效 NAL") + assert ok > 1000 + + +def _private_clip() -> tuple[bytes, bytes]: + sample_key = b"0123456789abcdef" + sample_plain = struct.pack(">I", 12) + b"\x65" + bytes(11) + b"TAIL!" + aligned = len(sample_plain) - (len(sample_plain) % 16) + encryptor = Cipher(algorithms.AES(sample_key), modes.ECB()).encryptor() + cipher_sample = encryptor.update(sample_plain[:aligned]) + encryptor.finalize() + sample_plain[aligned:] + client_rand = b"1234567890123456" + server_plain = b"abcdef0123456789xyz" + k_lic = _md5_key(_LICENSE_KEY) + k1 = _md5_key(client_rand) + k2 = _md5_key(client_rand + server_plain) + content = base64.b64encode(sample_key) + envelope = json.dumps({ + "ClientRand": client_rand.decode("ascii"), + "ServerRand": base64.b64encode(_cbc_enc(k1, k1, server_plain)).decode("ascii"), + "PlainText": base64.b64encode(_cbc_enc(k2, k1, content)).decode("ascii"), + }, separators=(",", ":")) + uri = base64.b64encode(_cbc_enc(k_lic, k_lic, envelope.encode("utf-8"))).decode("ascii") + stsz = _full(b"stsz", struct.pack(">II", 0, 1) + struct.pack(">I", len(cipher_sample))) + stsc = _full(b"stsc", struct.pack(">I", 1) + struct.pack(">III", 1, 1, 1)) + stco = _full(b"stco", struct.pack(">I", 1) + struct.pack(">I", 0)) + trak = _box(b"trak", _box(b"mdia", _box(b"minf", _box(b"stbl", stsz + stsc + stco)))) + name = b"AliyunPrivateKeyUri" + keys = _full(b"keys", struct.pack(">I", 1) + struct.pack(">I", 8 + len(name)) + b"mdta" + name) + data_box = _box(b"data", b"\x00\x00\x00\x01\x00\x00\x00\x00" + uri.encode("ascii")) + ilst = _box(b"ilst", _box(b"\x00\x00\x00\x01", data_box)) + udta = _box(b"udta", _full(b"meta", keys + ilst)) + moov = _box(b"moov", trak + udta) + ftyp = _box(b"ftyp", b"isom" + struct.pack(">I", 0) + b"isom") + mdat = _box(b"mdat", cipher_sample) + data = bytearray(ftyp + moov + mdat) + pos = data.find(b"stco") + struct.pack_into(">I", data, pos + 12, len(ftyp) + len(moov) + 8) + return bytes(data), sample_plain + + +def _cbc_enc(key: bytes, iv: bytes, data: bytes) -> bytes: + pad = 16 - (len(data) % 16) + padded = data + bytes([pad]) * pad + encryptor = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor() + return encryptor.update(padded) + encryptor.finalize() + + +def _box(kind: bytes, payload: bytes) -> bytes: + return struct.pack(">I", 8 + len(payload)) + kind + payload + + +def _full(kind: bytes, payload: bytes) -> bytes: + return _box(kind, b"\x00\x00\x00\x00" + payload) + + +def _avc_sample(data: bytes, at: int, size: int) -> bool: + end = at + size + pos = at + nals = 0 + while pos + 4 <= end: + length = struct.unpack(">I", data[pos:pos + 4])[0] + if length == 0 or pos + 4 + length > end: + return False + nals += 1 + pos += 4 + length + return nals > 0 and pos == end + + +def test_catalog_page_limit_defaults_and_clamps() -> None: + import tempfile + from pathlib import Path + from unittest.mock import patch + + from server.services.dramabox import catalog as cat + + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "catalog-settings.json" + with patch.object(cat, "settings_path", lambda: path), patch.object(cat, "_drop_catalog_cache"): + assert cat.page_limit() == 300 + assert cat.set_page_limit(0) == 300 + assert cat.set_page_limit(-8) == 300 + assert cat.set_page_limit(12) == 12 + assert cat.page_limit() == 12 + assert cat.set_page_limit(5000) == 999 + assert json.loads(path.read_text(encoding="utf-8"))["max_pages"] == 999 + + +def test_explore_loads_recommend_book_pages() -> None: + from unittest.mock import patch + + from server.services.dramabox import catalog as cat + + calls = [] + + def fake_post(path, payload): + calls.append((path.rsplit("/", 1)[-1], payload.get("pageNo"), payload.get("specialColumnId"))) + page = payload.get("pageNo") or 1 + if path.endswith("recommendBook"): + if page > 3: + return {"recommendList": {"records": [], "current": page, "pages": page, "size": 9, "total": 27}} + return {"recommendList": {"records": [{"bookId": str(page), "bookName": f"剧{page}"}]}} + raise AssertionError(f"unexpected path {path}") + + home = { + "specialColumnId": 7, + "bannerList": [{"bookId": "b", "bookName": "横幅"}], + "recommendList": {"records": [{"bookId": "1", "bookName": "首屏"}]}, + } + seen: set[str] = set() + + def fresh(rows): + page = [] + for drama in rows: + if drama["id"] in seen: + continue + seen.add(drama["id"]) + page.append(drama) + return page + + with patch.object(cat, "_post", fake_post), patch.object(cat, "page_limit", lambda: 10): + pages = list(cat._explore_pages(112, 0, 1, home, fresh, "sess")) + titles = [item["title"] for page in pages for item in page] + assert titles == ["首屏", "横幅", "剧2", "剧3"] + assert calls == [("recommendBook", 2, 7), ("recommendBook", 3, 7), ("recommendBook", 4, 7)] + + +def test_explore_continues_when_a_page_is_all_duplicates() -> None: + from unittest.mock import patch + + from server.services.dramabox import catalog as cat + + def fake_post(path, payload): + page = payload.get("pageNo") or 1 + if page == 2: + records = [{"bookId": "1", "bookName": "首屏"}] + elif page == 3: + records = [{"bookId": "3", "bookName": "新剧"}] + else: + records = [] + return {"recommendList": {"records": records}} + + home = {"recommendList": {"records": [{"bookId": "1", "bookName": "首屏"}]}} + seen: set[str] = set() + + def fresh(rows): + page = [] + for drama in rows: + if drama["id"] in seen: + continue + seen.add(drama["id"]) + page.append(drama) + return page + + with patch.object(cat, "_post", fake_post), patch.object(cat, "page_limit", lambda: 8): + pages = list(cat._explore_pages(112, 0, 1, home, fresh, "sess")) + titles = [item["title"] for page in pages for item in page] + assert titles == ["首屏", "新剧"] + + +def test_explore_stops_before_the_next_page_request() -> None: + import threading + from unittest.mock import patch + + from server.services.dramabox import catalog as cat + + stop = threading.Event() + calls = [] + + def fake_post(path, payload): + calls.append(payload.get("pageNo")) + if payload.get("pageNo") == 2: + stop.set() + page = payload.get("pageNo") + return {"recommendList": {"records": [{"bookId": str(page), "bookName": f"剧{page}"}]}} + + home = {"recommendList": {"records": [{"bookId": "1", "bookName": "首屏"}]}} + seen: set[str] = set() + + def fresh(rows): + page = [] + for drama in rows: + if drama["id"] in seen: + continue + seen.add(drama["id"]) + page.append(drama) + return page + + with patch.object(cat, "_post", fake_post), patch.object(cat, "page_limit", lambda: 10): + pages = list(cat._explore_pages(112, 0, 1, home, fresh, "sess", stop)) + assert calls == [2] + assert [item["id"] for page in pages for item in page] == ["1", "2"] + + +def test_explore_stops_at_page_limit() -> None: + from unittest.mock import patch + + from server.services.dramabox import catalog as cat + + calls = [] + + def fake_post(path, payload): + calls.append(payload.get("pageNo")) + page = payload.get("pageNo") + return {"recommendList": {"records": [{"bookId": str(page), "bookName": f"剧{page}"}]}} + + home = {"recommendList": {"records": [{"bookId": "1", "bookName": "首屏"}]}} + seen: set[str] = set() + + def fresh(rows): + page = [] + for drama in rows: + if drama["id"] in seen: + continue + seen.add(drama["id"]) + page.append(drama) + return page + + with patch.object(cat, "_post", fake_post), patch.object(cat, "page_limit", lambda: 3): + pages = list(cat._explore_pages(112, 0, 1, home, fresh, "sess")) + assert calls == [2, 3] + assert [item["id"] for page in pages for item in page] == ["1", "2", "3"] + + if __name__ == "__main__": test_locales_and_film_path() + test_app_sign_matches_the_native_samples() + test_guest_device_matches_app_first_open() test_chapter_source_choice() test_download_keeps_region_and_rejects_silent_file() test_download_workers_stay_on_their_own_platform() + test_plain_mp4_is_left_alone() + test_aliyun_private_mp4_roundtrip() + test_download_decrypts_private_file() + test_play_file_decrypts_and_caches() + test_play_file_accepts_byte_ranges() + test_live_encrypted_episode_if_present() + test_catalog_page_limit_defaults_and_clamps() + test_explore_loads_recommend_book_pages() + test_explore_continues_when_a_page_is_all_duplicates() + test_explore_stops_before_the_next_page_request() + test_explore_stops_at_page_limit() print("ok") diff --git a/tests/test_proxy.py b/tests/test_proxy.py new file mode 100644 index 0000000..6009d71 --- /dev/null +++ b/tests/test_proxy.py @@ -0,0 +1,46 @@ +import json +import tempfile +from pathlib import Path +from unittest.mock import patch + +from server.services.http import HttpClient + + +def test_proxy_is_reloaded_after_restart() -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "proxy.json" + with patch("server.services.http.PROXY_PATH", path): + first = HttpClient() + first.configure_proxy({ + "mode": "custom", + "scheme": "http", + "host": "127.0.0.1", + "port": "7897", + "username": "", + "password": "", + }) + saved = json.loads(path.read_text(encoding="utf-8")) + assert saved["mode"] == "custom" + assert saved["host"] == "127.0.0.1" + assert saved["port"] == "7897" + + second = HttpClient() + view = second.proxy_view() + assert view["mode"] == "custom" + assert view["scheme"] == "http" + assert view["url"] == "http://127.0.0.1:7897" + + +def test_invalid_proxy_file_does_not_block_startup() -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "proxy.json" + path.write_text("{", encoding="utf-8") + with patch("server.services.http.PROXY_PATH", path): + client = HttpClient() + assert client.proxy_view()["mode"] == "off" + + +if __name__ == "__main__": + test_proxy_is_reloaded_after_restart() + test_invalid_proxy_file_does_not_block_startup() + print("ok") diff --git a/ui/src/App.vue b/ui/src/App.vue index e8fe5ad..1ddb9cd 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -76,11 +76,23 @@ interface ProxySettings { function emptyProxy(): ProxySettings { return { mode: "off", scheme: "http", host: "", port: "", username: "", password: "" }; } + +function normalizeProxy(value: Partial | null | undefined): ProxySettings { + const proxy = { ...emptyProxy(), ...(value || {}) }; + if (proxy.mode !== "off" && proxy.mode !== "system" && proxy.mode !== "custom") proxy.mode = "off"; + if (proxy.scheme !== "http" && proxy.scheme !== "socks5") proxy.scheme = "http"; + proxy.host = String(proxy.host || ""); + proxy.port = String(proxy.port || ""); + proxy.username = String(proxy.username || ""); + proxy.password = String(proxy.password || ""); + return proxy; +} const DEVICE_KEY = "rapt-device-settings"; const SESSION_DEVICE_KEY = "rapt-device"; const ACCOUNTS_KEY = "rapt-accounts"; const PLATFORM_KEY = "rapt-platform"; const DRAMABOX_LANG_KEY = "dramabox-language"; +const DRAMABOX_DEVICE_KEY = "dramabox-device"; const themeOverrides: GlobalThemeOverrides = { Form: { @@ -108,6 +120,7 @@ const platformLabel = computed(() => { const dramaboxLang = ref("th"); const dramaboxLangs = ref<{ label: string; value: string }[]>([]); const accountBusy = ref(false); +const activeProxyUrl = ref(""); const profileError = ref(""); const method = ref("guest"); const email = ref(""); @@ -120,6 +133,7 @@ const error = ref(""); const token = ref(""); const profile = ref(null); const dramaboxLoggedIn = computed(() => profile.value?.has_login === "1"); +const dramaboxDeviceReady = computed(() => devices.value.some((item) => item.state === "device")); const page = ref<"download" | "profile" | "progress" | "settings" | "play">("download"); const playing = ref<{ id: string | number; title: string; image: string } | null>(null); const progressCount = ref(0); @@ -150,6 +164,8 @@ const downloadRef = ref<{ loadDirectory: () => Promise; } | null>(null); const catalogQuery = ref(""); +const catalogMaxPages = ref(300); +let catalogPagesTimer: number | null = null; const mainMenu = computed(() => [ { label: "视频清单", key: "download" }, { @@ -192,7 +208,10 @@ function selectPlatform(key: string) { platform.value = key; localStorage.setItem(PLATFORM_KEY, key); error.value = ""; - if (key === "dramabox") void loadDramaboxLanguages(); + if (key === "dramabox") { + void loadDramaboxLanguages(); + void loadDevices(); + } } function tokenKey() { @@ -362,10 +381,7 @@ function loadSettings() { settings.value.custom = { ...builtinDevice.value, ...data.custom }; } if (data.proxy && typeof data.proxy === "object") { - const proxy = { ...emptyProxy(), ...data.proxy }; - if (proxy.mode !== "off" && proxy.mode !== "system" && proxy.mode !== "custom") proxy.mode = "off"; - if (proxy.scheme !== "http" && proxy.scheme !== "socks5") proxy.scheme = "http"; - settings.value.proxy = proxy; + settings.value.proxy = normalizeProxy(data.proxy); } } catch { settings.value.custom = { ...builtinDevice.value }; @@ -384,6 +400,50 @@ function normalizeWorkers(value: unknown) { return count; } +function normalizeCatalogPages(value: unknown) { + const count = Number(value); + if (!Number.isInteger(count) || count < 1) return 300; + return Math.min(count, 999); +} + +async function loadCatalogSettings() { + if (platform.value !== "dramabox") return; + try { + const response = await fetch("/api/dramabox/catalog/settings"); + if (!response.ok) return; + const payload = await response.json(); + catalogMaxPages.value = normalizeCatalogPages(payload.max_pages); + } catch { + catalogMaxPages.value = 300; + } +} + +async function saveCatalogMaxPages(value: number) { + const pages = normalizeCatalogPages(value); + catalogMaxPages.value = pages; + try { + const response = await fetch("/api/dramabox/catalog/settings", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ max_pages: pages }), + }); + if (!response.ok) return; + const payload = await response.json(); + catalogMaxPages.value = normalizeCatalogPages(payload.max_pages); + } catch { + // 下次刷新会重新读取 + } +} + +function onCatalogMaxPages(value: number | null) { + if (value === null) return; + catalogMaxPages.value = normalizeCatalogPages(value); + if (catalogPagesTimer) window.clearTimeout(catalogPagesTimer); + catalogPagesTimer = window.setTimeout(() => { + void saveCatalogMaxPages(catalogMaxPages.value); + }, 400); +} + async function loadDownloadSettings() { const response = await fetch(`${apiBase.value}/downloads/settings`); if (!response.ok) return; @@ -408,9 +468,16 @@ async function openSettings() { watch(page, (value) => { if (value === "settings") void enterSettings(); + if (value === "profile" && platform.value === "dramabox") void loadDevices(); }); +watch( + () => platform.value === "dramabox" && !!profile.value, + (ready) => { + if (ready) void loadCatalogSettings(); + }, + { immediate: true }, +); -// 打开页面时把本机保存的代理推给后端,避免进程重启后丢失。 async function applyProxy(proxy: ProxySettings) { const response = await fetch("/api/proxy", { method: "POST", @@ -421,6 +488,22 @@ async function applyProxy(proxy: ProxySettings) { if (!response.ok) { throw new Error(typeof payload.detail === "string" ? payload.detail : "代理设置失败"); } + activeProxyUrl.value = typeof payload.url === "string" ? payload.url : ""; +} + +// 代理存在后台文件里。页面地址每次启动端口不同,不能只靠浏览器本地存储。 +async function loadProxySettings() { + const response = await fetch("/api/proxy"); + if (response.ok) { + const payload = await response.json().catch(() => ({})); + const server = normalizeProxy(payload); + if (server.mode !== "off") { + settings.value.proxy = server; + activeProxyUrl.value = typeof payload.url === "string" ? payload.url : ""; + return; + } + } + if (settings.value.proxy.mode !== "off") await applyProxy(settings.value.proxy); } async function saveSettings() { @@ -446,14 +529,20 @@ async function saveSettings() { return; } const directory = draft.value.directory.trim(); - if (!directory) { - settingsTab.value = "download"; - settingsError.value = "请选择下载目录"; - return; - } settingsBusy.value = true; try { await applyProxy(proxy); + settings.value.proxy = copySettings(proxy); + localStorage.setItem(DEVICE_KEY, JSON.stringify({ + adbMode: settings.value.adbMode, + custom: settings.value.custom, + proxy: settings.value.proxy, + })); + if (!directory) { + settingsTab.value = "download"; + settingsError.value = "请选择下载目录"; + return; + } const response = await fetch(`${apiBase.value}/downloads/settings`, { method: "POST", headers: { "Content-Type": "application/json" }, @@ -595,6 +684,7 @@ function profileText(key: keyof Profile) { if (kind === "google") return "Google"; if (kind === "facebook") return "Facebook"; if (kind === "apple") return "Apple"; + if (kind === "app") return "设备"; return kind ? String(profile.value?.loginType) : "—"; } const value = profile.value?.[key]; @@ -617,12 +707,21 @@ function deviceLabel(item: Device) { return `${item.model} · ${item.serial} · ${mark}`; } +function rememberedSerial() { + try { + return localStorage.getItem(DRAMABOX_DEVICE_KEY) || ""; + } catch { + return ""; + } +} + function applyDeviceList(list: Device[]) { devices.value = list; const stillThere = devices.value.some((item) => item.serial === serial.value && item.state === "device"); if (!stillThere) { const ready = devices.value.filter((item) => item.state === "device"); - serial.value = ready.length === 1 ? ready[0].serial : null; + const remembered = ready.find((item) => item.serial === rememberedSerial()); + serial.value = remembered?.serial || (ready.length === 1 ? ready[0].serial : null); } } @@ -694,32 +793,35 @@ async function loginHuangdou() { } } -function errorText(exc: unknown, fallback: string) { - if (typeof exc === "string" && exc.trim()) return exc; - if (exc instanceof Error && exc.message) return exc.message; - return fallback; -} - -async function loginDramaboxAccount() { +async function loginDramaboxAdb() { const inside = Boolean(token.value); error.value = ""; profileError.value = ""; if (inside) accountBusy.value = true; else busy.value = true; try { - if (!inTauri()) throw new Error("请在桌面程序里登录"); - const { invoke } = await import("@tauri-apps/api/core"); - const language = dramaboxLang.value || profile.value?.locale || "th"; - const user = await invoke>("dramabox_login", { language }); - localStorage.setItem(DRAMABOX_LANG_KEY, language); - const response = await fetch("/api/dramabox/login/account", { + if (!serial.value) await loadDevices(); + if (!serial.value && error.value) throw new Error(error.value); + const ready = devices.value.filter((item) => item.state === "device"); + const picked = serial.value || ""; + if (!picked) { + throw new Error( + ready.length + ? "请选择设备" + : "没有检测到已连接的设备。手机请打开 USB 调试;MuMu 请先点探测。", + ); + } + serial.value = picked; + localStorage.setItem(DRAMABOX_DEVICE_KEY, picked); + localStorage.setItem(DRAMABOX_LANG_KEY, dramaboxLang.value); + const response = await fetch("/api/dramabox/login/adb", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ language, user }), + body: JSON.stringify({ serial: picked, language: dramaboxLang.value }), }); const payload = await response.json(); if (!response.ok) { - throw new Error(typeof payload.detail === "string" ? payload.detail : "登录失败"); + throw new Error(typeof payload.detail === "string" ? payload.detail : "读取登录失败"); } token.value = payload.token; profile.value = payload.profile; @@ -729,7 +831,7 @@ async function loginDramaboxAccount() { startLive(); } } catch (exc) { - const message = errorText(exc, "登录失败"); + const message = exc instanceof Error ? exc.message : "读取登录失败"; if (inside) profileError.value = message; else error.value = message; } finally { @@ -946,13 +1048,16 @@ onMounted(async () => { await loadDeviceDefaults(); loadSettings(); try { - await applyProxy(settings.value.proxy); + await loadProxySettings(); } catch { error.value = "代理还没有生效,请重新打开设置并保存"; } savedAccounts.value = readList(ACCOUNTS_KEY); if (savedAccounts.value[0]) applyAccount(savedAccounts.value[0].email); - if (platform.value === "dramabox") await loadDramaboxLanguages(); + if (platform.value === "dramabox") { + await loadDramaboxLanguages(); + void loadDevices(); + } let saved = readSavedToken(); if (!saved && isolated.value) { try { @@ -1001,6 +1106,27 @@ onUnmounted(stopLive); :options="mainMenu" @update:value="page = $event" /> +
+
+ 最大页数 + + + 每个分类最多翻这么多页。精选这类推荐流可能一直有新内容,到上限就会停下。改完后点刷新生效。 + +
+ +