feat: 接入 DramaBox 并按语言地区切换清单
This commit is contained in:
@@ -12,12 +12,14 @@ from server.routes.covers import router as covers_router
|
||||
from server.routes.device import router as device_router
|
||||
from server.routes.downloads import router as downloads_router
|
||||
from server.routes.huangdou import router as huangdou_router
|
||||
from server.routes.dramabox import router as dramabox_router
|
||||
from server.routes.live import router as live_router
|
||||
from server.routes.play import router as play_router
|
||||
from server.routes.proxy import router as proxy_router
|
||||
from server.routes.session import router as session_router
|
||||
from server.services.downloads import downloads
|
||||
from server.services.huangdou.downloads import downloads as huangdou_downloads
|
||||
from server.services.dramabox.downloads import downloads as dramabox_downloads
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
@@ -39,11 +41,13 @@ def create_app() -> FastAPI:
|
||||
app.include_router(live_router)
|
||||
app.include_router(proxy_router)
|
||||
app.include_router(huangdou_router)
|
||||
app.include_router(dramabox_router)
|
||||
|
||||
@app.on_event("startup")
|
||||
def start_downloads() -> None:
|
||||
downloads.start()
|
||||
huangdou_downloads.start()
|
||||
dramabox_downloads.start()
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
import json
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from server.errors import call
|
||||
from server.services.http import http
|
||||
from server.services.dramabox import catalog as db_catalog
|
||||
from server.services.dramabox import login as db_login
|
||||
from server.services.dramabox import playlist as db_playlist
|
||||
from server.services.dramabox.api import cdn_headers
|
||||
from server.services.dramabox.client import client
|
||||
from server.services.dramabox.covers import covers
|
||||
from server.services.dramabox.downloads import downloads as db_downloads
|
||||
from server.services.playlist import is_direct_media
|
||||
|
||||
router = APIRouter(prefix="/api/dramabox")
|
||||
|
||||
|
||||
class EnterBody(BaseModel):
|
||||
language: str = ""
|
||||
|
||||
|
||||
class TokenBody(BaseModel):
|
||||
token: str = ""
|
||||
refresh: bool = False
|
||||
keyword: str = ""
|
||||
language: str = ""
|
||||
|
||||
|
||||
class DownloadItem(BaseModel):
|
||||
id: str | int
|
||||
title: str = ""
|
||||
image: str = ""
|
||||
|
||||
|
||||
class DownloadStartBody(BaseModel):
|
||||
token: str = ""
|
||||
items: list[DownloadItem] = []
|
||||
|
||||
|
||||
class DirectoryBody(BaseModel):
|
||||
path: str = ""
|
||||
|
||||
|
||||
class DownloadSettingsBody(BaseModel):
|
||||
directory: str = ""
|
||||
workers: int | None = None
|
||||
|
||||
|
||||
class PlayBody(BaseModel):
|
||||
token: str = ""
|
||||
vid: str
|
||||
|
||||
|
||||
def _require_token(token: str) -> None:
|
||||
token = (token or "").strip()
|
||||
if not token:
|
||||
raise RuntimeError("请先选择地区")
|
||||
if token != client.token:
|
||||
raise RuntimeError("登录已失效")
|
||||
|
||||
|
||||
@router.get("/languages")
|
||||
def list_languages():
|
||||
return {"items": db_login.languages()}
|
||||
|
||||
|
||||
@router.post("/login/device")
|
||||
def login_device(body: EnterBody | None = None):
|
||||
language = body.language if body else ""
|
||||
return call(lambda: db_login.enter(language))
|
||||
|
||||
|
||||
@router.post("/me")
|
||||
def me(body: TokenBody):
|
||||
return call(lambda: db_login.current(body.token))
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(body: TokenBody):
|
||||
db_login.logout(body.token)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/catalog")
|
||||
async def load_catalog(body: TokenBody):
|
||||
try:
|
||||
_require_token(body.token)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
async def generate():
|
||||
try:
|
||||
async for event in db_catalog.stream(body.refresh):
|
||||
yield json.dumps(event, ensure_ascii=False) + "\n"
|
||||
except Exception as exc:
|
||||
message = str(exc) or "获取清单失败"
|
||||
yield json.dumps({"type": "error", "message": message}, ensure_ascii=False) + "\n"
|
||||
|
||||
return StreamingResponse(generate(), media_type="application/x-ndjson")
|
||||
|
||||
|
||||
@router.post("/search")
|
||||
def search(body: TokenBody):
|
||||
def action():
|
||||
_require_token(body.token)
|
||||
return {"items": db_catalog.search(body.keyword)}
|
||||
|
||||
return call(action)
|
||||
|
||||
|
||||
@router.get("/covers/{digest}")
|
||||
def cover(digest: str):
|
||||
try:
|
||||
data, media = covers.read(digest)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=media,
|
||||
headers={"Cache-Control": "public, max-age=31536000, immutable"},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/play/episodes")
|
||||
def list_episodes(body: PlayBody):
|
||||
def action():
|
||||
_require_token(body.token)
|
||||
rows = db_playlist.load_episodes(body.vid)
|
||||
return {
|
||||
"episodes": [
|
||||
{
|
||||
"cid": ep["cid"],
|
||||
"idx": ep["idx"],
|
||||
"title": ep["title"],
|
||||
"playable": bool(ep.get("src")),
|
||||
"type": ep.get("type") or "",
|
||||
"media": "file" if (ep.get("src_kind") == "file" or is_direct_media(ep.get("src") or "")) else "hls",
|
||||
"is_preview": bool(ep.get("is_preview")),
|
||||
"preview_seconds": ep.get("preview_seconds") or 0,
|
||||
"locked_reason": ep.get("locked_reason") or "",
|
||||
}
|
||||
for ep in rows
|
||||
]
|
||||
}
|
||||
|
||||
return call(action)
|
||||
|
||||
|
||||
def _public_url(url: str) -> str:
|
||||
parts = urlsplit(url)
|
||||
if parts.scheme not in ("http", "https") or not parts.hostname:
|
||||
raise HTTPException(status_code=400, detail="播放地址无效")
|
||||
return url
|
||||
|
||||
|
||||
@router.get("/play/segment")
|
||||
def play_segment(url: str, vid: str = Query(default="")):
|
||||
target = _public_url(url)
|
||||
headers = cdn_headers(book_id=vid)
|
||||
try:
|
||||
upstream = http.open_stream(target, headers=headers)
|
||||
except (httpx.HTTPError, TimeoutError, OSError, RuntimeError) as exc:
|
||||
raise HTTPException(status_code=502, detail="分片读取失败") from exc
|
||||
media = upstream.headers.get("content-type", "video/mp2t").split(";", 1)[0].strip() or "video/mp2t"
|
||||
path = urlsplit(target).path.lower()
|
||||
if path.endswith(".ts") and not media.startswith("video/"):
|
||||
media = "video/mp2t"
|
||||
elif path.endswith(".m3u8") and "mpegurl" not in media:
|
||||
media = "application/vnd.apple.mpegurl"
|
||||
|
||||
def chunks():
|
||||
try:
|
||||
for chunk in upstream.iter_bytes(64 * 1024):
|
||||
if chunk:
|
||||
yield chunk
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
return StreamingResponse(chunks(), media_type=media)
|
||||
|
||||
|
||||
@router.get("/play/{vid}/{cid}/file")
|
||||
def play_file(vid: str, cid: int):
|
||||
row = db_playlist.episode_src(vid, cid)
|
||||
src = str(row.get("src") or "").strip()
|
||||
if not src:
|
||||
raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址")
|
||||
try:
|
||||
upstream = http.open_stream(src, headers=cdn_headers(book_id=vid))
|
||||
except (httpx.HTTPError, TimeoutError, OSError, RuntimeError) as exc:
|
||||
raise HTTPException(status_code=502, detail="分片读取失败") from exc
|
||||
media = upstream.headers.get("content-type", "video/mp4").split(";", 1)[0].strip() or "video/mp4"
|
||||
|
||||
def chunks():
|
||||
try:
|
||||
for chunk in upstream.iter_bytes(64 * 1024):
|
||||
if chunk:
|
||||
yield chunk
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
return StreamingResponse(chunks(), media_type=media)
|
||||
|
||||
|
||||
@router.get("/play/{vid}/{cid}/index.m3u8")
|
||||
def episode_playlist(vid: str, cid: int):
|
||||
row = db_playlist.episode_src(vid, cid)
|
||||
src = str(row.get("src") or "").strip()
|
||||
if not src:
|
||||
raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址")
|
||||
try:
|
||||
text = db_playlist.playback_playlist(src, drama_id=vid)
|
||||
text = text.replace("/api/dramabox/play/segment?url=", f"/api/dramabox/play/segment?vid={vid}&url=")
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
return Response(text, media_type="application/vnd.apple.mpegurl", headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/downloads")
|
||||
def list_downloads():
|
||||
return db_downloads.snapshot()
|
||||
|
||||
|
||||
@router.post("/downloads")
|
||||
def start_downloads(body: DownloadStartBody):
|
||||
def action():
|
||||
_require_token(body.token)
|
||||
return db_downloads.enqueue(body.token, None, [item.model_dump() for item in body.items])
|
||||
|
||||
return call(action)
|
||||
|
||||
|
||||
@router.post("/downloads/directory")
|
||||
def set_directory(body: DirectoryBody):
|
||||
if not body.path.strip():
|
||||
raise HTTPException(status_code=400, detail="请选择目录")
|
||||
return {"directory": db_downloads.set_directory(body.path.strip())}
|
||||
|
||||
|
||||
@router.post("/downloads/pick")
|
||||
def pick_directory():
|
||||
return {"directory": db_downloads.pick_directory()}
|
||||
|
||||
|
||||
@router.post("/downloads/choose")
|
||||
def choose_directory():
|
||||
return {"directory": db_downloads.choose_directory()}
|
||||
|
||||
|
||||
@router.get("/downloads/settings")
|
||||
def get_download_settings():
|
||||
return db_downloads.settings_view()
|
||||
|
||||
|
||||
@router.post("/downloads/settings")
|
||||
def update_download_settings(body: DownloadSettingsBody):
|
||||
if body.directory.strip():
|
||||
db_downloads.set_directory(body.directory.strip())
|
||||
if body.workers is not None:
|
||||
try:
|
||||
db_downloads.set_workers(body.workers)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
return db_downloads.settings_view()
|
||||
|
||||
|
||||
@router.post("/downloads/pause-all")
|
||||
def pause_all_downloads():
|
||||
return db_downloads.pause_all()
|
||||
|
||||
|
||||
@router.post("/downloads/resume-all")
|
||||
def resume_all_downloads():
|
||||
return db_downloads.resume_all()
|
||||
|
||||
|
||||
@router.post("/downloads/remux")
|
||||
def remux_downloads():
|
||||
return call(db_downloads.remux_saved)
|
||||
|
||||
|
||||
@router.post("/downloads/{drama_id}/remux")
|
||||
def remux_one_download(drama_id: str):
|
||||
return call(lambda: db_downloads.remux_job(drama_id))
|
||||
|
||||
|
||||
@router.post("/downloads/{drama_id}/redownload")
|
||||
def redownload_one(drama_id: str):
|
||||
return call(lambda: db_downloads.redownload(drama_id))
|
||||
|
||||
|
||||
@router.post("/downloads/{drama_id}/pause")
|
||||
def pause_download(drama_id: str):
|
||||
return db_downloads.pause(drama_id)
|
||||
|
||||
|
||||
@router.post("/downloads/{drama_id}/resume")
|
||||
def resume_download(drama_id: str):
|
||||
return db_downloads.resume(drama_id)
|
||||
|
||||
|
||||
@router.post("/downloads/{drama_id}/cancel")
|
||||
def cancel_download(drama_id: str):
|
||||
return db_downloads.cancel(drama_id)
|
||||
|
||||
|
||||
@router.post("/downloads/{drama_id}/open")
|
||||
def open_download(drama_id: str):
|
||||
def action():
|
||||
db_downloads.open_folder(drama_id)
|
||||
return db_downloads.snapshot()
|
||||
|
||||
return call(action)
|
||||
|
||||
|
||||
@router.delete("/downloads/{drama_id}")
|
||||
def remove_download(drama_id: str):
|
||||
return db_downloads.remove(drama_id)
|
||||
@@ -5,6 +5,8 @@ from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from server.services.downloads import downloads
|
||||
from server.services.huangdou.client import client as huangdou_client
|
||||
from server.services.huangdou.downloads import downloads as huangdou_downloads
|
||||
from server.services.dramabox.client import client as dramabox_client
|
||||
from server.services.dramabox.downloads import downloads as dramabox_downloads
|
||||
from server.services.live import live
|
||||
from server.services.sessions import sessions
|
||||
|
||||
@@ -17,6 +19,11 @@ def _payload(platform: str) -> dict:
|
||||
"downloads": huangdou_downloads.snapshot(),
|
||||
"profile": huangdou_client.profile or None,
|
||||
}
|
||||
if platform == "dramabox":
|
||||
return {
|
||||
"downloads": dramabox_downloads.snapshot(),
|
||||
"profile": dramabox_client.profile or None,
|
||||
}
|
||||
profile = sessions.snapshot()
|
||||
return {
|
||||
"downloads": downloads.snapshot(),
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""DramaBox 平台。会话、清单和下载与 RaptDrama / 黄豆短剧隔离。"""
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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"},
|
||||
)
|
||||
@@ -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}"
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -0,0 +1,50 @@
|
||||
from server.services.dramabox.locales import film_path, public_list, resolve
|
||||
from server.services.dramabox.playlist import _choose_src
|
||||
from server.services.playlist import is_direct_media
|
||||
|
||||
|
||||
def test_locales_and_film_path() -> None:
|
||||
items = public_list()
|
||||
ids = [item["id"] for item in items]
|
||||
assert "th" in ids
|
||||
assert "en" in ids
|
||||
assert "zhHans" in ids
|
||||
thai = resolve("th")
|
||||
assert thai["country"] == "泰国"
|
||||
assert thai["language"] == "泰语"
|
||||
assert film_path("en", "41000119953") == "/film/41000119953"
|
||||
assert film_path("th", "41000119953") == "/th/film/41000119953"
|
||||
try:
|
||||
resolve("xx")
|
||||
except RuntimeError as exc:
|
||||
assert "语言" in str(exc)
|
||||
else:
|
||||
raise AssertionError("未知语言应拒绝")
|
||||
|
||||
|
||||
def test_chapter_source_choice() -> None:
|
||||
src, kind = _choose_src({
|
||||
"m3u8Url": "https://cdn.example/ep1.m3u8?sig=1",
|
||||
"mp4": "https://cdn.example/ep1.mp4?sig=1",
|
||||
"unlock": True,
|
||||
})
|
||||
assert kind == "hls"
|
||||
assert src.endswith(".m3u8?sig=1")
|
||||
|
||||
src, kind = _choose_src({
|
||||
"m3u8Url": "",
|
||||
"mp4": "https://cdn.example/ep2.mp4?sig=1",
|
||||
"unlock": True,
|
||||
})
|
||||
assert kind == "file"
|
||||
assert is_direct_media(src)
|
||||
|
||||
src, kind = _choose_src({"unlock": False})
|
||||
assert src == ""
|
||||
assert kind == ""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_locales_and_film_path()
|
||||
test_chapter_source_choice()
|
||||
print("ok")
|
||||
+123
-32
@@ -7,7 +7,7 @@ import SettingsPanel from "./views/SettingsPanel.vue";
|
||||
import PlayerPage from "./views/PlayerPage.vue";
|
||||
|
||||
type Method = "guest" | "password" | "adb";
|
||||
type Platform = "rapt" | "huangdou";
|
||||
type Platform = "rapt" | "huangdou" | "dramabox";
|
||||
|
||||
interface Profile {
|
||||
nickname?: string;
|
||||
@@ -30,6 +30,10 @@ interface Profile {
|
||||
balance?: string | number;
|
||||
is_vip?: string | number;
|
||||
has_login?: string;
|
||||
country?: string;
|
||||
language?: string;
|
||||
native?: string;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
interface Device {
|
||||
@@ -75,6 +79,7 @@ const DEVICE_KEY = "rapt-device-settings";
|
||||
const SESSION_DEVICE_KEY = "rapt-device";
|
||||
const ACCOUNTS_KEY = "rapt-accounts";
|
||||
const PLATFORM_KEY = "rapt-platform";
|
||||
const DRAMABOX_LANG_KEY = "dramabox-language";
|
||||
|
||||
const themeOverrides: GlobalThemeOverrides = {
|
||||
Form: {
|
||||
@@ -85,10 +90,22 @@ const themeOverrides: GlobalThemeOverrides = {
|
||||
const platforms: { key: Platform; label: string }[] = [
|
||||
{ key: "rapt", label: "RaptDrama" },
|
||||
{ key: "huangdou", label: "黄豆短剧" },
|
||||
{ key: "dramabox", label: "DramaBox" },
|
||||
];
|
||||
const platform = ref<Platform>(readPlatform());
|
||||
const apiBase = computed(() => (platform.value === "huangdou" ? "/api/huangdou" : "/api"));
|
||||
const platformLabel = computed(() => platforms.find((item) => item.key === platform.value)?.label || "RaptDrama");
|
||||
const isolated = computed(() => platform.value === "huangdou" || platform.value === "dramabox");
|
||||
const apiBase = computed(() => {
|
||||
if (platform.value === "huangdou") return "/api/huangdou";
|
||||
if (platform.value === "dramabox") return "/api/dramabox";
|
||||
return "/api";
|
||||
});
|
||||
const platformLabel = computed(() => {
|
||||
const name = platforms.find((item) => item.key === platform.value)?.label || "RaptDrama";
|
||||
if (platform.value === "dramabox" && profile.value?.nickname) return `${name} · ${profile.value.nickname}`;
|
||||
return name;
|
||||
});
|
||||
const dramaboxLang = ref("th");
|
||||
const dramaboxLangs = ref<{ label: string; value: string }[]>([]);
|
||||
const method = ref<Method>("guest");
|
||||
const email = ref("");
|
||||
const password = ref("");
|
||||
@@ -159,7 +176,7 @@ const menuValue = computed(() => {
|
||||
function readPlatform(): Platform {
|
||||
try {
|
||||
const value = localStorage.getItem(PLATFORM_KEY);
|
||||
if (value === "huangdou" || value === "rapt") return value;
|
||||
if (value === "huangdou" || value === "rapt" || value === "dramabox") return value;
|
||||
} catch {
|
||||
// 沿用默认平台
|
||||
}
|
||||
@@ -167,14 +184,43 @@ function readPlatform(): Platform {
|
||||
}
|
||||
|
||||
function selectPlatform(key: string) {
|
||||
if (key !== "rapt" && key !== "huangdou") return;
|
||||
if (key !== "rapt" && key !== "huangdou" && key !== "dramabox") return;
|
||||
platform.value = key;
|
||||
localStorage.setItem(PLATFORM_KEY, key);
|
||||
error.value = "";
|
||||
if (key === "dramabox") void loadDramaboxLanguages();
|
||||
}
|
||||
|
||||
function tokenKey() {
|
||||
return platform.value === "huangdou" ? "huangdou-token" : "rapt-token";
|
||||
if (platform.value === "huangdou") return "huangdou-token";
|
||||
if (platform.value === "dramabox") return "dramabox-token";
|
||||
return "rapt-token";
|
||||
}
|
||||
|
||||
async function loadDramaboxLanguages() {
|
||||
try {
|
||||
const response = await fetch("/api/dramabox/languages");
|
||||
const payload = await response.json();
|
||||
const items = Array.isArray(payload.items) ? payload.items : [];
|
||||
dramaboxLangs.value = items.map((item: { id: string; label: string }) => ({
|
||||
label: item.label,
|
||||
value: item.id,
|
||||
}));
|
||||
} catch {
|
||||
dramaboxLangs.value = [];
|
||||
}
|
||||
if (!dramaboxLangs.value.length) {
|
||||
dramaboxLangs.value = [
|
||||
{ label: "泰国 · 泰语", value: "th" },
|
||||
{ label: "美国 · 英语", value: "en" },
|
||||
];
|
||||
}
|
||||
try {
|
||||
const saved = localStorage.getItem(DRAMABOX_LANG_KEY);
|
||||
if (saved && dramaboxLangs.value.some((item) => item.value === saved)) dramaboxLang.value = saved;
|
||||
} catch {
|
||||
// 使用默认地区
|
||||
}
|
||||
}
|
||||
|
||||
function openPlay(drama: { id: string | number; title: string; image: string }) {
|
||||
@@ -225,20 +271,28 @@ const methods: { id: Method; label: string }[] = [
|
||||
{ id: "adb", label: "ADB" },
|
||||
];
|
||||
|
||||
const accountFields = computed(() =>
|
||||
platform.value === "huangdou"
|
||||
? [
|
||||
{ key: "username" as const, label: "账号" },
|
||||
{ key: "id" as const, label: "用户 ID" },
|
||||
{ key: "group_name" as const, label: "身份" },
|
||||
{ key: "email" as const, label: "邮箱" },
|
||||
{ key: "phone" as const, label: "手机" },
|
||||
]
|
||||
: [
|
||||
{ key: "email" as const, label: "邮箱" },
|
||||
{ key: "id" as const, label: "用户 ID" },
|
||||
],
|
||||
);
|
||||
const accountFields = computed(() => {
|
||||
if (platform.value === "huangdou") {
|
||||
return [
|
||||
{ key: "username" as const, label: "账号" },
|
||||
{ key: "id" as const, label: "用户 ID" },
|
||||
{ key: "group_name" as const, label: "身份" },
|
||||
{ key: "email" as const, label: "邮箱" },
|
||||
{ key: "phone" as const, label: "手机" },
|
||||
];
|
||||
}
|
||||
if (platform.value === "dramabox") {
|
||||
return [
|
||||
{ key: "country" as const, label: "国家" },
|
||||
{ key: "language" as const, label: "语言" },
|
||||
{ key: "id" as const, label: "代码" },
|
||||
];
|
||||
}
|
||||
return [
|
||||
{ key: "email" as const, label: "邮箱" },
|
||||
{ key: "id" as const, label: "用户 ID" },
|
||||
];
|
||||
});
|
||||
|
||||
const statFields = computed(() =>
|
||||
platform.value === "huangdou"
|
||||
@@ -247,6 +301,8 @@ const statFields = computed(() =>
|
||||
{ key: "score" as const, label: "余额" },
|
||||
{ key: "watched" as const, label: "观看" },
|
||||
]
|
||||
: platform.value === "dramabox"
|
||||
? []
|
||||
: [
|
||||
{ key: "vipday" as const, label: "VIP" },
|
||||
{ key: "score" as const, label: "积分" },
|
||||
@@ -310,13 +366,13 @@ async function loadDownloadSettings() {
|
||||
|
||||
async function enterSettings() {
|
||||
settingsError.value = "";
|
||||
if (platform.value === "huangdou" && settingsTab.value === "device") settingsTab.value = "download";
|
||||
if (isolated.value && settingsTab.value === "device") settingsTab.value = "download";
|
||||
await loadDownloadSettings();
|
||||
draft.value = copySettings(settings.value);
|
||||
}
|
||||
|
||||
async function openSettings() {
|
||||
settingsTab.value = platform.value === "huangdou" ? "download" : "device";
|
||||
settingsTab.value = isolated.value ? "download" : "device";
|
||||
await enterSettings();
|
||||
settingsOpen.value = true;
|
||||
}
|
||||
@@ -602,11 +658,41 @@ async function loginHuangdou() {
|
||||
}
|
||||
}
|
||||
|
||||
async function loginDramabox() {
|
||||
error.value = "";
|
||||
busy.value = true;
|
||||
try {
|
||||
localStorage.setItem(DRAMABOX_LANG_KEY, dramaboxLang.value);
|
||||
const response = await fetch("/api/dramabox/login/device", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ language: dramaboxLang.value }),
|
||||
});
|
||||
const payload = await response.json();
|
||||
if (!response.ok) {
|
||||
throw new Error(typeof payload.detail === "string" ? payload.detail : "进入失败");
|
||||
}
|
||||
token.value = payload.token;
|
||||
profile.value = payload.profile;
|
||||
sessionStorage.setItem(tokenKey(), payload.token);
|
||||
page.value = "download";
|
||||
startLive();
|
||||
} catch (exc) {
|
||||
error.value = exc instanceof Error ? exc.message : "进入失败";
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function login() {
|
||||
if (platform.value === "huangdou") {
|
||||
await loginHuangdou();
|
||||
return;
|
||||
}
|
||||
if (platform.value === "dramabox") {
|
||||
await loginDramabox();
|
||||
return;
|
||||
}
|
||||
error.value = "";
|
||||
busy.value = true;
|
||||
try {
|
||||
@@ -709,7 +795,7 @@ async function logout() {
|
||||
sessionStorage.removeItem(SESSION_DEVICE_KEY);
|
||||
if (!current) return;
|
||||
try {
|
||||
await fetch(platform.value === "huangdou" ? "/api/huangdou/logout" : "/api/logout", {
|
||||
await fetch(isolated.value ? `${apiBase.value}/logout` : "/api/logout", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: current }),
|
||||
@@ -739,11 +825,12 @@ async function watchClose() {
|
||||
|
||||
async function askClose(win: ReturnType<typeof getCurrentWindow>) {
|
||||
try {
|
||||
const [rapt, huangdou] = await Promise.all([
|
||||
const [rapt, huangdou, dramabox] = await Promise.all([
|
||||
fetch("/api/downloads").then((item) => item.json()).catch(() => ({})),
|
||||
fetch("/api/huangdou/downloads").then((item) => item.json()).catch(() => ({})),
|
||||
fetch("/api/dramabox/downloads").then((item) => item.json()).catch(() => ({})),
|
||||
]);
|
||||
const count = Number(rapt.active_count || 0) + Number(huangdou.active_count || 0);
|
||||
const count = Number(rapt.active_count || 0) + Number(huangdou.active_count || 0) + Number(dramabox.active_count || 0);
|
||||
if (count > 0) {
|
||||
closeCount.value = count;
|
||||
closeAsk.value = true;
|
||||
@@ -775,9 +862,10 @@ onMounted(async () => {
|
||||
}
|
||||
savedAccounts.value = readList<SavedAccount>(ACCOUNTS_KEY);
|
||||
if (savedAccounts.value[0]) applyAccount(savedAccounts.value[0].email);
|
||||
if (platform.value === "dramabox") await loadDramaboxLanguages();
|
||||
const saved = sessionStorage.getItem(tokenKey());
|
||||
if (!saved) return;
|
||||
const response = await fetch(platform.value === "huangdou" ? "/api/huangdou/me" : "/api/me", {
|
||||
const response = await fetch(isolated.value ? `${apiBase.value}/me` : "/api/me", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: saved, device: sessionDevice() }),
|
||||
@@ -862,7 +950,7 @@ onUnmounted(stopLive);
|
||||
:token="token"
|
||||
:device="sessionDevice()"
|
||||
:api-base="apiBase"
|
||||
:remote-search="platform === 'huangdou'"
|
||||
:remote-search="isolated"
|
||||
@started="page = 'progress'"
|
||||
@play="openPlay"
|
||||
/>
|
||||
@@ -876,7 +964,7 @@ onUnmounted(stopLive);
|
||||
<DownloadProgressPage v-show="page === 'progress'" :api-base="apiBase" :active="downloadState.active" :done="downloadState.done" />
|
||||
<div v-show="page === 'settings'" class="settings-page">
|
||||
<n-alert v-if="settingsError" class="hint" type="error" :show-icon="false">{{ settingsError }}</n-alert>
|
||||
<SettingsPanel v-model:tab="settingsTab" :draft="draft" :hide-device="platform === 'huangdou'" @choose="chooseDownloadDirectory" />
|
||||
<SettingsPanel v-model:tab="settingsTab" :draft="draft" :hide-device="isolated" @choose="chooseDownloadDirectory" />
|
||||
</div>
|
||||
<div v-show="page === 'profile'" class="profile-page">
|
||||
<div class="profile-sheet">
|
||||
@@ -887,7 +975,7 @@ onUnmounted(stopLive);
|
||||
<span class="profile-name">{{ profile.nickname || "未命名" }}</span>
|
||||
<n-tag v-if="profile.badge" size="small" :bordered="false" type="success">{{ profile.badge }}</n-tag>
|
||||
</div>
|
||||
<span class="profile-sub">{{ profile.email || "未绑定邮箱" }}</span>
|
||||
<span class="profile-sub">{{ profile.email || (platform === "dramabox" ? profile.native || "" : "未绑定邮箱") }}</span>
|
||||
</div>
|
||||
<n-tooltip placement="bottom">
|
||||
<template #trigger>
|
||||
@@ -904,7 +992,7 @@ onUnmounted(stopLive);
|
||||
退出
|
||||
</n-tooltip>
|
||||
</div>
|
||||
<div class="profile-stats" :style="{ gridTemplateColumns: `repeat(${statFields.length}, minmax(0, 1fr))` }">
|
||||
<div v-if="statFields.length" class="profile-stats" :style="{ gridTemplateColumns: `repeat(${statFields.length}, minmax(0, 1fr))` }">
|
||||
<div v-for="item in statFields" :key="item.key" class="profile-stat">
|
||||
<span class="profile-stat-value">{{ profileNumber(item.key) }}</span>
|
||||
<span class="profile-stat-label">{{ item.label }}</span>
|
||||
@@ -945,6 +1033,9 @@ onUnmounted(stopLive);
|
||||
<n-tab v-for="item in methods" :key="item.id" :name="item.id">{{ item.label }}</n-tab>
|
||||
</n-tabs>
|
||||
<n-form label-placement="left" label-width="96" size="small" :show-feedback="false" @submit.prevent="login">
|
||||
<n-form-item v-if="platform === 'dramabox'" label="地区">
|
||||
<n-select v-model:value="dramaboxLang" filterable :options="dramaboxLangs" placeholder="选择国家 / 语言" />
|
||||
</n-form-item>
|
||||
<template v-if="platform === 'rapt' && method === 'password'">
|
||||
<n-form-item v-if="savedAccounts.length" label="已保存">
|
||||
<div class="device-line">
|
||||
@@ -984,7 +1075,7 @@ onUnmounted(stopLive);
|
||||
<n-text v-if="platform === 'rapt' && method === 'adb'" class="hint" depth="3">从已 root 的设备读取当前登录账号。未 root 的设备无法获取登录信息。默认同时读取这台设备的品牌、型号和系统版本,可在右下角设置里修改。</n-text>
|
||||
<n-alert v-if="error" class="hint" type="error" :show-icon="false">{{ error }}</n-alert>
|
||||
<div class="login-actions">
|
||||
<n-button type="primary" attr-type="submit" :loading="busy">{{ platform === "huangdou" ? "进入" : "登录" }}</n-button>
|
||||
<n-button type="primary" attr-type="submit" :loading="busy">{{ isolated ? "进入" : "登录" }}</n-button>
|
||||
</div>
|
||||
</n-form>
|
||||
</div>
|
||||
@@ -1009,7 +1100,7 @@ onUnmounted(stopLive);
|
||||
<n-modal v-model:show="settingsOpen" preset="card" title="设置" style="width: 640px">
|
||||
<div class="settings-modal-body">
|
||||
<n-alert v-if="settingsError" class="hint" type="error" :show-icon="false">{{ settingsError }}</n-alert>
|
||||
<SettingsPanel v-model:tab="settingsTab" :draft="draft" :hide-device="platform === 'huangdou'" @choose="chooseDownloadDirectory" />
|
||||
<SettingsPanel v-model:tab="settingsTab" :draft="draft" :hide-device="isolated" @choose="chooseDownloadDirectory" />
|
||||
</div>
|
||||
<template #footer>
|
||||
<div class="modal-actions">
|
||||
|
||||
Reference in New Issue
Block a user