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
+4
View File
@@ -11,11 +11,13 @@ from server.routes.catalog import router as catalog_router
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.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
def create_app() -> FastAPI:
@@ -36,10 +38,12 @@ def create_app() -> FastAPI:
app.include_router(play_router)
app.include_router(live_router)
app.include_router(proxy_router)
app.include_router(huangdou_router)
@app.on_event("startup")
def start_downloads() -> None:
downloads.start()
huangdou_downloads.start()
@app.get("/health")
def health():
+1
View File
@@ -2,3 +2,4 @@ fastapi>=0.115
uvicorn>=0.32
websockets>=14
httpx[socks]>=0.28
cryptography>=44
+1 -1
View File
@@ -9,7 +9,7 @@ router = APIRouter(prefix="/api/downloads")
class DownloadItem(BaseModel):
id: int
id: str | int
title: str = ""
image: str = ""
+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)
+10 -2
View File
@@ -3,13 +3,20 @@ import asyncio
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.live import live
from server.services.sessions import sessions
router = APIRouter()
def _payload() -> dict:
def _payload(platform: str) -> dict:
if platform == "huangdou":
return {
"downloads": huangdou_downloads.snapshot(),
"profile": huangdou_client.profile or None,
}
profile = sessions.snapshot()
return {
"downloads": downloads.snapshot(),
@@ -20,13 +27,14 @@ def _payload() -> dict:
@router.websocket("/api/live")
async def live_socket(websocket: WebSocket):
await websocket.accept()
platform = (websocket.query_params.get("platform") or "rapt").strip() or "rapt"
seen = -1
try:
while True:
revision = await asyncio.to_thread(live.wait, seen, 20)
if revision != seen:
seen = revision
await websocket.send_json(_payload())
await websocket.send_json(_payload(platform))
else:
await websocket.send_json({"type": "ping"})
except WebSocketDisconnect:
+124 -30
View File
@@ -60,10 +60,29 @@ def _default_directory() -> str:
class DownloadManager:
def __init__(self) -> None:
def __init__(
self,
*,
state_dir: Path | None = None,
default_directory: str | None = None,
load_episodes=None,
write_intro=None,
read_cover=None,
current_auth=None,
headers: dict | None = None,
) -> None:
self._lock = threading.Lock()
self._jobs: dict[str, dict] = {}
self._directory = _default_directory()
self._state_dir = Path(state_dir) if state_dir else STATE_DIR
self._state_path = self._state_dir / "jobs.json"
self._settings_path = self._state_dir / "settings.json"
self._default_directory = default_directory or _default_directory()
self._directory = self._default_directory
self._load_episodes = load_episodes
self._write_intro_fn = write_intro
self._read_cover_fn = read_cover
self._current_auth = current_auth
self._headers = dict(headers or {})
self._worker_limit = DEFAULT_WORKERS
self._alive_workers = 0
self._wake = threading.Event()
@@ -124,7 +143,7 @@ class DownloadManager:
return {
"directory": self._directory,
"workers": self._worker_limit,
"default_directory": _default_directory(),
"default_directory": self._default_directory,
}
def set_workers(self, count: int) -> int:
@@ -320,7 +339,7 @@ class DownloadManager:
os.startfile(folder) # noqa: S606
def _enqueue_one(self, drama_id: str, title: str, image: str, token: str, device, directory: str) -> None:
episodes = playlists.load_episodes(token, device, int(drama_id))
episodes = self._episodes_of(token, device, drama_id)
with self._lock:
job = self._jobs.get(drama_id)
if job is None:
@@ -337,6 +356,7 @@ class DownloadManager:
"episodes": [],
"error": "",
"fraction": 0,
"auth_token": token,
}
self._jobs[drama_id] = job
else:
@@ -351,6 +371,8 @@ class DownloadManager:
pass
elif job["status"] not in ACTIVE:
job["status"] = "queued"
if token:
job["auth_token"] = token
self._apply_episodes_locked(job, episodes)
if job["status"] == "paused":
job["command"] = "pause"
@@ -367,6 +389,7 @@ class DownloadManager:
if phase == "done" and not self._mp4_exists(job, ep):
phase = "pending" if ep.get("src") else "skipped"
merged.append({
**{key: value for key, value in ep.items() if key not in {"phase", "cid", "idx", "title", "src"}},
"cid": int(ep["cid"]),
"idx": int(ep.get("idx") or 0),
"title": ep.get("title") or "",
@@ -390,6 +413,9 @@ class DownloadManager:
self._save_intro(folder, drama_id, title, token, device)
def _save_intro(self, folder: Path, drama_id: str, title: str, token: str, device) -> None:
if self._write_intro_fn is not None:
self._write_intro_fn(folder, drama_id, title, token, device)
return
vid = drama_id
name = title.strip()
desc = ""
@@ -422,7 +448,10 @@ class DownloadManager:
if not digest:
return
try:
data, media = covers.read(digest)
if self._read_cover_fn is not None:
data, media = self._read_cover_fn(image)
else:
data, media = covers.read(digest)
except Exception:
return
if not data:
@@ -478,12 +507,11 @@ class DownloadManager:
job = self._jobs.get(drama_id)
if job is None:
return
token = sessions.active_token()
device = sessions.device_for(token) if token else None
token, device = self._auth_of(job)
folder = Path(job["folder"])
image = str(job.get("image") or "")
title = str(job.get("title") or "")
episodes = playlists.load_episodes(token, device, int(drama_id))
episodes = self._episodes_of(token, device, drama_id)
with self._lock:
job = self._jobs.get(drama_id)
if job is None:
@@ -575,17 +603,23 @@ class DownloadManager:
def _write_playlist(self, drama_id: str, folder: Path, row: dict) -> None:
source_dir, _mp4_path = self._episode_paths(folder, row)
master_text, media_text, items, audio_text, audio_items = playlists.expand_variant(row["src"])
if playlists.is_direct_media(row.get("src") or ""):
self._set_segments(drama_id, row["cid"], 1, 0)
return
headers = self._headers or None
master_text, media_text, items, audio_text, audio_items = playlists.expand_variant(row["src"], headers=headers)
source_dir.mkdir(parents=True, exist_ok=True)
key = str(row.get("hls_key") or "").strip()
if key:
from server.services.huangdou.playlist import apply_hls_key, store_fallback_key
store_fallback_key(source_dir, key)
media_text = apply_hls_key(media_text, source_dir, key)
(source_dir / "video.m3u8").write_text(media_text, encoding="utf-8", newline="\n")
if audio_text and audio_items:
(source_dir / "audio.m3u8").write_text(audio_text, encoding="utf-8", newline="\n")
master_text = _point_audio_at_local(master_text)
(source_dir / "playlist.m3u8").write_text(
_localize(master_text, ["video.m3u8"]),
encoding="utf-8",
newline="\n",
)
(source_dir / "playlist.m3u8").write_text(_local_master(master_text), encoding="utf-8", newline="\n")
saved_items = list(items) + list(audio_items)
(source_dir / "segments.json").write_text(json.dumps(saved_items, ensure_ascii=False), encoding="utf-8")
if row.get("src"):
@@ -623,6 +657,9 @@ class DownloadManager:
self._set_segments(drama_id, row["cid"], len(items), len(items))
self._set_phase(drama_id, row["cid"], "done")
return
if playlists.is_direct_media(row.get("src") or ""):
self._download_direct(drama_id, folder, row)
return
self._set_phase(drama_id, row["cid"], "downloading")
self._write_playlist(drama_id, folder, row)
items = json.loads(manifest.read_text(encoding="utf-8"))
@@ -632,12 +669,20 @@ class DownloadManager:
raise RuntimeError("已停止")
target = source_dir / item["name"]
if not target.is_file() or target.stat().st_size <= 0:
http.download_file(
item["url"],
target,
on_chunk=lambda size, job_id=drama_id: self._note_bytes(job_id, size),
stop=lambda job_id=drama_id: self._stopped(job_id),
)
try:
http.download_file(
item["url"],
target,
on_chunk=lambda size, job_id=drama_id: self._note_bytes(job_id, size),
stop=lambda job_id=drama_id: self._stopped(job_id),
headers=self._headers or None,
)
except RuntimeError:
fallback = source_dir / "hls.key"
if str(item.get("name") or "").lower().endswith(".key") and fallback.is_file() and fallback.stat().st_size > 0:
shutil.copy2(fallback, target)
else:
raise
done = sum(1 for part in items[:index] if (source_dir / part["name"]).is_file() and (source_dir / part["name"]).stat().st_size > 0)
earlier = sum(1 for part in items[index:] if (source_dir / part["name"]).is_file() and (source_dir / part["name"]).stat().st_size > 0)
self._set_segments(drama_id, row["cid"], total, done + earlier)
@@ -648,6 +693,33 @@ class DownloadManager:
self._set_phase(drama_id, row["cid"], "done")
self._set_segments(drama_id, row["cid"], total, total)
def _download_direct(self, drama_id: str, folder: Path, row: dict) -> None:
source_dir, mp4_path = self._episode_paths(folder, row)
if _keep_finished_episode(str(row.get("phase") or ""), mp4_path):
self._set_segments(drama_id, row["cid"], 1, 1)
self._set_phase(drama_id, row["cid"], "done")
return
self._set_phase(drama_id, row["cid"], "downloading")
source_dir.mkdir(parents=True, exist_ok=True)
target = source_dir / "video.mp4"
if not target.is_file() or target.stat().st_size <= 0:
http.download_file(
row["src"],
target,
on_chunk=lambda size, job_id=drama_id: self._note_bytes(job_id, size),
stop=lambda job_id=drama_id: self._stopped(job_id),
headers=self._headers or None,
)
if self._stopped(drama_id):
raise RuntimeError("已停止")
if not target.is_file() or target.stat().st_size <= 0:
raise RuntimeError("试看文件没有下下来")
mp4_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(target, mp4_path)
(source_dir / "master.url").write_text(str(row["src"]).strip() + "\n", encoding="utf-8")
self._set_segments(drama_id, row["cid"], 1, 1)
self._set_phase(drama_id, row["cid"], "done")
def _set_phase(self, drama_id: str, cid: int, phase: str) -> None:
with self._lock:
job = self._jobs.get(drama_id)
@@ -708,11 +780,27 @@ class DownloadManager:
"error": job.get("error") or "",
}
def _episodes_of(self, token: str, device, drama_id: str) -> list[dict]:
if self._load_episodes is not None:
return self._load_episodes(token, device, drama_id)
return playlists.load_episodes(token, device, int(drama_id))
def _auth_of(self, job: dict) -> tuple[str, object | None]:
if self._current_auth is not None:
token, device = self._current_auth()
else:
token = sessions.active_token()
device = sessions.device_for(token) if token else None
stored = str(job.get("auth_token") or "").strip()
if stored:
token = stored
return token, device
def _load(self) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
if SETTINGS_PATH.is_file():
self._state_dir.mkdir(parents=True, exist_ok=True)
if self._settings_path.is_file():
try:
data = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
data = json.loads(self._settings_path.read_text(encoding="utf-8"))
if isinstance(data, dict) and data.get("directory"):
self._directory = data["directory"]
workers = data.get("workers") if isinstance(data, dict) else None
@@ -720,10 +808,10 @@ class DownloadManager:
self._worker_limit = workers
except (OSError, json.JSONDecodeError):
pass
if not STATE_PATH.is_file():
if not self._state_path.is_file():
return
try:
data = json.loads(STATE_PATH.read_text(encoding="utf-8"))
data = json.loads(self._state_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return
jobs = data.get("jobs") if isinstance(data, dict) else None
@@ -733,19 +821,19 @@ class DownloadManager:
self._jobs[str(job["id"])] = job
def _save_locked(self) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
self._state_dir.mkdir(parents=True, exist_ok=True)
stored = []
for job in self._jobs.values():
stored.append({key: value for key, value in job.items() if key != "fraction"})
temporary = STATE_PATH.with_suffix(".json.tmp")
temporary = self._state_path.with_suffix(".json.tmp")
temporary.write_text(json.dumps({"jobs": stored}, ensure_ascii=False), encoding="utf-8")
temporary.replace(STATE_PATH)
temporary.replace(self._state_path)
self._save_settings_locked()
live.touch()
def _save_settings_locked(self) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
SETTINGS_PATH.write_text(
self._state_dir.mkdir(parents=True, exist_ok=True)
self._settings_path.write_text(
json.dumps({"directory": self._directory, "workers": self._worker_limit}, ensure_ascii=False),
encoding="utf-8",
)
@@ -777,6 +865,12 @@ def _seed_master_urls(drama_id: str, folder: Path, episodes: list[dict]) -> None
path.write_text(url + "\n", encoding="utf-8")
def _local_master(text: str) -> str:
if playlists.is_media_playlist(text):
return "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nvideo.m3u8\n"
return _localize(text, ["video.m3u8"])
def _point_audio_at_local(text: str) -> str:
lines = []
for line in text.splitlines():
+28 -8
View File
@@ -88,15 +88,26 @@ class HttpClient:
self._client = httpx.Client(**self._client_kwargs())
return self._client
def get_bytes(self, url: str) -> tuple[bytes, str]:
response = self._client_locked().get(url, headers={"User-Agent": "RaptDrama"})
def send(self, method: str, url: str, *, headers: dict | None = None, content: bytes | None = None, timeout=None) -> httpx.Response:
options: dict = {"headers": headers or {}}
if content is not None:
options["content"] = content
if timeout is not None:
options["timeout"] = timeout
return self._client_locked().request(method, url, **options)
def get_bytes(self, url: str, headers: dict | None = None) -> tuple[bytes, str]:
hdrs = {"User-Agent": "RaptDrama"}
if headers:
hdrs.update(headers)
response = self._client_locked().get(url, headers=hdrs)
response.raise_for_status()
media = response.headers.get("content-type", "image/jpeg").split(";", 1)[0].strip() or "image/jpeg"
if not media.startswith("image/"):
raise RuntimeError("不是图片")
return response.content, media
def download_file(self, url: str, dest, on_chunk=None, stop=None) -> int:
def download_file(self, url: str, dest, on_chunk=None, stop=None, headers: dict | None = None) -> int:
from pathlib import Path
target = Path(dest)
@@ -107,7 +118,10 @@ class HttpClient:
if stop and stop():
raise RuntimeError("已取消")
try:
with self._client_locked().stream("GET", url, headers={"User-Agent": "RaptDrama"}) as response:
hdrs = {"User-Agent": "RaptDrama"}
if headers:
hdrs.update(headers)
with self._client_locked().stream("GET", url, headers=hdrs) as response:
response.raise_for_status()
size = 0
with temporary.open("wb") as handle:
@@ -131,11 +145,14 @@ class HttpClient:
time.sleep(0.4)
raise RuntimeError(f"下载失败: {last_error}")
def read_text(self, url: str) -> str:
def read_text(self, url: str, headers: dict | None = None) -> str:
last_error = None
hdrs = {"User-Agent": "RaptDrama"}
if headers:
hdrs.update(headers)
for _attempt in range(3):
try:
response = self._client_locked().get(url, headers={"User-Agent": "RaptDrama"})
response = self._client_locked().get(url, headers=hdrs)
response.raise_for_status()
return response.text
except (httpx.HTTPError, TimeoutError, OSError) as exc:
@@ -143,9 +160,12 @@ class HttpClient:
time.sleep(0.4)
raise RuntimeError(f"下载失败: {last_error}")
def open_stream(self, url: str) -> httpx.Response:
def open_stream(self, url: str, headers: dict | None = None) -> httpx.Response:
client = self._client_locked()
request = client.build_request("GET", url, headers={"User-Agent": "RaptDrama"})
hdrs = {"User-Agent": "RaptDrama"}
if headers:
hdrs.update(headers)
request = client.build_request("GET", url, headers=hdrs)
response = client.send(request, stream=True)
try:
response.raise_for_status()
+1
View File
@@ -0,0 +1 @@
"""黄豆短剧平台。会话、清单和下载与 RaptDrama 隔离。"""
+150
View File
@@ -0,0 +1,150 @@
from server.services.huangdou.client import ApiError, TokenExpired, client
from server.services.huangdou.crypto import USER_AGENT
def device_info() -> dict:
return {
"browserName": "Chrome",
"language": "zh-CN",
"userAgent": USER_AGENT,
"platform": "Win32",
}
def login_device(*, force_new: bool = False) -> dict:
data = client.request(
"/login/device",
{
"line_code": "china_1",
"channel_code": "",
"share_code": "",
"clipboard_text": "",
"force_new": "1" if force_new else "",
"device_info": device_info(),
},
auth=False,
)
if not isinstance(data, dict):
raise RuntimeError("设备登录没有返回数据")
token = str(data.get("token") or "").strip()
if not token:
raise RuntimeError("设备登录没有返回 token")
client.token = token
return data
def user_info() -> dict:
data = client.request("/user/info", {}, auth=True)
return data if isinstance(data, dict) else {}
def system_info() -> dict:
data = client.request(
"/system/info",
{
"line_code": "china_1",
"channel_code": "",
"share_code": "",
"clipboard_text": "",
"device_info": device_info(),
"package_name": "",
},
auth=True,
)
return data if isinstance(data, dict) else {}
def nav_list() -> list[dict]:
data = client.request("/drama/navList", {"with_filters": "1"}, auth=True)
rows = _list_of(data)
return [item for item in rows if isinstance(item, dict)]
def nav_block(code: str, tab: str = "", page: int = 1) -> list[dict]:
data = client.request(
"/drama/navBlock",
{"code": str(code or ""), "tab": str(tab or ""), "page": str(page)},
auth=True,
)
rows = _list_of(data)
return [item for item in rows if isinstance(item, dict)]
def drama_list(
*,
page: int = 1,
page_size: int = 18,
keywords: str = "",
order: str = "",
cat_id: str = "",
tag_id: str = "",
source: str = "",
canvas: str = "",
pay_type: str = "",
update_status: str = "",
) -> list[dict]:
body = {"page": str(page), "page_size": str(page_size)}
if order:
body["order"] = order
if cat_id:
body["cat_id"] = cat_id
if tag_id:
body["tag_id"] = tag_id
if source:
body["source"] = source
if canvas:
body["canvas"] = canvas
if keywords:
body["keywords"] = keywords
if update_status:
body["update_status"] = update_status
if pay_type:
body["pay_type"] = pay_type
data = client.request("/drama/list", body, auth=True)
rows = _list_of(data)
return [item for item in rows if isinstance(item, dict)]
def limited_free(page: int = 1) -> list[dict]:
data = client.request("/drama/limitedFree", {"page": str(page), "size": "18"}, auth=True)
rows = _list_of(data)
return [item for item in rows if isinstance(item, dict)]
def drama_detail(drama_id: str) -> dict:
data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True)
return data if isinstance(data, dict) else {}
def drama_play(drama_id: str, seq: int) -> dict:
data = client.request("/drama/play", {"id": str(drama_id), "seq": str(seq)}, auth=True)
return data if isinstance(data, dict) else {}
def _list_of(data) -> list:
if isinstance(data, list):
return data
if isinstance(data, dict):
rows = data.get("list")
if isinstance(rows, list):
return rows
items = data.get("items")
if isinstance(items, list):
return items
return []
__all__ = [
"ApiError",
"TokenExpired",
"client",
"drama_detail",
"drama_list",
"drama_play",
"limited_free",
"login_device",
"nav_block",
"nav_list",
"system_info",
"user_info",
]
+261
View File
@@ -0,0 +1,261 @@
import asyncio
import json
import os
from pathlib import Path
from server.services.huangdou import api
from server.services.huangdou.covers import covers
CACHE_PATH = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "catalog.json"
AD_STYLE = {"ad", "banner", "splash", "advert"}
def enabled_cache() -> bool:
flag = os.environ.get("RAPTD_CATALOG_CACHE", "1").strip().lower()
return flag not in ("0", "false", "no")
async def stream(refresh: bool = False):
if enabled_cache():
if refresh:
CACHE_PATH.unlink(missing_ok=True)
else:
cached = _read_cache()
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(collected)
async def _fetch():
navs = await asyncio.to_thread(api.nav_list)
sections = []
jobs = []
for index, nav in enumerate(navs):
code = str(nav.get("code") or "").strip()
name = str(nav.get("name") or "").strip()
if not name:
continue
key = f"nav-{code or index}"
sections.append({"key": key, "name": name, "note": "", "loading": True})
jobs.append((key, name, nav))
sections.append({"key": "limited-free", "name": "限时免费", "note": "", "loading": True})
if not sections:
raise RuntimeError("没有获取到分类")
yield {"type": "outline", "sections": sections}
loop = asyncio.get_running_loop()
queue: asyncio.Queue = asyncio.Queue()
async def run(job):
key, name, nav = job
def work():
try:
items = _nav_items(nav)
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)
await asyncio.to_thread(work)
async def run_limited():
def work():
try:
items = [_drama(item) for item in api.limited_free(1)]
items = [item for item in items if item]
loop.call_soon_threadsafe(queue.put_nowait, _page("limited-free", "限时免费", items, done=True))
except Exception as exc:
loop.call_soon_threadsafe(
queue.put_nowait,
_page("limited-free", "限时免费", [], str(exc) or "获取清单失败", done=True, failed=True),
)
finally:
loop.call_soon_threadsafe(queue.put_nowait, None)
await asyncio.to_thread(work)
tasks = [asyncio.create_task(run(job)) for job in jobs]
tasks.append(asyncio.create_task(run_limited()))
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()
for page in range(1, 6):
rows = api.drama_list(page=page, page_size=18, keywords=text)
if 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) < 18:
break
return items
def _nav_items(nav: dict) -> list[dict]:
code = str(nav.get("code") or "").strip()
items = _block_items(code) if code else []
if items:
return items
return _filter_items(nav)
def _filter_items(nav: dict) -> list[dict]:
filters = nav.get("filters")
if not isinstance(filters, list) or not filters:
return []
items = []
seen: set[str] = set()
primary = filters[0] if isinstance(filters[0], dict) else {}
params = primary.get("filter") if isinstance(primary.get("filter"), dict) else {}
for page in range(1, 4):
rows = api.drama_list(
page=page,
page_size=18,
order=str(params.get("order") or ""),
cat_id=str(params.get("cat_id") or ""),
tag_id=str(params.get("tag_id") or ""),
source=str(params.get("source") or ""),
canvas=str(params.get("canvas") or ""),
pay_type=str(params.get("pay_type") or ""),
update_status=str(params.get("update_status") or ""),
)
if 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) < 18:
break
for extra in filters[1:]:
if not isinstance(extra, dict):
continue
params = extra.get("filter") if isinstance(extra.get("filter"), dict) else {}
rows = api.drama_list(
page=1,
page_size=18,
order=str(params.get("order") or ""),
cat_id=str(params.get("cat_id") or ""),
tag_id=str(params.get("tag_id") or ""),
source=str(params.get("source") or ""),
canvas=str(params.get("canvas") or ""),
pay_type=str(params.get("pay_type") or ""),
update_status=str(params.get("update_status") or ""),
)
for item in rows:
drama = _drama(item)
if not drama or drama["id"] in seen:
continue
seen.add(drama["id"])
items.append(drama)
return items
def _block_items(code: str) -> list[dict]:
blocks = api.nav_block(code, page=1)
items = []
seen = set()
for block in blocks:
style = str(block.get("style") or "").strip().lower()
route = str(block.get("route") or "").strip().lower()
if style in AD_STYLE or "ad" in route:
continue
rows = block.get("items")
if not isinstance(rows, list):
continue
for item in rows:
drama = _drama(item)
if not drama or drama["id"] in seen:
continue
seen.add(drama["id"])
items.append(drama)
return items
def _drama(item: dict) -> dict | None:
if not isinstance(item, dict):
return None
drama_id = str(item.get("id") or item.get("drama_id") or "").strip()
title = str(item.get("name") or item.get("title") or "").strip()
if not drama_id or not title:
return None
image = str(item.get("img_y") or item.get("img") or item.get("img_x") or "").strip()
pay_type = str(item.get("pay_type") or "").strip()
episode_type = str(item.get("type") or "").strip()
return {
"id": drama_id,
"title": title,
"image": covers.local_url(image) if image else "",
"payType": pay_type,
"episodeCount": str(item.get("episode_count") or ""),
"corner": str(item.get("corner") or ""),
"limitedFree": item.get("limited_free") is True,
"locked": bool(pay_type) and pay_type not in {"free", "0", "none"},
"kind": episode_type,
}
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() -> list[dict] | None:
if not CACHE_PATH.is_file():
return None
try:
data = json.loads(CACHE_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(events: list[dict]) -> None:
CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
temporary = CACHE_PATH.with_suffix(".json.tmp")
temporary.write_text(json.dumps({"events": events}, ensure_ascii=False), encoding="utf-8")
temporary.replace(CACHE_PATH)
+152
View File
@@ -0,0 +1,152 @@
import json
import time
from pathlib import Path
from server.services.http import http
from server.services.huangdou.crypto import (
APP_VERSION,
DEVICE_TYPE,
LANG,
USER_AGENT,
decrypt_body,
encrypt_body,
new_uuid,
session_id_of,
sign_header,
)
ROOT = Path(__file__).resolve().parents[3]
STATE_DIR = ROOT / "cache" / "huangdou"
SESSION_PATH = STATE_DIR / "session.json"
HOSTS = (
"https://pmihlvee.cc",
"https://sxqirtho.top",
"https://qicuknlj.top",
"https://ferncider.cc",
"https://hvthtcpa.top",
"https://onyxripple.cc",
"https://vivifable.top",
"https://kucvcxrv.cc",
"https://larkgarden.top",
"https://niniharbor.top",
"https://larksummit.icu",
)
LINE_CODE = "china_1"
class TokenExpired(RuntimeError):
pass
class ApiError(RuntimeError):
def __init__(self, message: str, code=None) -> None:
super().__init__(message)
self.code = code
class HuangdouClient:
def __init__(self) -> None:
self.device_id = new_uuid()
self.session_id = session_id_of("")
self.token = ""
self.host = HOSTS[0]
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.device_id = str(data.get("device_id") or self.device_id)
self.session_id = session_id_of(str(data.get("session_id") or self.session_id))
self.token = str(data.get("token") or "")
host = str(data.get("host") or "")
if host.startswith("https://"):
self.host = host.rstrip("/")
profile = data.get("profile")
if isinstance(profile, dict):
self.profile = profile
def save(self) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
payload = {
"device_id": self.device_id,
"session_id": self.session_id,
"token": self.token,
"host": self.host,
"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 clear_token(self) -> None:
self.token = ""
self.profile = {}
self.save()
def request(self, path: str, data: dict | None = None, *, auth: bool = True) -> dict | list | None:
last_error: Exception | None = None
hosts = [self.host, *[item for item in HOSTS if item != self.host]]
for host in hosts:
try:
payload = self._call(host, path, data or {}, auth=auth)
self.host = host
return payload
except (TokenExpired, ApiError):
raise
except RuntimeError as exc:
last_error = exc
raise last_error or RuntimeError("网络请求异常")
def _call(self, host: str, path: str, data: dict, *, auth: bool) -> dict | list | None:
url = host.rstrip("/") + "/api" + path
request_id = new_uuid()
now = str(int(time.time()))
body = {
"token": self.token if auth else "",
"deviceId": self.device_id,
"data": data,
}
headers = {
"Accept": "*/*",
"Accept-Language": LANG,
"Content-Type": "application/x-www-form-urlencoded",
"Origin": host,
"Referer": host + "/",
"User-Agent": USER_AGENT,
"version": APP_VERSION,
"deviceType": DEVICE_TYPE,
"time": now,
"sign": sign_header(self.session_id, request_id, now, url),
"requestId": request_id,
"sessionId": self.session_id,
"deviceBrand": "",
"deviceModel": "",
"systemName": "",
"systemVersion": "",
"X-Lang": LANG,
}
try:
response = http.send("POST", url, headers=headers, content=encrypt_body(body, request_id), timeout=30.0)
except Exception as exc:
raise RuntimeError(f"请求失败: {exc}") from exc
if response.status_code != 200:
raise RuntimeError(f"网络请求异常 ({response.status_code})")
parsed = decrypt_body(response.content, request_id)
if parsed.get("status") == "n":
code = parsed.get("errorCode")
if str(code) == "2002":
raise TokenExpired("登录已失效")
raise ApiError(str(parsed.get("error") or "网络请求异常"), code)
return parsed.get("data")
client = HuangdouClient()
+71
View File
@@ -0,0 +1,71 @@
import hashlib
import re
import threading
from pathlib import Path
from server.services.http import http
from server.services.huangdou.crypto import USER_AGENT, decrypt_resource
CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "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/huangdou/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/huangdou/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 = http.get_bytes(remote, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"})
data = decrypt_resource(data)
media = _sniff_media(data) or media
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 _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()
+115
View File
@@ -0,0 +1,115 @@
import gzip
import hashlib
import hmac
import json
import os
import re
import uuid
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.padding import PKCS7
WEB_AES_KEY = "7961beb44246e3012ce228d6b5ced05a"
IMAGE_AES_KEY = "525202f9149e061d"
SIGN_PREFIX = "Dart"
APP_VERSION = "2.0.0"
DEVICE_TYPE = "web"
LANG = "zh-CN"
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
)
_SCHEME = re.compile(r"^https?://", re.I)
_IMAGE_MAGIC = (
b"\xff\xd8\xff",
b"\x89PNG",
b"GIF8",
b"RIFF",
b"\x00\x00\x00 ftyp",
)
def new_uuid() -> str:
return str(uuid.uuid4())
def session_id_of(value: str) -> str:
text = (value or "").strip()
if not text:
text = new_uuid()
return text.replace("-", "")
def derive_aes_key(request_id: str, secret: str = WEB_AES_KEY) -> bytes:
raw = bytes.fromhex(request_id.replace("-", ""))
return hmac.new(secret.encode("utf-8"), raw, hashlib.sha256).digest()
def sign_header(session_id: str, request_id: str, time_text: str, url: str) -> str:
path = _SCHEME.sub("", url)
payload = f"{SIGN_PREFIX}|{session_id}|{request_id}|{time_text}|{path}"
digest = hashlib.md5(payload.encode("utf-8")).hexdigest()
return f"{digest}-{time_text}"
def _aes_cbc(key: bytes, iv: bytes, data: bytes, encrypt: bool) -> bytes:
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
if encrypt:
padder = PKCS7(128).padder()
blob = padder.update(data) + padder.finalize()
engine = cipher.encryptor()
return engine.update(blob) + engine.finalize()
engine = cipher.decryptor()
blob = engine.update(data) + engine.finalize()
unpadder = PKCS7(128).unpadder()
return unpadder.update(blob) + unpadder.finalize()
def encrypt_body(payload: dict, request_id: str, secret: str = WEB_AES_KEY) -> bytes:
plain = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
packed = gzip.compress(plain)
iv = os.urandom(16)
key = derive_aes_key(request_id, secret)
return iv + _aes_cbc(key, iv, packed, True)
def decrypt_body(blob: bytes, request_id: str, secret: str = WEB_AES_KEY) -> dict:
if len(blob) < 32:
raise RuntimeError("响应数据格式错误")
iv, data = blob[:16], blob[16:]
key = derive_aes_key(request_id, secret)
try:
raw = _aes_cbc(key, iv, data, False)
except ValueError as exc:
raise RuntimeError("响应数据格式错误") from exc
try:
text = gzip.decompress(raw).decode("utf-8")
except OSError:
text = raw.decode("utf-8")
try:
parsed = json.loads(text)
except json.JSONDecodeError as exc:
raise RuntimeError("响应数据格式错误") from exc
if not isinstance(parsed, dict):
raise RuntimeError("响应数据格式错误")
return parsed
def decrypt_resource(data: bytes, key: str = IMAGE_AES_KEY) -> bytes:
if _looks_like_image(data) or len(data) < 16 or len(data) % 16 != 0:
return data
secret = key.encode("utf-8")
cipher = Cipher(algorithms.AES(secret), modes.ECB())
engine = cipher.decryptor()
blob = engine.update(data) + engine.finalize()
try:
unpadder = PKCS7(128).unpadder()
plain = unpadder.update(blob) + unpadder.finalize()
except ValueError:
return data
return plain if _looks_like_image(plain) else data
def _looks_like_image(data: bytes) -> bool:
return any(data.startswith(magic) for magic in _IMAGE_MAGIC)
+76
View File
@@ -0,0 +1,76 @@
from pathlib import Path
from server.services.downloads import DownloadManager, _plain_text
from server.services.huangdou import api
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 import playlist as hd_playlist
ROOT = Path(__file__).resolve().parents[3]
def _load_episodes(_token, _device, drama_id: str) -> list[dict]:
return hd_playlist.load_episodes(str(drama_id))
def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) -> None:
name = title.strip()
desc = ""
pay_type = ""
free_episodes = ""
vip_episodes = ""
points_price = ""
money = ""
try:
detail = api.drama_detail(str(drama_id))
fetched = str(detail.get("name") or "").strip()
if fetched:
name = fetched
desc = _plain_text(detail.get("description") or "")
pay_type = _field(detail.get("pay_type"))
free_episodes = _field(detail.get("free_episodes"))
vip_episodes = _field(detail.get("vip_episodes"))
points_price = _field(detail.get("points_price"))
money = _field(detail.get("money"))
except Exception:
pass
lines = [
f"ID: {drama_id}",
f"名称: {name}",
f"简介: {desc}",
f"付费类型: {pay_type or '—'}",
f"免费集数: {free_episodes or '—'}",
f"VIP 集: {vip_episodes or '—'}",
f"积分价格: {points_price or '—'}",
f"金额: {money 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 _field(value) -> str:
if isinstance(value, list):
return "、".join(str(item) for item in value if item not in (None, ""))
text = str(value or "").strip()
return text
def _auth():
return client.token, None
downloads = DownloadManager(
state_dir=ROOT / "cache" / "huangdou" / "downloads",
default_directory=str((Path.cwd() / "download" / "huangdou").resolve()),
load_episodes=_load_episodes,
write_intro=_write_intro,
read_cover=_read_cover,
current_auth=_auth,
headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"},
)
+89
View File
@@ -0,0 +1,89 @@
from server.services.huangdou import api
from server.services.huangdou.client import TokenExpired, client
from server.services.huangdou.covers import covers as huangdou_covers
def enter() -> dict:
try:
if client.token:
profile = _profile(api.user_info())
client.profile = profile
client.save()
return {"token": client.token, "profile": profile}
except TokenExpired:
client.clear_token()
except RuntimeError:
pass
raw = api.login_device(force_new=False)
try:
info = api.user_info()
except RuntimeError:
info = raw
profile = _profile(info if isinstance(info, dict) else raw)
client.profile = profile
client.save()
return {"token": client.token, "profile": profile}
def current(token: str) -> dict:
token = (token or "").strip()
if not token:
raise RuntimeError("请先登录")
if token != client.token:
client.token = token
try:
profile = _profile(api.user_info())
except TokenExpired as exc:
client.clear_token()
raise RuntimeError("登录已失效") from exc
client.profile = profile
client.save()
return {"token": client.token, "profile": profile}
def logout(token: str) -> None:
if token and token == client.token:
client.clear_token()
return
if not token:
client.clear_token()
def _profile(raw: dict) -> dict:
data = raw if isinstance(raw, dict) else {}
vip = _truthy(data.get("is_vip"))
head = str(data.get("headico") or "").strip()
return {
"id": data.get("id") or data.get("user_id") or "",
"username": data.get("username") or "",
"nickname": data.get("nickname") or data.get("username") or "黄豆用户",
"email": data.get("email") or "",
"phone": data.get("phone") or "",
"badge": "VIP" if vip else "",
"vipday": 1 if vip else 0,
"score": _number(data.get("balance")),
"watched": _number(data.get("play_num")),
"rewards": 0,
"login_day": 0,
"is_vip": data.get("is_vip") or "",
"balance": data.get("balance") or "0",
"group_name": data.get("group_name") or "",
"group_end_time": data.get("group_end_time") or "",
"account_type": data.get("account_type") or "",
"has_login": data.get("has_login") or "",
"sign": data.get("sign") or "",
"avatarNumUrl": huangdou_covers.local_url(head) if head else "",
"headico": head,
}
def _truthy(value) -> bool:
text = str(value or "").strip().lower()
return text in {"1", "true", "y", "yes", "vip"}
def _number(value) -> int:
try:
return int(float(str(value or "0")))
except (TypeError, ValueError):
return 0
+279
View File
@@ -0,0 +1,279 @@
import json
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from urllib.parse import quote, urljoin
from server.services.huangdou import api
from server.services.http import http
from server.services.huangdou.crypto import USER_AGENT
from server.services.playlist import is_direct_media, looks_like_segment
CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "playlists"
CDN_HEADERS = {"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"}
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) -> str:
if is_direct_media(src):
raise RuntimeError("这一集是整段视频")
text = http.read_text(src, headers=CDN_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=CDN_HEADERS), variant_url)
def decode_key(value: str) -> bytes:
text = (value or "").strip()
if not text:
return b""
try:
raw = bytes.fromhex(text)
if raw:
return raw
except ValueError:
pass
import base64
try:
return base64.b64decode(text)
except Exception:
return text.encode("utf-8")
def store_fallback_key(source_dir: Path, key: str) -> None:
raw = decode_key(key)
if not raw:
return
source_dir.mkdir(parents=True, exist_ok=True)
(source_dir / "hls.key").write_bytes(raw)
def _choose_src(played: dict) -> tuple[str, str]:
candidates: list[str] = []
for value in (played.get("m3u8"),):
text = str(value or "").strip()
if text:
candidates.append(text)
lines = played.get("lines") if isinstance(played.get("lines"), list) else []
for line in lines:
if not isinstance(line, dict):
continue
url = str(line.get("url") or "").strip()
if url:
candidates.append(url)
preview = str(played.get("preview_m3u8") or "").strip()
if preview:
candidates.append(preview)
for url in candidates:
if url and not is_direct_media(url):
return url, "hls"
for url in candidates:
if is_direct_media(url):
return url, "file"
return "", ""
def apply_hls_key(text: str, source_dir: Path, key: str) -> str:
secret = (key or "").strip()
if not secret:
return text
if "EXT-X-KEY" in text.upper():
return text
raw = decode_key(secret)
if not raw:
return text
source_dir.mkdir(parents=True, exist_ok=True)
(source_dir / "hls.key").write_bytes(raw)
lines = text.splitlines()
inserted = False
result = []
for line in lines:
result.append(line)
if not inserted and line.startswith("#EXTM3U"):
result.append('#EXT-X-KEY:METHOD=AES-128,URI="hls.key"')
inserted = True
if not inserted:
result.insert(0, '#EXT-X-KEY:METHOD=AES-128,URI="hls.key"')
return "\n".join(result) + "\n"
def _fetch_episodes(drama_id: str) -> list[dict]:
detail = api.drama_detail(drama_id)
rows = detail.get("episodes") if isinstance(detail, dict) else None
if not isinstance(rows, list) or not rows:
raise RuntimeError("没有读到分集")
skeleton = []
for item in rows:
if not isinstance(item, dict):
continue
seq = _int(item.get("seq"))
if seq <= 0:
continue
kind = str(item.get("type") or "free").strip() or "free"
skeleton.append({
"cid": seq,
"idx": seq,
"title": str(item.get("name") or f"第{seq}集").strip() or f"第{seq}集",
"src": "",
"type": kind,
"price": _int(item.get("price")),
"is_buy": item.get("is_buy") is True or item.get("is_buy") is None,
"cover": str(item.get("cover") or ""),
"duration": _int(item.get("duration")),
"methods": item.get("methods") if isinstance(item.get("methods"), list) else [],
"is_preview": False,
"preview_seconds": 0,
"preview_m3u8": "",
"hls_key": "",
"src_kind": "",
"locked_reason": "",
})
if not skeleton:
raise RuntimeError("没有读到分集")
def play_one(row: dict) -> dict:
try:
played = api.drama_play(drama_id, int(row["cid"]))
except RuntimeError as exc:
row["locked_reason"] = str(exc) or "这一集暂时不能下载"
return row
preview = str(played.get("preview_m3u8") or "").strip()
row["hls_key"] = str(played.get("hls_key") or "").strip()
row["is_preview"] = played.get("is_preview") is True
row["preview_seconds"] = _int(played.get("preview_seconds"))
row["preview_m3u8"] = preview
src, kind = _choose_src(played)
row["src"] = src
row["src_kind"] = kind
if src:
if kind == "file" or row["is_preview"]:
row["is_preview"] = True
row["locked_reason"] = "当前账号只能下到试看"
else:
row["locked_reason"] = _lock_reason(row)
return row
updated = []
with ThreadPoolExecutor(max_workers=6) as pool:
futures = [pool.submit(play_one, dict(row)) for row in skeleton]
by_cid = {}
for future in as_completed(futures):
row = future.result()
by_cid[int(row["cid"])] = row
for row in skeleton:
updated.append(by_cid.get(int(row["cid"]), row))
return updated
def _lock_reason(row: dict) -> str:
kind = str(row.get("type") or "free")
if kind in {"vip", "VIP"}:
return "需要 VIP"
if kind in {"coin", "points", "point", "pay"}:
return "需要积分或付费"
if not row.get("is_buy"):
return "尚未购买"
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 _read_cache(drama_id: str) -> list[dict]:
path = CACHE_DIR / f"{drama_id}.json"
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:
CACHE_DIR.mkdir(parents=True, exist_ok=True)
path = CACHE_DIR / f"{drama_id}.json"
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/huangdou/play/segment?url=" + quote(url, safe="")
def _int(value) -> int:
try:
return int(float(str(value)))
except (TypeError, ValueError):
return 0
+26 -11
View File
@@ -166,20 +166,40 @@ def audio_rendition_uris(text: str) -> list[str]:
return found
def expand_variant(master_url: str) -> tuple[str, str, list[dict], str, list[dict]]:
master_text = http.read_text(master_url)
def is_direct_media(url: str) -> bool:
path = url.split("?", 1)[0].lower()
return path.endswith((".mp4", ".m4v", ".webm", ".mkv"))
def looks_like_segment(url: str) -> bool:
path = url.split("?", 1)[0].lower()
return path.endswith((".ts", ".m4s", ".m4v", ".mp4", ".aac", ".vtt"))
def is_media_playlist(text: str) -> bool:
first = next(
(line.strip() for line in text.splitlines() if line.strip() and not line.startswith("#")),
"",
)
return bool(first) and looks_like_segment(first)
def expand_variant(master_url: str, headers: dict | None = None) -> tuple[str, str, list[dict], str, list[dict]]:
if is_direct_media(master_url):
raise RuntimeError("这是整段视频,不是播放列表")
master_text = http.read_text(master_url, headers=headers)
variant_rel = next(
(line.strip() for line in master_text.splitlines() if line.strip() and not line.startswith("#")),
"",
)
if not variant_rel:
raise RuntimeError("播放列表没有视频地址")
if _looks_like_segment(variant_rel):
if looks_like_segment(variant_rel):
variant_url = master_url
media_text = master_text
else:
variant_url = urljoin(master_url, variant_rel)
media_text = http.read_text(variant_url)
media_text = http.read_text(variant_url, headers=headers)
localized, items = localize_media(media_text, variant_url)
if not items:
raise RuntimeError("播放列表没有分片")
@@ -187,7 +207,7 @@ def expand_variant(master_url: str) -> tuple[str, str, list[dict], str, list[dic
audio_items: list[dict] = []
for rel in audio_rendition_uris(master_text):
audio_url = urljoin(master_url, rel)
fetched = http.read_text(audio_url)
fetched = http.read_text(audio_url, headers=headers)
audio_text, audio_items = localize_media(fetched, audio_url, name_prefix="audio-")
if audio_items:
break
@@ -495,17 +515,12 @@ def playback_playlist(master_url: str) -> str:
)
if not variant_rel:
raise RuntimeError("播放列表没有视频地址")
if _looks_like_segment(variant_rel):
if looks_like_segment(variant_rel):
return _rewrite_playlist(master_text, master_url)
variant_url = urljoin(master_url, variant_rel)
return _rewrite_playlist(http.read_text(variant_url), variant_url)
def _looks_like_segment(url: str) -> bool:
path = url.split("?", 1)[0].lower()
return path.endswith((".ts", ".m4s", ".m4v", ".mp4", ".aac", ".vtt"))
def _proxy_url(url: str) -> str:
return "/api/play/segment?url=" + quote(url, safe="")