feat: DramaBox 全量走 App 接口,清单可停止并避免卡死
分类按 App 翻页,精选走推荐接口。清单顶部显示进度,停止后不再拉新剧,已拿到的封面继续加载。列表只绘制可见卡片,避免大量剧目占满主线程。
This commit is contained in:
+119
-22
@@ -1,8 +1,10 @@
|
||||
import json
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -15,6 +17,7 @@ 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")
|
||||
@@ -24,9 +27,9 @@ class EnterBody(BaseModel):
|
||||
language: str = ""
|
||||
|
||||
|
||||
class AccountBody(BaseModel):
|
||||
class AdbLoginBody(BaseModel):
|
||||
serial: str = ""
|
||||
language: str = ""
|
||||
user: dict = {}
|
||||
|
||||
|
||||
class TokenBody(BaseModel):
|
||||
@@ -36,6 +39,10 @@ class TokenBody(BaseModel):
|
||||
language: str = ""
|
||||
|
||||
|
||||
class CatalogSettingsBody(BaseModel):
|
||||
max_pages: int | None = None
|
||||
|
||||
|
||||
class DownloadItem(BaseModel):
|
||||
id: str | int
|
||||
title: str = ""
|
||||
@@ -80,9 +87,9 @@ def login_device(body: EnterBody | None = None):
|
||||
return call(lambda: db_login.enter(language))
|
||||
|
||||
|
||||
@router.post("/login/account")
|
||||
def login_account(body: AccountBody):
|
||||
return call(lambda: db_login.apply_account(body.language, body.user))
|
||||
@router.post("/login/adb")
|
||||
def login_adb(body: AdbLoginBody):
|
||||
return call(lambda: db_login.import_adb(body.serial, body.language))
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
@@ -101,6 +108,18 @@ def logout(body: TokenBody):
|
||||
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:
|
||||
@@ -199,27 +218,105 @@ def play_segment(url: str, vid: str = Query(default="")):
|
||||
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):
|
||||
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 "这一集还没有可播放的地址")
|
||||
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)
|
||||
return _ranged_mp4(_load_play_file(vid, cid, src), request.headers.get("range"))
|
||||
|
||||
|
||||
@router.get("/play/{vid}/{cid}/index.m3u8")
|
||||
|
||||
Reference in New Issue
Block a user