feat: DramaBox 全量走 App 接口,清单可停止并避免卡死
分类按 App 翻页,精选走推荐接口。清单顶部显示进度,停止后不再拉新剧,已拿到的封面继续加载。列表只绘制可见卡片,避免大量剧目占满主线程。
This commit is contained in:
@@ -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'<script id="__NEXT_DATA__"[^>]*>(.*?)</script>', 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,
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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'<string name="{re.escape(name)}">(.*?)</string>', 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
|
||||
@@ -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")
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user