feat: 接入 DramaBox 并按语言地区切换清单

This commit is contained in:
Nixevol
2026-10-21 23:36:52 +08:00
parent 213614c735
commit 39774ad9cc
14 changed files with 1416 additions and 32 deletions
+1
View File
@@ -0,0 +1 @@
"""DramaBox 平台。会话、清单和下载与 RaptDrama / 黄豆短剧隔离。"""
+144
View File
@@ -0,0 +1,144 @@
import json
import re
from server.services.dramabox.client import SITE, USER_AGENT, WEBFIC, 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 []
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:
locale = resolve(language or client.language)["id"]
referer = SITE + (film_path(locale, book_id) if book_id else "/")
return {
"User-Agent": USER_AGENT,
"Referer": referer,
"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,
}
+248
View File
@@ -0,0 +1,248 @@
import asyncio
import json
import os
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]
def enabled_cache() -> bool:
flag = os.environ.get("RAPTD_CATALOG_CACHE", "1").strip().lower()
return flag not in ("0", "false", "no")
def cache_path() -> Path:
return ROOT / "cache" / "dramabox" / f"catalog-{client.language}.json"
async def stream(refresh: bool = False):
path = cache_path()
if enabled_cache():
if refresh:
path.unlink(missing_ok=True)
else:
cached = _read_cache(path)
if cached:
for event in cached:
yield event
return
collected: list[dict] = []
failed = False
async for event in _fetch():
if event.get("failed"):
failed = True
collected.append(event)
yield event
if enabled_cache() and not failed and collected and collected[-1].get("type") == "done":
_write_cache(path, collected)
async def _fetch():
home = await asyncio.to_thread(api.home_index)
first = await asyncio.to_thread(api.browse, 1, 0)
types = [item for item in (first.get("types") or []) if isinstance(item, dict)]
jobs: list[tuple[str, str, str, object]] = []
sections = []
for column in home:
if not isinstance(column, dict):
continue
name = str(column.get("name") or "").strip()
if not name:
continue
key = f"home-{column.get('id') or name}"
sections.append({"key": key, "name": name, "note": "", "loading": True})
jobs.append((key, name, "home", column))
sections.append({"key": "browse-0", "name": "全部", "note": "", "loading": True})
jobs.append(("browse-0", "全部", "browse", {"id": 0, "seed": first}))
for item in types:
type_id = _int(item.get("id"))
name = str(item.get("name") or "").strip()
if type_id <= 0 or not name:
continue
key = f"browse-{type_id}"
sections.append({"key": key, "name": name, "note": "", "loading": True})
jobs.append((key, name, "browse", {"id": type_id}))
if not sections:
raise RuntimeError("没有获取到分类")
yield {"type": "outline", "sections": sections}
loop = asyncio.get_running_loop()
queue: asyncio.Queue = asyncio.Queue()
limit = asyncio.Semaphore(6)
async def run(job):
key, name, kind, payload = job
def work():
try:
if kind == "home":
items = _home_items(payload)
else:
items = _browse_items(payload)
loop.call_soon_threadsafe(queue.put_nowait, _page(key, name, items, done=True))
except Exception as exc:
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)
async with limit:
await asyncio.to_thread(work)
tasks = [asyncio.create_task(run(job)) for job in jobs]
finished = 0
try:
while finished < len(tasks):
event = await queue.get()
if event is None:
finished += 1
continue
yield event
yield {"type": "done"}
finally:
for task in tasks:
if not task.done():
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
def search(keyword: str) -> list[dict]:
text = (keyword or "").strip()
if not text:
return []
items = []
seen: set[str] = set()
for page in range(1, 4):
payload = api.search_books(text, page=page, page_size=20)
rows = payload.get("records") if isinstance(payload, dict) else None
if not isinstance(rows, list) or not rows:
break
for item in rows:
drama = _drama(item)
if not drama or drama["id"] in seen:
continue
seen.add(drama["id"])
items.append(drama)
if len(rows) < 20:
break
return items
def _home_items(column: dict) -> list[dict]:
items = []
seen: set[str] = set()
for item in column.get("items") or []:
drama = _drama(item)
if not drama or drama["id"] in seen:
continue
seen.add(drama["id"])
items.append(drama)
name = str(column.get("name") or "").strip()
if name:
for page in range(1, 3):
payload = api.home_more(name, page=page, page_size=18)
block = payload.get("data") if isinstance(payload, dict) else None
rows = block.get("items") if isinstance(block, dict) else None
if not isinstance(rows, list) or not rows:
break
for item in rows:
drama = _drama(item)
if not drama or drama["id"] in seen:
continue
seen.add(drama["id"])
items.append(drama)
pages = _int(payload.get("pages")) if isinstance(payload, dict) else 0
if page >= pages:
break
return items
def _browse_items(payload: dict) -> list[dict]:
type_id = _int(payload.get("id"))
items = []
seen: set[str] = set()
seed = payload.get("seed") if isinstance(payload.get("seed"), dict) else None
pages = 3 if type_id == 0 else 1
for page in range(1, pages + 1):
if page == 1 and seed is not None:
data = seed
else:
data = api.browse(page, type_id)
rows = data.get("bookList") if isinstance(data, dict) else None
if not isinstance(rows, list) or not rows:
break
for item in rows:
drama = _drama(item)
if not drama or drama["id"] in seen:
continue
seen.add(drama["id"])
items.append(drama)
total_pages = _int(data.get("pages")) if isinstance(data, dict) else 0
if page >= total_pages:
break
return items
def _drama(item: dict) -> dict | None:
if not isinstance(item, dict):
return None
drama_id = str(item.get("bookId") or item.get("action") or "").strip()
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()
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()
free = item.get("free")
return {
"id": drama_id,
"title": title,
"image": covers.local_url(image) if image else "",
"payType": "" if free in (1, "1", True, None) else str(free or ""),
"episodeCount": str(count or ""),
"corner": corner,
"limitedFree": False,
"locked": False,
"kind": corner,
}
def _page(key: str, name: str, items: list[dict], note: str = "", done: bool = False, failed: bool = False) -> dict:
event = {"type": "page", "key": key, "name": name, "note": note, "items": items, "done": done}
if failed:
event["failed"] = True
return event
def _read_cache(path: Path) -> list[dict] | None:
if not path.is_file():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
events = data.get("events") if isinstance(data, dict) else None
if not isinstance(events, list) or not events:
return None
return events
def _write_cache(path: Path, events: list[dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(".json.tmp")
temporary.write_text(json.dumps({"events": events}, ensure_ascii=False), encoding="utf-8")
temporary.replace(path)
def _int(value) -> int:
try:
return int(float(str(value)))
except (TypeError, ValueError):
return 0
+92
View File
@@ -0,0 +1,92 @@
import json
import secrets
from pathlib import Path
from server.services.dramabox.locales import DEFAULT_LANGUAGE, resolve
ROOT = Path(__file__).resolve().parents[3]
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"
)
class DramaBoxClient:
def __init__(self) -> None:
self.token = ""
self.language = DEFAULT_LANGUAGE
self.build_id = ""
self.profile: dict = {}
self._load()
def _load(self) -> None:
if not SESSION_PATH.is_file():
return
try:
data = json.loads(SESSION_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return
if not isinstance(data, dict):
return
self.token = str(data.get("token") or "")
language = str(data.get("language") or "").strip()
if language:
try:
self.language = resolve(language)["id"]
except RuntimeError:
self.language = DEFAULT_LANGUAGE
self.build_id = str(data.get("build_id") or "")
profile = data.get("profile")
if isinstance(profile, dict):
self.profile = profile
def save(self) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
payload = {
"token": self.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)
def enter(self, language: str) -> dict:
locale = resolve(language)
self.language = locale["id"]
if not self.token:
self.token = secrets.token_hex(16)
self.profile = {
"id": locale["id"],
"username": locale["id"],
"nickname": locale["country"],
"email": locale["language"],
"phone": "",
"badge": "",
"vipday": 0,
"score": 0,
"watched": 0,
"rewards": 0,
"login_day": 0,
"country": locale["country"],
"language": locale["language"],
"native": locale["native"],
"locale": locale["id"],
"avatarNumUrl": "",
}
self.save()
return {"token": self.token, "profile": self.profile}
def clear(self) -> None:
self.token = ""
self.profile = {}
self.save()
client = DramaBoxClient()
+94
View File
@@ -0,0 +1,94 @@
import hashlib
import re
import threading
from pathlib import Path
from server.services.dramabox.client import USER_AGENT
from server.services.http import http
CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "dramabox" / "covers"
_lock = threading.Lock()
_IMAGE_TYPES = {
b"\xff\xd8\xff": "image/jpeg",
b"\x89PNG": "image/png",
b"GIF8": "image/gif",
b"RIFF": "image/webp",
}
class CoverCache:
def local_url(self, remote: str) -> str:
remote = (remote or "").strip()
if not remote:
return ""
if remote.startswith("/api/dramabox/covers/"):
return remote
if not remote.startswith(("http://", "https://")):
return remote
digest = hashlib.sha256(remote.encode("utf-8")).hexdigest()
CACHE_DIR.mkdir(parents=True, exist_ok=True)
meta = CACHE_DIR / f"{digest}.url"
if not meta.is_file():
meta.write_text(remote, encoding="utf-8")
return f"/api/dramabox/covers/{digest}"
def read(self, digest: str) -> tuple[bytes, str]:
if not re.fullmatch(r"[0-9a-f]{64}", digest):
raise RuntimeError("封面不存在")
meta = CACHE_DIR / f"{digest}.url"
body = CACHE_DIR / digest
if not meta.is_file():
raise RuntimeError("封面不存在")
if body.is_file() and body.stat().st_size > 0:
return body.read_bytes(), _media_type(body)
remote = meta.read_text(encoding="utf-8").strip()
data, media = _download(remote)
with _lock:
CACHE_DIR.mkdir(parents=True, exist_ok=True)
body.write_bytes(data)
(CACHE_DIR / f"{digest}.type").write_text(media, encoding="utf-8")
return data, media
def _download(remote: str) -> tuple[bytes, str]:
headers = {"User-Agent": USER_AGENT, "Referer": "https://www.dramaboxapp.com/"}
last_error = "封面读取失败"
for url in _candidates(remote):
try:
response = http.send("GET", url, headers=headers, timeout=30.0)
response.raise_for_status()
except Exception as exc:
last_error = str(exc) or last_error
continue
media = _sniff_media(response.content) or (response.headers.get("content-type") or "").split(";", 1)[0].strip()
if response.content and media.startswith("image/"):
return response.content, media
last_error = "不是图片"
raise RuntimeError(last_error)
def _candidates(remote: str) -> list[str]:
urls = [remote]
stripped = re.sub(r"@w=\d+&h=\d+$", "", remote)
if stripped != remote:
urls.append(stripped)
return urls
def _sniff_media(data: bytes) -> str:
for magic, media in _IMAGE_TYPES.items():
if data.startswith(magic):
return media
return ""
def _media_type(path: Path) -> str:
sidecar = Path(f"{path}.type")
if sidecar.is_file():
media = sidecar.read_text(encoding="utf-8").strip()
if media.startswith("image/"):
return media
return "image/jpeg"
covers = CoverCache()
+68
View File
@@ -0,0 +1,68 @@
from pathlib import Path
from server.services.downloads import DownloadManager, _plain_text
from server.services.dramabox import api
from server.services.dramabox.client import USER_AGENT, client
from server.services.dramabox.covers import covers
from server.services.dramabox import playlist as db_playlist
ROOT = Path(__file__).resolve().parents[3]
def _load_episodes(_token, _device, drama_id: str) -> list[dict]:
return db_playlist.load_episodes(str(drama_id))
def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) -> None:
name = title.strip()
desc = ""
language = client.language
country = ""
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 "")
profile = client.profile or {}
country = str(profile.get("country") or "")
except Exception:
pass
lines = [
f"ID: {drama_id}",
f"名称: {name}",
f"简介: {desc}",
f"地区: {country or '—'}",
f"语言: {language or '—'}",
f"分类: {tags or '—'}",
f"集数: {count or '—'}",
"",
]
(folder / "简介.txt").write_text("\n".join(lines), encoding="utf-8")
def _read_cover(image: str):
digest = (image or "").rstrip("/").rsplit("/", 1)[-1].strip()
return covers.read(digest)
def _auth():
return client.token, None
downloads = DownloadManager(
state_dir=ROOT / "cache" / "dramabox" / "downloads",
default_directory=str((Path.cwd() / "download" / "dramabox").resolve()),
load_episodes=_load_episodes,
write_intro=_write_intro,
read_cover=_read_cover,
current_auth=_auth,
headers={"User-Agent": USER_AGENT, "Referer": "https://www.dramaboxapp.com/", "Origin": "https://www.dramaboxapp.com"},
)
+56
View File
@@ -0,0 +1,56 @@
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"},
)
DEFAULT_LANGUAGE = "th"
_BY_ID = {item["id"]: item for item in LOCALES}
def resolve(language: str) -> dict:
text = (language or "").strip()
if text in _BY_ID:
return dict(_BY_ID[text])
lowered = text.lower()
for item in LOCALES:
if item["id"].lower() == lowered:
return dict(item)
raise RuntimeError("不支持这个语言地区")
def public_list() -> list[dict]:
return [
{
"id": item["id"],
"country": item["country"],
"language": item["language"],
"native": item["native"],
"label": f'{item["country"]} · {item["language"]}',
}
for item in LOCALES
]
def film_path(language: str, book_id: str) -> str:
locale = resolve(language)["id"]
book_id = str(book_id or "").strip()
if not book_id:
raise RuntimeError("没有这部剧")
if locale == "en":
return f"/film/{book_id}"
return f"/{locale}/film/{book_id}"
+27
View File
@@ -0,0 +1,27 @@
from server.services.dramabox.client import client
from server.services.dramabox.locales import DEFAULT_LANGUAGE, public_list
def languages() -> list[dict]:
return public_list()
def enter(language: str = "") -> dict:
return client.enter(language or client.language or DEFAULT_LANGUAGE)
def current(token: str) -> dict:
token = (token or "").strip()
if not token:
raise RuntimeError("请先选择地区")
if token != client.token or not client.profile:
raise RuntimeError("登录已失效")
return {"token": client.token, "profile": client.profile}
def logout(token: str) -> None:
if token and token == client.token:
client.clear()
return
if not token:
client.clear()
+179
View File
@@ -0,0 +1,179 @@
import json
import re
from pathlib import Path
from urllib.parse import quote, urljoin
from server.services.dramabox import api
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) -> list[dict]:
drama_id = str(drama_id or "").strip()
if not drama_id:
raise RuntimeError("没有这部剧")
cached = _read_cache(drama_id)
fresh = _fetch_episodes(drama_id)
merged, save = _merge(cached, fresh)
if save or (not cached and merged):
_write_cache(drama_id, merged)
return merged
def episode_src(drama_id: str, cid: int) -> dict:
for ep in load_episodes(drama_id):
if int(ep.get("cid") or 0) == int(cid):
return ep
return {}
def playback_playlist(src: str, drama_id: str = "") -> str:
if is_direct_media(src):
raise RuntimeError("这一集是整段视频")
headers = api.cdn_headers(book_id=drama_id)
text = http.read_text(src, headers=headers)
variant_rel = next(
(line.strip() for line in text.splitlines() if line.strip() and not line.startswith("#")),
"",
)
if not variant_rel:
raise RuntimeError("播放列表没有视频地址")
if looks_like_segment(variant_rel):
return _rewrite_playlist(text, src)
variant_url = urljoin(src, variant_rel)
return _rewrite_playlist(http.read_text(variant_url, headers=headers), variant_url)
def _fetch_episodes(drama_id: str) -> list[dict]:
data = api.film(drama_id)
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) -> Path:
return CACHE_DIR / client.language / f"{drama_id}.json"
def _read_cache(drama_id: str) -> list[dict]:
path = _cache_file(drama_id)
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, episodes: list[dict]) -> None:
path = _cache_file(drama_id)
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():
stripped = line.strip()
if not stripped:
lines.append(line)
continue
if stripped.startswith("#"):
lines.append(_rewrite_tag(line, base))
continue
lines.append(_proxy_url(urljoin(base, stripped)))
return "\n".join(lines) + "\n"
def _rewrite_tag(line: str, base: str) -> str:
def replace(match):
return 'URI="' + _proxy_url(urljoin(base, match.group(1))) + '"'
return re.sub(r'URI="([^"]*)"', replace, line)
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