feat: 接入 DramaBox 并按语言地区切换清单
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user