feat: 接入黄豆短剧独立清单与下载

This commit is contained in:
Nixevol
2026-10-21 22:54:56 +08:00
parent e31e80384c
commit 5b4a948e5f
25 changed files with 2093 additions and 132 deletions
+324
View File
@@ -0,0 +1,324 @@
import json
from urllib.parse import urlsplit
import httpx
from fastapi import APIRouter, HTTPException
from fastapi.responses import Response, StreamingResponse
from pydantic import BaseModel
from server.errors import call
from server.services.http import http
from server.services.huangdou import catalog as hd_catalog
from server.services.huangdou import login as hd_login
from server.services.huangdou import playlist as hd_playlist
from server.services.huangdou.client import client
from server.services.huangdou.covers import covers
from server.services.huangdou.crypto import USER_AGENT
from server.services.huangdou.downloads import downloads as hd_downloads
from server.services.playlist import is_direct_media
router = APIRouter(prefix="/api/huangdou")
class TokenBody(BaseModel):
token: str = ""
refresh: bool = False
keyword: 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:
client.token = token
@router.post("/login/device")
def login_device():
return call(hd_login.enter)
@router.post("/me")
def me(body: TokenBody):
return call(lambda: hd_login.current(body.token))
@router.post("/logout")
def logout(body: TokenBody):
hd_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 hd_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": hd_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 = hd_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):
target = _public_url(url)
try:
upstream = http.open_stream(target, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"})
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"
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 = hd_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={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"})
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}/hls.key")
def play_key(vid: str, cid: int):
row = hd_playlist.episode_src(vid, cid)
raw = hd_playlist.decode_key(str(row.get("hls_key") or ""))
if not raw:
raise HTTPException(status_code=404, detail="没有这一集的密钥")
return Response(raw, media_type="application/octet-stream", headers={"Cache-Control": "no-store"})
@router.get("/play/{vid}/{cid}/index.m3u8")
def episode_playlist(vid: str, cid: int):
row = hd_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 = hd_playlist.playback_playlist(src)
key = str(row.get("hls_key") or "").strip()
if key and "EXT-X-KEY" not in text.upper():
lines = []
inserted = False
for line in text.splitlines():
lines.append(line)
if not inserted and line.startswith("#EXTM3U"):
lines.append(f'#EXT-X-KEY:METHOD=AES-128,URI="/api/huangdou/play/{vid}/{cid}/hls.key"')
inserted = True
text = "\n".join(lines) + "\n"
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 hd_downloads.snapshot()
@router.post("/downloads")
def start_downloads(body: DownloadStartBody):
def action():
_require_token(body.token)
return hd_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": hd_downloads.set_directory(body.path.strip())}
@router.post("/downloads/pick")
def pick_directory():
return {"directory": hd_downloads.pick_directory()}
@router.post("/downloads/choose")
def choose_directory():
return {"directory": hd_downloads.choose_directory()}
@router.get("/downloads/settings")
def get_download_settings():
return hd_downloads.settings_view()
@router.post("/downloads/settings")
def update_download_settings(body: DownloadSettingsBody):
if body.directory.strip():
hd_downloads.set_directory(body.directory.strip())
if body.workers is not None:
try:
hd_downloads.set_workers(body.workers)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return hd_downloads.settings_view()
@router.post("/downloads/pause-all")
def pause_all_downloads():
return hd_downloads.pause_all()
@router.post("/downloads/resume-all")
def resume_all_downloads():
return hd_downloads.resume_all()
@router.post("/downloads/remux")
def remux_downloads():
return call(hd_downloads.remux_saved)
@router.post("/downloads/{drama_id}/remux")
def remux_one_download(drama_id: str):
return call(lambda: hd_downloads.remux_job(drama_id))
@router.post("/downloads/{drama_id}/redownload")
def redownload_one(drama_id: str):
return call(lambda: hd_downloads.redownload(drama_id))
@router.post("/downloads/{drama_id}/pause")
def pause_download(drama_id: str):
return hd_downloads.pause(drama_id)
@router.post("/downloads/{drama_id}/resume")
def resume_download(drama_id: str):
return hd_downloads.resume(drama_id)
@router.post("/downloads/{drama_id}/cancel")
def cancel_download(drama_id: str):
return hd_downloads.cancel(drama_id)
@router.post("/downloads/{drama_id}/open")
def open_download(drama_id: str):
def action():
hd_downloads.open_folder(drama_id)
return hd_downloads.snapshot()
return call(action)
@router.delete("/downloads/{drama_id}")
def remove_download(drama_id: str):
return hd_downloads.remove(drama_id)