463 lines
14 KiB
Python
463 lines
14 KiB
Python
import json
|
|
import threading
|
|
from collections import OrderedDict
|
|
from urllib.parse import urlsplit
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, HTTPException, Query, Request
|
|
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.dramabox.private_mp4 import decrypt_if_needed
|
|
from server.services.playlist import is_direct_media
|
|
|
|
router = APIRouter(prefix="/api/dramabox")
|
|
|
|
|
|
class EnterBody(BaseModel):
|
|
language: str = ""
|
|
|
|
|
|
class AdbLoginBody(BaseModel):
|
|
serial: str = ""
|
|
language: str = ""
|
|
|
|
|
|
class TokenBody(BaseModel):
|
|
token: str = ""
|
|
refresh: bool = False
|
|
keyword: str = ""
|
|
language: str = ""
|
|
|
|
|
|
class CatalogSettingsBody(BaseModel):
|
|
max_pages: int | None = None
|
|
|
|
|
|
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("/login/adb")
|
|
def login_adb(body: AdbLoginBody):
|
|
return call(lambda: db_login.import_adb(body.serial, body.language))
|
|
|
|
|
|
@router.get("/login/credential")
|
|
def export_credential():
|
|
return call(db_login.export_credential)
|
|
|
|
|
|
class CredentialBody(BaseModel):
|
|
kind: str = ""
|
|
version: int = 0
|
|
app: dict = {}
|
|
language: str = ""
|
|
|
|
|
|
@router.post("/login/credential/save")
|
|
def save_credential():
|
|
return call(db_login.save_credential_file)
|
|
|
|
|
|
@router.post("/login/credential")
|
|
def import_credential(body: CredentialBody):
|
|
return call(lambda: db_login.import_credential(body.model_dump(), body.language))
|
|
|
|
|
|
@router.post("/resume")
|
|
def resume():
|
|
return call(db_login.resume)
|
|
|
|
|
|
@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.get("/catalog/settings")
|
|
def get_catalog_settings():
|
|
return {"max_pages": db_catalog.page_limit()}
|
|
|
|
|
|
@router.post("/catalog/settings")
|
|
def update_catalog_settings(body: CatalogSettingsBody):
|
|
if body.max_pages is None:
|
|
return {"max_pages": db_catalog.page_limit()}
|
|
return {"max_pages": db_catalog.set_page_limit(body.max_pages)}
|
|
|
|
|
|
@router.post("/catalog")
|
|
async def load_catalog(body: TokenBody):
|
|
try:
|
|
_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)
|
|
|
|
|
|
_play_files: OrderedDict[tuple[str, int], bytes] = OrderedDict()
|
|
_play_lock = threading.Lock()
|
|
_play_inflight: dict[tuple[str, int], threading.Event] = {}
|
|
_PLAY_KEEP = 2
|
|
|
|
|
|
def _load_play_file(vid: str, cid: int, src: str) -> bytes:
|
|
key = (str(vid), int(cid))
|
|
while True:
|
|
with _play_lock:
|
|
hit = _play_files.get(key)
|
|
if hit is not None:
|
|
_play_files.move_to_end(key)
|
|
return hit
|
|
waiter = _play_inflight.get(key)
|
|
if waiter is None:
|
|
waiter = threading.Event()
|
|
_play_inflight[key] = waiter
|
|
owner = True
|
|
else:
|
|
owner = False
|
|
if owner:
|
|
break
|
|
if not waiter.wait(timeout=120):
|
|
raise HTTPException(status_code=502, detail="视频读取失败")
|
|
try:
|
|
try:
|
|
upstream = http.open_stream(src, headers=cdn_headers(book_id=vid), timeout=httpx.Timeout(90.0))
|
|
try:
|
|
data = b"".join(chunk for chunk in upstream.iter_bytes(64 * 1024) if chunk)
|
|
finally:
|
|
upstream.close()
|
|
data = decrypt_if_needed(data)
|
|
except (httpx.HTTPError, TimeoutError, OSError, RuntimeError, ValueError) as exc:
|
|
raise HTTPException(status_code=502, detail="视频读取失败") from exc
|
|
with _play_lock:
|
|
_play_files[key] = data
|
|
_play_files.move_to_end(key)
|
|
while len(_play_files) > _PLAY_KEEP:
|
|
_play_files.popitem(last=False)
|
|
return data
|
|
finally:
|
|
with _play_lock:
|
|
event = _play_inflight.pop(key, None)
|
|
if event is not None:
|
|
event.set()
|
|
|
|
|
|
def _parse_byte_range(header: str | None, total: int) -> tuple[int, int] | None:
|
|
text = (header or "").strip()
|
|
if not text:
|
|
return None
|
|
if not text.lower().startswith("bytes="):
|
|
raise ValueError("range")
|
|
spec = text.split("=", 1)[1].split(",", 1)[0].strip()
|
|
if "-" not in spec:
|
|
raise ValueError("range")
|
|
left, right = spec.split("-", 1)
|
|
try:
|
|
if left == "":
|
|
length = int(right)
|
|
if length <= 0:
|
|
raise ValueError("range")
|
|
start = max(0, total - length)
|
|
end = total - 1
|
|
else:
|
|
start = int(left)
|
|
end = int(right) if right else total - 1
|
|
except ValueError as exc:
|
|
raise ValueError("range") from exc
|
|
if start < 0 or end < start or start >= total:
|
|
raise ValueError("range")
|
|
return start, min(end, total - 1)
|
|
|
|
|
|
def _ranged_mp4(data: bytes, range_header: str | None) -> Response:
|
|
total = len(data)
|
|
headers = {"Accept-Ranges": "bytes", "Cache-Control": "no-store"}
|
|
try:
|
|
parsed = _parse_byte_range(range_header, total)
|
|
except ValueError:
|
|
return Response(status_code=416, headers={**headers, "Content-Range": f"bytes */{total}"})
|
|
if parsed is None:
|
|
headers["Content-Length"] = str(total)
|
|
return Response(content=data, media_type="video/mp4", headers=headers)
|
|
start, end = parsed
|
|
chunk = data[start:end + 1]
|
|
headers["Content-Range"] = f"bytes {start}-{end}/{total}"
|
|
headers["Content-Length"] = str(len(chunk))
|
|
return Response(content=chunk, status_code=206, media_type="video/mp4", headers=headers)
|
|
|
|
|
|
@router.get("/play/{vid}/{cid}/file")
|
|
def play_file(vid: str, cid: int, request: Request):
|
|
row = db_playlist.episode_src(vid, cid)
|
|
src = str(row.get("src") or "").strip()
|
|
if not src:
|
|
raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址")
|
|
return _ranged_mp4(_load_play_file(vid, cid, src), request.headers.get("range"))
|
|
|
|
|
|
@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)
|
|
items = []
|
|
for item in body.items:
|
|
data = item.model_dump()
|
|
data["language"] = client.language
|
|
items.append(data)
|
|
return db_downloads.enqueue(body.token, None, 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)
|