feat: DramaBox 全量走 App 接口,清单可停止并避免卡死

分类按 App 翻页,精选走推荐接口。清单顶部显示进度,停止后不再拉新剧,已拿到的封面继续加载。列表只绘制可见卡片,避免大量剧目占满主线程。
This commit is contained in:
Nixevol
2026-10-24 03:03:27 +08:00
parent 241762451c
commit cea741eead
25 changed files with 2923 additions and 1070 deletions
+456
View File
@@ -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