feat: 接入黄豆短剧独立清单与下载
This commit is contained in:
@@ -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.covers import router as covers_router
|
||||||
from server.routes.device import router as device_router
|
from server.routes.device import router as device_router
|
||||||
from server.routes.downloads import router as downloads_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.live import router as live_router
|
||||||
from server.routes.play import router as play_router
|
from server.routes.play import router as play_router
|
||||||
from server.routes.proxy import router as proxy_router
|
from server.routes.proxy import router as proxy_router
|
||||||
from server.routes.session import router as session_router
|
from server.routes.session import router as session_router
|
||||||
from server.services.downloads import downloads
|
from server.services.downloads import downloads
|
||||||
|
from server.services.huangdou.downloads import downloads as huangdou_downloads
|
||||||
|
|
||||||
|
|
||||||
def create_app() -> FastAPI:
|
def create_app() -> FastAPI:
|
||||||
@@ -36,10 +38,12 @@ def create_app() -> FastAPI:
|
|||||||
app.include_router(play_router)
|
app.include_router(play_router)
|
||||||
app.include_router(live_router)
|
app.include_router(live_router)
|
||||||
app.include_router(proxy_router)
|
app.include_router(proxy_router)
|
||||||
|
app.include_router(huangdou_router)
|
||||||
|
|
||||||
@app.on_event("startup")
|
@app.on_event("startup")
|
||||||
def start_downloads() -> None:
|
def start_downloads() -> None:
|
||||||
downloads.start()
|
downloads.start()
|
||||||
|
huangdou_downloads.start()
|
||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
def health():
|
def health():
|
||||||
|
|||||||
@@ -2,3 +2,4 @@ fastapi>=0.115
|
|||||||
uvicorn>=0.32
|
uvicorn>=0.32
|
||||||
websockets>=14
|
websockets>=14
|
||||||
httpx[socks]>=0.28
|
httpx[socks]>=0.28
|
||||||
|
cryptography>=44
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ router = APIRouter(prefix="/api/downloads")
|
|||||||
|
|
||||||
|
|
||||||
class DownloadItem(BaseModel):
|
class DownloadItem(BaseModel):
|
||||||
id: int
|
id: str | int
|
||||||
title: str = ""
|
title: str = ""
|
||||||
image: str = ""
|
image: str = ""
|
||||||
|
|
||||||
|
|||||||
@@ -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
@@ -3,13 +3,20 @@ import asyncio
|
|||||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||||
|
|
||||||
from server.services.downloads import downloads
|
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.live import live
|
||||||
from server.services.sessions import sessions
|
from server.services.sessions import sessions
|
||||||
|
|
||||||
router = APIRouter()
|
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()
|
profile = sessions.snapshot()
|
||||||
return {
|
return {
|
||||||
"downloads": downloads.snapshot(),
|
"downloads": downloads.snapshot(),
|
||||||
@@ -20,13 +27,14 @@ def _payload() -> dict:
|
|||||||
@router.websocket("/api/live")
|
@router.websocket("/api/live")
|
||||||
async def live_socket(websocket: WebSocket):
|
async def live_socket(websocket: WebSocket):
|
||||||
await websocket.accept()
|
await websocket.accept()
|
||||||
|
platform = (websocket.query_params.get("platform") or "rapt").strip() or "rapt"
|
||||||
seen = -1
|
seen = -1
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
revision = await asyncio.to_thread(live.wait, seen, 20)
|
revision = await asyncio.to_thread(live.wait, seen, 20)
|
||||||
if revision != seen:
|
if revision != seen:
|
||||||
seen = revision
|
seen = revision
|
||||||
await websocket.send_json(_payload())
|
await websocket.send_json(_payload(platform))
|
||||||
else:
|
else:
|
||||||
await websocket.send_json({"type": "ping"})
|
await websocket.send_json({"type": "ping"})
|
||||||
except WebSocketDisconnect:
|
except WebSocketDisconnect:
|
||||||
|
|||||||
+117
-23
@@ -60,10 +60,29 @@ def _default_directory() -> str:
|
|||||||
|
|
||||||
|
|
||||||
class DownloadManager:
|
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._lock = threading.Lock()
|
||||||
self._jobs: dict[str, dict] = {}
|
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._worker_limit = DEFAULT_WORKERS
|
||||||
self._alive_workers = 0
|
self._alive_workers = 0
|
||||||
self._wake = threading.Event()
|
self._wake = threading.Event()
|
||||||
@@ -124,7 +143,7 @@ class DownloadManager:
|
|||||||
return {
|
return {
|
||||||
"directory": self._directory,
|
"directory": self._directory,
|
||||||
"workers": self._worker_limit,
|
"workers": self._worker_limit,
|
||||||
"default_directory": _default_directory(),
|
"default_directory": self._default_directory,
|
||||||
}
|
}
|
||||||
|
|
||||||
def set_workers(self, count: int) -> int:
|
def set_workers(self, count: int) -> int:
|
||||||
@@ -320,7 +339,7 @@ class DownloadManager:
|
|||||||
os.startfile(folder) # noqa: S606
|
os.startfile(folder) # noqa: S606
|
||||||
|
|
||||||
def _enqueue_one(self, drama_id: str, title: str, image: str, token: str, device, directory: str) -> None:
|
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:
|
with self._lock:
|
||||||
job = self._jobs.get(drama_id)
|
job = self._jobs.get(drama_id)
|
||||||
if job is None:
|
if job is None:
|
||||||
@@ -337,6 +356,7 @@ class DownloadManager:
|
|||||||
"episodes": [],
|
"episodes": [],
|
||||||
"error": "",
|
"error": "",
|
||||||
"fraction": 0,
|
"fraction": 0,
|
||||||
|
"auth_token": token,
|
||||||
}
|
}
|
||||||
self._jobs[drama_id] = job
|
self._jobs[drama_id] = job
|
||||||
else:
|
else:
|
||||||
@@ -351,6 +371,8 @@ class DownloadManager:
|
|||||||
pass
|
pass
|
||||||
elif job["status"] not in ACTIVE:
|
elif job["status"] not in ACTIVE:
|
||||||
job["status"] = "queued"
|
job["status"] = "queued"
|
||||||
|
if token:
|
||||||
|
job["auth_token"] = token
|
||||||
self._apply_episodes_locked(job, episodes)
|
self._apply_episodes_locked(job, episodes)
|
||||||
if job["status"] == "paused":
|
if job["status"] == "paused":
|
||||||
job["command"] = "pause"
|
job["command"] = "pause"
|
||||||
@@ -367,6 +389,7 @@ class DownloadManager:
|
|||||||
if phase == "done" and not self._mp4_exists(job, ep):
|
if phase == "done" and not self._mp4_exists(job, ep):
|
||||||
phase = "pending" if ep.get("src") else "skipped"
|
phase = "pending" if ep.get("src") else "skipped"
|
||||||
merged.append({
|
merged.append({
|
||||||
|
**{key: value for key, value in ep.items() if key not in {"phase", "cid", "idx", "title", "src"}},
|
||||||
"cid": int(ep["cid"]),
|
"cid": int(ep["cid"]),
|
||||||
"idx": int(ep.get("idx") or 0),
|
"idx": int(ep.get("idx") or 0),
|
||||||
"title": ep.get("title") or "",
|
"title": ep.get("title") or "",
|
||||||
@@ -390,6 +413,9 @@ class DownloadManager:
|
|||||||
self._save_intro(folder, drama_id, title, token, device)
|
self._save_intro(folder, drama_id, title, token, device)
|
||||||
|
|
||||||
def _save_intro(self, folder: Path, drama_id: str, title: str, token: str, device) -> None:
|
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
|
vid = drama_id
|
||||||
name = title.strip()
|
name = title.strip()
|
||||||
desc = ""
|
desc = ""
|
||||||
@@ -422,6 +448,9 @@ class DownloadManager:
|
|||||||
if not digest:
|
if not digest:
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
|
if self._read_cover_fn is not None:
|
||||||
|
data, media = self._read_cover_fn(image)
|
||||||
|
else:
|
||||||
data, media = covers.read(digest)
|
data, media = covers.read(digest)
|
||||||
except Exception:
|
except Exception:
|
||||||
return
|
return
|
||||||
@@ -478,12 +507,11 @@ class DownloadManager:
|
|||||||
job = self._jobs.get(drama_id)
|
job = self._jobs.get(drama_id)
|
||||||
if job is None:
|
if job is None:
|
||||||
return
|
return
|
||||||
token = sessions.active_token()
|
token, device = self._auth_of(job)
|
||||||
device = sessions.device_for(token) if token else None
|
|
||||||
folder = Path(job["folder"])
|
folder = Path(job["folder"])
|
||||||
image = str(job.get("image") or "")
|
image = str(job.get("image") or "")
|
||||||
title = str(job.get("title") 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:
|
with self._lock:
|
||||||
job = self._jobs.get(drama_id)
|
job = self._jobs.get(drama_id)
|
||||||
if job is None:
|
if job is None:
|
||||||
@@ -575,17 +603,23 @@ class DownloadManager:
|
|||||||
|
|
||||||
def _write_playlist(self, drama_id: str, folder: Path, row: dict) -> None:
|
def _write_playlist(self, drama_id: str, folder: Path, row: dict) -> None:
|
||||||
source_dir, _mp4_path = self._episode_paths(folder, row)
|
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)
|
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")
|
(source_dir / "video.m3u8").write_text(media_text, encoding="utf-8", newline="\n")
|
||||||
if audio_text and audio_items:
|
if audio_text and audio_items:
|
||||||
(source_dir / "audio.m3u8").write_text(audio_text, encoding="utf-8", newline="\n")
|
(source_dir / "audio.m3u8").write_text(audio_text, encoding="utf-8", newline="\n")
|
||||||
master_text = _point_audio_at_local(master_text)
|
master_text = _point_audio_at_local(master_text)
|
||||||
(source_dir / "playlist.m3u8").write_text(
|
(source_dir / "playlist.m3u8").write_text(_local_master(master_text), encoding="utf-8", newline="\n")
|
||||||
_localize(master_text, ["video.m3u8"]),
|
|
||||||
encoding="utf-8",
|
|
||||||
newline="\n",
|
|
||||||
)
|
|
||||||
saved_items = list(items) + list(audio_items)
|
saved_items = list(items) + list(audio_items)
|
||||||
(source_dir / "segments.json").write_text(json.dumps(saved_items, ensure_ascii=False), encoding="utf-8")
|
(source_dir / "segments.json").write_text(json.dumps(saved_items, ensure_ascii=False), encoding="utf-8")
|
||||||
if row.get("src"):
|
if row.get("src"):
|
||||||
@@ -623,6 +657,9 @@ class DownloadManager:
|
|||||||
self._set_segments(drama_id, row["cid"], len(items), len(items))
|
self._set_segments(drama_id, row["cid"], len(items), len(items))
|
||||||
self._set_phase(drama_id, row["cid"], "done")
|
self._set_phase(drama_id, row["cid"], "done")
|
||||||
return
|
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._set_phase(drama_id, row["cid"], "downloading")
|
||||||
self._write_playlist(drama_id, folder, row)
|
self._write_playlist(drama_id, folder, row)
|
||||||
items = json.loads(manifest.read_text(encoding="utf-8"))
|
items = json.loads(manifest.read_text(encoding="utf-8"))
|
||||||
@@ -632,12 +669,20 @@ class DownloadManager:
|
|||||||
raise RuntimeError("已停止")
|
raise RuntimeError("已停止")
|
||||||
target = source_dir / item["name"]
|
target = source_dir / item["name"]
|
||||||
if not target.is_file() or target.stat().st_size <= 0:
|
if not target.is_file() or target.stat().st_size <= 0:
|
||||||
|
try:
|
||||||
http.download_file(
|
http.download_file(
|
||||||
item["url"],
|
item["url"],
|
||||||
target,
|
target,
|
||||||
on_chunk=lambda size, job_id=drama_id: self._note_bytes(job_id, size),
|
on_chunk=lambda size, job_id=drama_id: self._note_bytes(job_id, size),
|
||||||
stop=lambda job_id=drama_id: self._stopped(job_id),
|
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)
|
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)
|
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)
|
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_phase(drama_id, row["cid"], "done")
|
||||||
self._set_segments(drama_id, row["cid"], total, total)
|
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:
|
def _set_phase(self, drama_id: str, cid: int, phase: str) -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
job = self._jobs.get(drama_id)
|
job = self._jobs.get(drama_id)
|
||||||
@@ -708,11 +780,27 @@ class DownloadManager:
|
|||||||
"error": job.get("error") or "",
|
"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:
|
def _load(self) -> None:
|
||||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
self._state_dir.mkdir(parents=True, exist_ok=True)
|
||||||
if SETTINGS_PATH.is_file():
|
if self._settings_path.is_file():
|
||||||
try:
|
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"):
|
if isinstance(data, dict) and data.get("directory"):
|
||||||
self._directory = data["directory"]
|
self._directory = data["directory"]
|
||||||
workers = data.get("workers") if isinstance(data, dict) else None
|
workers = data.get("workers") if isinstance(data, dict) else None
|
||||||
@@ -720,10 +808,10 @@ class DownloadManager:
|
|||||||
self._worker_limit = workers
|
self._worker_limit = workers
|
||||||
except (OSError, json.JSONDecodeError):
|
except (OSError, json.JSONDecodeError):
|
||||||
pass
|
pass
|
||||||
if not STATE_PATH.is_file():
|
if not self._state_path.is_file():
|
||||||
return
|
return
|
||||||
try:
|
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):
|
except (OSError, json.JSONDecodeError):
|
||||||
return
|
return
|
||||||
jobs = data.get("jobs") if isinstance(data, dict) else None
|
jobs = data.get("jobs") if isinstance(data, dict) else None
|
||||||
@@ -733,19 +821,19 @@ class DownloadManager:
|
|||||||
self._jobs[str(job["id"])] = job
|
self._jobs[str(job["id"])] = job
|
||||||
|
|
||||||
def _save_locked(self) -> None:
|
def _save_locked(self) -> None:
|
||||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
self._state_dir.mkdir(parents=True, exist_ok=True)
|
||||||
stored = []
|
stored = []
|
||||||
for job in self._jobs.values():
|
for job in self._jobs.values():
|
||||||
stored.append({key: value for key, value in job.items() if key != "fraction"})
|
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.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()
|
self._save_settings_locked()
|
||||||
live.touch()
|
live.touch()
|
||||||
|
|
||||||
def _save_settings_locked(self) -> None:
|
def _save_settings_locked(self) -> None:
|
||||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
self._state_dir.mkdir(parents=True, exist_ok=True)
|
||||||
SETTINGS_PATH.write_text(
|
self._settings_path.write_text(
|
||||||
json.dumps({"directory": self._directory, "workers": self._worker_limit}, ensure_ascii=False),
|
json.dumps({"directory": self._directory, "workers": self._worker_limit}, ensure_ascii=False),
|
||||||
encoding="utf-8",
|
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")
|
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:
|
def _point_audio_at_local(text: str) -> str:
|
||||||
lines = []
|
lines = []
|
||||||
for line in text.splitlines():
|
for line in text.splitlines():
|
||||||
|
|||||||
+28
-8
@@ -88,15 +88,26 @@ class HttpClient:
|
|||||||
self._client = httpx.Client(**self._client_kwargs())
|
self._client = httpx.Client(**self._client_kwargs())
|
||||||
return self._client
|
return self._client
|
||||||
|
|
||||||
def get_bytes(self, url: str) -> tuple[bytes, str]:
|
def send(self, method: str, url: str, *, headers: dict | None = None, content: bytes | None = None, timeout=None) -> httpx.Response:
|
||||||
response = self._client_locked().get(url, headers={"User-Agent": "RaptDrama"})
|
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()
|
response.raise_for_status()
|
||||||
media = response.headers.get("content-type", "image/jpeg").split(";", 1)[0].strip() or "image/jpeg"
|
media = response.headers.get("content-type", "image/jpeg").split(";", 1)[0].strip() or "image/jpeg"
|
||||||
if not media.startswith("image/"):
|
if not media.startswith("image/"):
|
||||||
raise RuntimeError("不是图片")
|
raise RuntimeError("不是图片")
|
||||||
return response.content, media
|
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
|
from pathlib import Path
|
||||||
|
|
||||||
target = Path(dest)
|
target = Path(dest)
|
||||||
@@ -107,7 +118,10 @@ class HttpClient:
|
|||||||
if stop and stop():
|
if stop and stop():
|
||||||
raise RuntimeError("已取消")
|
raise RuntimeError("已取消")
|
||||||
try:
|
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()
|
response.raise_for_status()
|
||||||
size = 0
|
size = 0
|
||||||
with temporary.open("wb") as handle:
|
with temporary.open("wb") as handle:
|
||||||
@@ -131,11 +145,14 @@ class HttpClient:
|
|||||||
time.sleep(0.4)
|
time.sleep(0.4)
|
||||||
raise RuntimeError(f"下载失败: {last_error}")
|
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
|
last_error = None
|
||||||
|
hdrs = {"User-Agent": "RaptDrama"}
|
||||||
|
if headers:
|
||||||
|
hdrs.update(headers)
|
||||||
for _attempt in range(3):
|
for _attempt in range(3):
|
||||||
try:
|
try:
|
||||||
response = self._client_locked().get(url, headers={"User-Agent": "RaptDrama"})
|
response = self._client_locked().get(url, headers=hdrs)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
return response.text
|
return response.text
|
||||||
except (httpx.HTTPError, TimeoutError, OSError) as exc:
|
except (httpx.HTTPError, TimeoutError, OSError) as exc:
|
||||||
@@ -143,9 +160,12 @@ class HttpClient:
|
|||||||
time.sleep(0.4)
|
time.sleep(0.4)
|
||||||
raise RuntimeError(f"下载失败: {last_error}")
|
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()
|
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)
|
response = client.send(request, stream=True)
|
||||||
try:
|
try:
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""黄豆短剧平台。会话、清单和下载与 RaptDrama 隔离。"""
|
||||||
@@ -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",
|
||||||
|
]
|
||||||
@@ -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)
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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)
|
||||||
@@ -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/"},
|
||||||
|
)
|
||||||
@@ -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
|
||||||
@@ -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
@@ -166,20 +166,40 @@ def audio_rendition_uris(text: str) -> list[str]:
|
|||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
def expand_variant(master_url: str) -> tuple[str, str, list[dict], str, list[dict]]:
|
def is_direct_media(url: str) -> bool:
|
||||||
master_text = http.read_text(master_url)
|
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(
|
variant_rel = next(
|
||||||
(line.strip() for line in master_text.splitlines() if line.strip() and not line.startswith("#")),
|
(line.strip() for line in master_text.splitlines() if line.strip() and not line.startswith("#")),
|
||||||
"",
|
"",
|
||||||
)
|
)
|
||||||
if not variant_rel:
|
if not variant_rel:
|
||||||
raise RuntimeError("播放列表没有视频地址")
|
raise RuntimeError("播放列表没有视频地址")
|
||||||
if _looks_like_segment(variant_rel):
|
if looks_like_segment(variant_rel):
|
||||||
variant_url = master_url
|
variant_url = master_url
|
||||||
media_text = master_text
|
media_text = master_text
|
||||||
else:
|
else:
|
||||||
variant_url = urljoin(master_url, variant_rel)
|
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)
|
localized, items = localize_media(media_text, variant_url)
|
||||||
if not items:
|
if not items:
|
||||||
raise RuntimeError("播放列表没有分片")
|
raise RuntimeError("播放列表没有分片")
|
||||||
@@ -187,7 +207,7 @@ def expand_variant(master_url: str) -> tuple[str, str, list[dict], str, list[dic
|
|||||||
audio_items: list[dict] = []
|
audio_items: list[dict] = []
|
||||||
for rel in audio_rendition_uris(master_text):
|
for rel in audio_rendition_uris(master_text):
|
||||||
audio_url = urljoin(master_url, rel)
|
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-")
|
audio_text, audio_items = localize_media(fetched, audio_url, name_prefix="audio-")
|
||||||
if audio_items:
|
if audio_items:
|
||||||
break
|
break
|
||||||
@@ -495,17 +515,12 @@ def playback_playlist(master_url: str) -> str:
|
|||||||
)
|
)
|
||||||
if not variant_rel:
|
if not variant_rel:
|
||||||
raise RuntimeError("播放列表没有视频地址")
|
raise RuntimeError("播放列表没有视频地址")
|
||||||
if _looks_like_segment(variant_rel):
|
if looks_like_segment(variant_rel):
|
||||||
return _rewrite_playlist(master_text, master_url)
|
return _rewrite_playlist(master_text, master_url)
|
||||||
variant_url = urljoin(master_url, variant_rel)
|
variant_url = urljoin(master_url, variant_rel)
|
||||||
return _rewrite_playlist(http.read_text(variant_url), variant_url)
|
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:
|
def _proxy_url(url: str) -> str:
|
||||||
return "/api/play/segment?url=" + quote(url, safe="")
|
return "/api/play/segment?url=" + quote(url, safe="")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if str(ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from server.services.huangdou.crypto import (
|
||||||
|
WEB_AES_KEY,
|
||||||
|
decrypt_body,
|
||||||
|
decrypt_resource,
|
||||||
|
derive_aes_key,
|
||||||
|
encrypt_body,
|
||||||
|
sign_header,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_roundtrip_and_sign() -> None:
|
||||||
|
request_id = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
|
||||||
|
payload = {
|
||||||
|
"token": "",
|
||||||
|
"deviceId": "11111111-2222-4333-8444-555555555555",
|
||||||
|
"data": {"line_code": "china_1", "force_new": ""},
|
||||||
|
}
|
||||||
|
blob = encrypt_body(payload, request_id)
|
||||||
|
assert len(blob) > 16
|
||||||
|
parsed = decrypt_body(blob, request_id)
|
||||||
|
assert parsed == payload
|
||||||
|
|
||||||
|
key = derive_aes_key(request_id)
|
||||||
|
expected = hmac.new(
|
||||||
|
WEB_AES_KEY.encode("utf-8"),
|
||||||
|
bytes.fromhex(request_id.replace("-", "")),
|
||||||
|
hashlib.sha256,
|
||||||
|
).digest()
|
||||||
|
assert key == expected
|
||||||
|
|
||||||
|
sign = sign_header(
|
||||||
|
"abcdeffedcbaabcdeffedcbaabcdeffe",
|
||||||
|
request_id,
|
||||||
|
"1710000000",
|
||||||
|
"https://pmihlvee.cc/api/login/device",
|
||||||
|
)
|
||||||
|
digest, stamp = sign.split("-", 1)
|
||||||
|
assert stamp == "1710000000"
|
||||||
|
assert len(digest) == 32
|
||||||
|
raw = "Dart|abcdeffedcbaabcdeffedcbaabcdeffe|aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee|1710000000|pmihlvee.cc/api/login/device"
|
||||||
|
assert digest == hashlib.md5(raw.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
jpeg = b"\xff\xd8\xff" + b"\x00" * 32
|
||||||
|
assert decrypt_resource(jpeg) == jpeg
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_roundtrip_and_sign()
|
||||||
|
print("ok")
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
from server.services.downloads import _local_master
|
||||||
|
from server.services.huangdou.playlist import _choose_src
|
||||||
|
from server.services.playlist import expand_variant, is_direct_media, is_media_playlist
|
||||||
|
|
||||||
|
|
||||||
|
def test_direct_media_and_hls_choice() -> None:
|
||||||
|
assert is_direct_media("https://cdn.example/chapters/2/preview-r10.mp4?auth=1")
|
||||||
|
assert not is_direct_media("https://host.example/api/drama/hls/id/1/play.m3u8?line=free")
|
||||||
|
|
||||||
|
media = "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"enc.key\"\n#EXTINF:1,\nseg_000.ts\n"
|
||||||
|
assert is_media_playlist(media)
|
||||||
|
master = _local_master(media)
|
||||||
|
assert "video.m3u8" in master
|
||||||
|
assert "seg_000.ts" not in master
|
||||||
|
|
||||||
|
src, kind = _choose_src({
|
||||||
|
"m3u8": "https://host.example/play.m3u8?x=1",
|
||||||
|
"preview_m3u8": "https://cdn.example/preview-r10.mp4",
|
||||||
|
"lines": [],
|
||||||
|
})
|
||||||
|
assert kind == "hls"
|
||||||
|
assert src.endswith("play.m3u8?x=1")
|
||||||
|
|
||||||
|
src, kind = _choose_src({
|
||||||
|
"m3u8": "",
|
||||||
|
"preview_m3u8": "https://cdn.example/chapters/2/preview-r10.mp4",
|
||||||
|
"lines": [],
|
||||||
|
})
|
||||||
|
assert kind == "file"
|
||||||
|
assert src.endswith(".mp4")
|
||||||
|
|
||||||
|
try:
|
||||||
|
expand_variant("https://cdn.example/preview-r10.mp4")
|
||||||
|
except RuntimeError as exc:
|
||||||
|
assert "整段视频" in str(exc)
|
||||||
|
else:
|
||||||
|
raise AssertionError("mp4 不应走播放列表")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_direct_media_and_hls_choice()
|
||||||
|
print("ok")
|
||||||
+147
-41
@@ -7,6 +7,7 @@ import SettingsPanel from "./views/SettingsPanel.vue";
|
|||||||
import PlayerPage from "./views/PlayerPage.vue";
|
import PlayerPage from "./views/PlayerPage.vue";
|
||||||
|
|
||||||
type Method = "guest" | "password" | "adb";
|
type Method = "guest" | "password" | "adb";
|
||||||
|
type Platform = "rapt" | "huangdou";
|
||||||
|
|
||||||
interface Profile {
|
interface Profile {
|
||||||
nickname?: string;
|
nickname?: string;
|
||||||
@@ -23,6 +24,12 @@ interface Profile {
|
|||||||
google_bind?: number;
|
google_bind?: number;
|
||||||
apple_bind?: number;
|
apple_bind?: number;
|
||||||
avatarNumUrl?: string;
|
avatarNumUrl?: string;
|
||||||
|
username?: string;
|
||||||
|
phone?: string;
|
||||||
|
group_name?: string;
|
||||||
|
balance?: string | number;
|
||||||
|
is_vip?: string | number;
|
||||||
|
has_login?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Device {
|
interface Device {
|
||||||
@@ -67,6 +74,7 @@ function emptyProxy(): ProxySettings {
|
|||||||
const DEVICE_KEY = "rapt-device-settings";
|
const DEVICE_KEY = "rapt-device-settings";
|
||||||
const SESSION_DEVICE_KEY = "rapt-device";
|
const SESSION_DEVICE_KEY = "rapt-device";
|
||||||
const ACCOUNTS_KEY = "rapt-accounts";
|
const ACCOUNTS_KEY = "rapt-accounts";
|
||||||
|
const PLATFORM_KEY = "rapt-platform";
|
||||||
|
|
||||||
const themeOverrides: GlobalThemeOverrides = {
|
const themeOverrides: GlobalThemeOverrides = {
|
||||||
Form: {
|
Form: {
|
||||||
@@ -74,6 +82,13 @@ const themeOverrides: GlobalThemeOverrides = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const platforms: { key: Platform; label: string }[] = [
|
||||||
|
{ key: "rapt", label: "RaptDrama" },
|
||||||
|
{ key: "huangdou", label: "黄豆短剧" },
|
||||||
|
];
|
||||||
|
const platform = ref<Platform>(readPlatform());
|
||||||
|
const apiBase = computed(() => (platform.value === "huangdou" ? "/api/huangdou" : "/api"));
|
||||||
|
const platformLabel = computed(() => platforms.find((item) => item.key === platform.value)?.label || "RaptDrama");
|
||||||
const method = ref<Method>("guest");
|
const method = ref<Method>("guest");
|
||||||
const email = ref("");
|
const email = ref("");
|
||||||
const password = ref("");
|
const password = ref("");
|
||||||
@@ -85,7 +100,7 @@ const error = ref("");
|
|||||||
const token = ref("");
|
const token = ref("");
|
||||||
const profile = ref<Profile | null>(null);
|
const profile = ref<Profile | null>(null);
|
||||||
const page = ref<"download" | "profile" | "progress" | "settings" | "play">("download");
|
const page = ref<"download" | "profile" | "progress" | "settings" | "play">("download");
|
||||||
const playing = ref<{ id: number; title: string; image: string } | null>(null);
|
const playing = ref<{ id: string | number; title: string; image: string } | null>(null);
|
||||||
const progressCount = ref(0);
|
const progressCount = ref(0);
|
||||||
interface LiveJob {
|
interface LiveJob {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -141,7 +156,28 @@ const menuValue = computed(() => {
|
|||||||
return page.value;
|
return page.value;
|
||||||
});
|
});
|
||||||
|
|
||||||
function openPlay(drama: { id: number; title: string; image: string }) {
|
function readPlatform(): Platform {
|
||||||
|
try {
|
||||||
|
const value = localStorage.getItem(PLATFORM_KEY);
|
||||||
|
if (value === "huangdou" || value === "rapt") return value;
|
||||||
|
} catch {
|
||||||
|
// 沿用默认平台
|
||||||
|
}
|
||||||
|
return "rapt";
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectPlatform(key: string) {
|
||||||
|
if (key !== "rapt" && key !== "huangdou") return;
|
||||||
|
platform.value = key;
|
||||||
|
localStorage.setItem(PLATFORM_KEY, key);
|
||||||
|
error.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenKey() {
|
||||||
|
return platform.value === "huangdou" ? "huangdou-token" : "rapt-token";
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPlay(drama: { id: string | number; title: string; image: string }) {
|
||||||
playing.value = drama;
|
playing.value = drama;
|
||||||
page.value = "play";
|
page.value = "play";
|
||||||
}
|
}
|
||||||
@@ -189,18 +225,36 @@ const methods: { id: Method; label: string }[] = [
|
|||||||
{ id: "adb", label: "ADB" },
|
{ id: "adb", label: "ADB" },
|
||||||
];
|
];
|
||||||
|
|
||||||
const accountFields: { key: keyof Profile; label: string }[] = [
|
const accountFields = computed(() =>
|
||||||
{ key: "email", label: "邮箱" },
|
platform.value === "huangdou"
|
||||||
{ key: "id", label: "用户 ID" },
|
? [
|
||||||
];
|
{ key: "username" as const, label: "账号" },
|
||||||
|
{ key: "id" as const, label: "用户 ID" },
|
||||||
|
{ key: "group_name" as const, label: "身份" },
|
||||||
|
{ key: "email" as const, label: "邮箱" },
|
||||||
|
{ key: "phone" as const, label: "手机" },
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{ key: "email" as const, label: "邮箱" },
|
||||||
|
{ key: "id" as const, label: "用户 ID" },
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
const statFields: { key: keyof Profile; label: string }[] = [
|
const statFields = computed(() =>
|
||||||
{ key: "vipday", label: "VIP" },
|
platform.value === "huangdou"
|
||||||
{ key: "score", label: "积分" },
|
? [
|
||||||
{ key: "watched", label: "观看" },
|
{ key: "vipday" as const, label: "VIP" },
|
||||||
{ key: "rewards", label: "奖励" },
|
{ key: "score" as const, label: "余额" },
|
||||||
{ key: "login_day", label: "登录" },
|
{ key: "watched" as const, label: "观看" },
|
||||||
];
|
]
|
||||||
|
: [
|
||||||
|
{ key: "vipday" as const, label: "VIP" },
|
||||||
|
{ key: "score" as const, label: "积分" },
|
||||||
|
{ key: "watched" as const, label: "观看" },
|
||||||
|
{ key: "rewards" as const, label: "奖励" },
|
||||||
|
{ key: "login_day" as const, label: "登录" },
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
const bindFields: { key: keyof Profile; label: string }[] = [
|
const bindFields: { key: keyof Profile; label: string }[] = [
|
||||||
{ key: "email_bind", label: "邮箱" },
|
{ key: "email_bind", label: "邮箱" },
|
||||||
@@ -246,7 +300,7 @@ function normalizeWorkers(value: unknown) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadDownloadSettings() {
|
async function loadDownloadSettings() {
|
||||||
const response = await fetch("/api/downloads/settings");
|
const response = await fetch(`${apiBase.value}/downloads/settings`);
|
||||||
if (!response.ok) return;
|
if (!response.ok) return;
|
||||||
const payload = await response.json();
|
const payload = await response.json();
|
||||||
settings.value.workers = normalizeWorkers(payload.workers);
|
settings.value.workers = normalizeWorkers(payload.workers);
|
||||||
@@ -256,12 +310,13 @@ async function loadDownloadSettings() {
|
|||||||
|
|
||||||
async function enterSettings() {
|
async function enterSettings() {
|
||||||
settingsError.value = "";
|
settingsError.value = "";
|
||||||
|
if (platform.value === "huangdou" && settingsTab.value === "device") settingsTab.value = "download";
|
||||||
await loadDownloadSettings();
|
await loadDownloadSettings();
|
||||||
draft.value = copySettings(settings.value);
|
draft.value = copySettings(settings.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openSettings() {
|
async function openSettings() {
|
||||||
settingsTab.value = "device";
|
settingsTab.value = platform.value === "huangdou" ? "download" : "device";
|
||||||
await enterSettings();
|
await enterSettings();
|
||||||
settingsOpen.value = true;
|
settingsOpen.value = true;
|
||||||
}
|
}
|
||||||
@@ -314,7 +369,7 @@ async function saveSettings() {
|
|||||||
settingsBusy.value = true;
|
settingsBusy.value = true;
|
||||||
try {
|
try {
|
||||||
await applyProxy(proxy);
|
await applyProxy(proxy);
|
||||||
const response = await fetch("/api/downloads/settings", {
|
const response = await fetch(`${apiBase.value}/downloads/settings`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ directory, workers }),
|
body: JSON.stringify({ directory, workers }),
|
||||||
@@ -345,7 +400,7 @@ async function saveSettings() {
|
|||||||
|
|
||||||
async function chooseDownloadDirectory() {
|
async function chooseDownloadDirectory() {
|
||||||
settingsError.value = "";
|
settingsError.value = "";
|
||||||
const response = await fetch("/api/downloads/choose", { method: "POST" });
|
const response = await fetch(`${apiBase.value}/downloads/choose`, { method: "POST" });
|
||||||
const payload = await response.json().catch(() => ({}));
|
const payload = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
settingsError.value = typeof payload.detail === "string" ? payload.detail : "目录选择失败";
|
settingsError.value = typeof payload.detail === "string" ? payload.detail : "目录选择失败";
|
||||||
@@ -526,7 +581,32 @@ watch(method, (value) => {
|
|||||||
if (value === "adb") loadDevices();
|
if (value === "adb") loadDevices();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
async function loginHuangdou() {
|
||||||
|
error.value = "";
|
||||||
|
busy.value = true;
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/huangdou/login/device", { method: "POST" });
|
||||||
|
const payload = await response.json();
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(typeof payload.detail === "string" ? payload.detail : "登录失败");
|
||||||
|
}
|
||||||
|
token.value = payload.token;
|
||||||
|
profile.value = payload.profile;
|
||||||
|
sessionStorage.setItem(tokenKey(), payload.token);
|
||||||
|
page.value = "download";
|
||||||
|
startLive();
|
||||||
|
} catch (exc) {
|
||||||
|
error.value = exc instanceof Error ? exc.message : "登录失败";
|
||||||
|
} finally {
|
||||||
|
busy.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function login() {
|
async function login() {
|
||||||
|
if (platform.value === "huangdou") {
|
||||||
|
await loginHuangdou();
|
||||||
|
return;
|
||||||
|
}
|
||||||
error.value = "";
|
error.value = "";
|
||||||
busy.value = true;
|
busy.value = true;
|
||||||
try {
|
try {
|
||||||
@@ -561,7 +641,7 @@ async function login() {
|
|||||||
}
|
}
|
||||||
token.value = payload.token;
|
token.value = payload.token;
|
||||||
profile.value = payload.profile;
|
profile.value = payload.profile;
|
||||||
sessionStorage.setItem("rapt-token", payload.token);
|
sessionStorage.setItem(tokenKey(), payload.token);
|
||||||
rememberSessionDevice(payload.device);
|
rememberSessionDevice(payload.device);
|
||||||
page.value = "download";
|
page.value = "download";
|
||||||
startLive();
|
startLive();
|
||||||
@@ -576,7 +656,7 @@ async function login() {
|
|||||||
const avatarSrc = computed(() => {
|
const avatarSrc = computed(() => {
|
||||||
const image = profile.value?.avatarNumUrl || "";
|
const image = profile.value?.avatarNumUrl || "";
|
||||||
if (!image) return undefined;
|
if (!image) return undefined;
|
||||||
if (image.startsWith("http://") || image.startsWith("https://")) return image;
|
if (image.startsWith("http://") || image.startsWith("https://") || image.startsWith("/api/")) return image;
|
||||||
return `https://apis.raptdrama.com${image.startsWith("/") ? image : `/${image}`}`;
|
return `https://apis.raptdrama.com${image.startsWith("/") ? image : `/${image}`}`;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -597,7 +677,7 @@ function applyLive(payload: { downloads?: { active: LiveJob[]; done: LiveJob[];
|
|||||||
function startLive() {
|
function startLive() {
|
||||||
stopLive();
|
stopLive();
|
||||||
const protocol = location.protocol === "https:" ? "wss" : "ws";
|
const protocol = location.protocol === "https:" ? "wss" : "ws";
|
||||||
const socket = new WebSocket(`${protocol}://${location.host}/api/live`);
|
const socket = new WebSocket(`${protocol}://${location.host}/api/live?platform=${platform.value}`);
|
||||||
liveSocket = socket;
|
liveSocket = socket;
|
||||||
socket.onmessage = (event) => {
|
socket.onmessage = (event) => {
|
||||||
applyLive(JSON.parse(event.data));
|
applyLive(JSON.parse(event.data));
|
||||||
@@ -625,11 +705,11 @@ async function logout() {
|
|||||||
token.value = "";
|
token.value = "";
|
||||||
profile.value = null;
|
profile.value = null;
|
||||||
page.value = "download";
|
page.value = "download";
|
||||||
sessionStorage.removeItem("rapt-token");
|
sessionStorage.removeItem(tokenKey());
|
||||||
sessionStorage.removeItem(SESSION_DEVICE_KEY);
|
sessionStorage.removeItem(SESSION_DEVICE_KEY);
|
||||||
if (!current) return;
|
if (!current) return;
|
||||||
try {
|
try {
|
||||||
await fetch("/api/logout", {
|
await fetch(platform.value === "huangdou" ? "/api/huangdou/logout" : "/api/logout", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ token: current }),
|
body: JSON.stringify({ token: current }),
|
||||||
@@ -659,9 +739,11 @@ async function watchClose() {
|
|||||||
|
|
||||||
async function askClose(win: ReturnType<typeof getCurrentWindow>) {
|
async function askClose(win: ReturnType<typeof getCurrentWindow>) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/downloads");
|
const [rapt, huangdou] = await Promise.all([
|
||||||
const payload = await response.json();
|
fetch("/api/downloads").then((item) => item.json()).catch(() => ({})),
|
||||||
const count = Number(payload.active_count || 0);
|
fetch("/api/huangdou/downloads").then((item) => item.json()).catch(() => ({})),
|
||||||
|
]);
|
||||||
|
const count = Number(rapt.active_count || 0) + Number(huangdou.active_count || 0);
|
||||||
if (count > 0) {
|
if (count > 0) {
|
||||||
closeCount.value = count;
|
closeCount.value = count;
|
||||||
closeAsk.value = true;
|
closeAsk.value = true;
|
||||||
@@ -693,15 +775,15 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
savedAccounts.value = readList<SavedAccount>(ACCOUNTS_KEY);
|
savedAccounts.value = readList<SavedAccount>(ACCOUNTS_KEY);
|
||||||
if (savedAccounts.value[0]) applyAccount(savedAccounts.value[0].email);
|
if (savedAccounts.value[0]) applyAccount(savedAccounts.value[0].email);
|
||||||
const saved = sessionStorage.getItem("rapt-token");
|
const saved = sessionStorage.getItem(tokenKey());
|
||||||
if (!saved) return;
|
if (!saved) return;
|
||||||
const response = await fetch("/api/me", {
|
const response = await fetch(platform.value === "huangdou" ? "/api/huangdou/me" : "/api/me", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ token: saved, device: sessionDevice() }),
|
body: JSON.stringify({ token: saved, device: sessionDevice() }),
|
||||||
});
|
});
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
sessionStorage.removeItem("rapt-token");
|
sessionStorage.removeItem(tokenKey());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const payload = await response.json();
|
const payload = await response.json();
|
||||||
@@ -720,6 +802,7 @@ onUnmounted(stopLive);
|
|||||||
<n-layout v-if="profile" class="shell" has-sider position="absolute">
|
<n-layout v-if="profile" class="shell" has-sider position="absolute">
|
||||||
<n-layout-sider bordered :width="208" content-style="height: 100%; padding: 0">
|
<n-layout-sider bordered :width="208" content-style="height: 100%; padding: 0">
|
||||||
<div class="sider">
|
<div class="sider">
|
||||||
|
<div class="platform-mark">{{ platformLabel }}</div>
|
||||||
<n-menu
|
<n-menu
|
||||||
:value="menuValue"
|
:value="menuValue"
|
||||||
:options="mainMenu"
|
:options="mainMenu"
|
||||||
@@ -778,6 +861,8 @@ onUnmounted(stopLive);
|
|||||||
ref="downloadRef"
|
ref="downloadRef"
|
||||||
:token="token"
|
:token="token"
|
||||||
:device="sessionDevice()"
|
:device="sessionDevice()"
|
||||||
|
:api-base="apiBase"
|
||||||
|
:remote-search="platform === 'huangdou'"
|
||||||
@started="page = 'progress'"
|
@started="page = 'progress'"
|
||||||
@play="openPlay"
|
@play="openPlay"
|
||||||
/>
|
/>
|
||||||
@@ -786,11 +871,12 @@ onUnmounted(stopLive);
|
|||||||
:token="token"
|
:token="token"
|
||||||
:device="sessionDevice()"
|
:device="sessionDevice()"
|
||||||
:drama-id="playing.id"
|
:drama-id="playing.id"
|
||||||
|
:api-base="apiBase"
|
||||||
/>
|
/>
|
||||||
<DownloadProgressPage v-show="page === 'progress'" :active="downloadState.active" :done="downloadState.done" />
|
<DownloadProgressPage v-show="page === 'progress'" :api-base="apiBase" :active="downloadState.active" :done="downloadState.done" />
|
||||||
<div v-show="page === 'settings'" class="settings-page">
|
<div v-show="page === 'settings'" class="settings-page">
|
||||||
<n-alert v-if="settingsError" class="hint" type="error" :show-icon="false">{{ settingsError }}</n-alert>
|
<n-alert v-if="settingsError" class="hint" type="error" :show-icon="false">{{ settingsError }}</n-alert>
|
||||||
<SettingsPanel v-model:tab="settingsTab" :draft="draft" @choose="chooseDownloadDirectory" />
|
<SettingsPanel v-model:tab="settingsTab" :draft="draft" :hide-device="platform === 'huangdou'" @choose="chooseDownloadDirectory" />
|
||||||
</div>
|
</div>
|
||||||
<div v-show="page === 'profile'" class="profile-page">
|
<div v-show="page === 'profile'" class="profile-page">
|
||||||
<div class="profile-sheet">
|
<div class="profile-sheet">
|
||||||
@@ -818,7 +904,7 @@ onUnmounted(stopLive);
|
|||||||
退出
|
退出
|
||||||
</n-tooltip>
|
</n-tooltip>
|
||||||
</div>
|
</div>
|
||||||
<div class="profile-stats">
|
<div class="profile-stats" :style="{ gridTemplateColumns: `repeat(${statFields.length}, minmax(0, 1fr))` }">
|
||||||
<div v-for="item in statFields" :key="item.key" class="profile-stat">
|
<div v-for="item in statFields" :key="item.key" class="profile-stat">
|
||||||
<span class="profile-stat-value">{{ profileNumber(item.key) }}</span>
|
<span class="profile-stat-value">{{ profileNumber(item.key) }}</span>
|
||||||
<span class="profile-stat-label">{{ item.label }}</span>
|
<span class="profile-stat-label">{{ item.label }}</span>
|
||||||
@@ -831,7 +917,7 @@ onUnmounted(stopLive);
|
|||||||
<span class="profile-row-value">{{ profileText(item.key) }}</span>
|
<span class="profile-row-value">{{ profileText(item.key) }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="profile-block">
|
<div v-if="platform === 'rapt'" class="profile-block">
|
||||||
<div class="profile-block-title">绑定</div>
|
<div class="profile-block-title">绑定</div>
|
||||||
<div class="profile-binds">
|
<div class="profile-binds">
|
||||||
<span v-for="item in bindFields" :key="item.key" class="profile-bind" :class="{ on: profileBound(item.key) }">{{ item.label }}</span>
|
<span v-for="item in bindFields" :key="item.key" class="profile-bind" :class="{ on: profileBound(item.key) }">{{ item.label }}</span>
|
||||||
@@ -842,15 +928,27 @@ onUnmounted(stopLive);
|
|||||||
</n-layout-content>
|
</n-layout-content>
|
||||||
</n-layout>
|
</n-layout>
|
||||||
</n-layout>
|
</n-layout>
|
||||||
<n-layout v-else class="shell login-shell" position="absolute">
|
<n-layout v-else class="shell login-shell" has-sider position="absolute">
|
||||||
|
<n-layout-sider bordered :width="208" content-style="height: 100%; padding: 0">
|
||||||
|
<div class="sider">
|
||||||
|
<n-menu
|
||||||
|
:value="platform"
|
||||||
|
:options="platforms.map((item) => ({ label: item.label, key: item.key }))"
|
||||||
|
@update:value="selectPlatform"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</n-layout-sider>
|
||||||
<n-layout-content>
|
<n-layout-content>
|
||||||
<div class="login-center">
|
<div class="login-center">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<n-tabs v-model:value="method" type="segment" size="small">
|
<n-tabs v-if="platform === 'rapt'" v-model:value="method" type="segment" size="small">
|
||||||
<n-tab v-for="item in methods" :key="item.id" :name="item.id">{{ item.label }}</n-tab>
|
<n-tab v-for="item in methods" :key="item.id" :name="item.id">{{ item.label }}</n-tab>
|
||||||
</n-tabs>
|
</n-tabs>
|
||||||
<n-form label-placement="left" label-width="96" size="small" :show-feedback="false" @submit.prevent="login">
|
<n-form label-placement="left" label-width="96" size="small" :show-feedback="false" @submit.prevent="login">
|
||||||
<template v-if="method === 'password'">
|
<template v-if="platform === 'huangdou'">
|
||||||
|
<n-text class="hint" depth="3">打开后会自动分配一个设备账号,无需观看广告。账号密码登录以后再做。</n-text>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="method === 'password'">
|
||||||
<n-form-item v-if="savedAccounts.length" label="已保存">
|
<n-form-item v-if="savedAccounts.length" label="已保存">
|
||||||
<div class="device-line">
|
<div class="device-line">
|
||||||
<n-select
|
<n-select
|
||||||
@@ -872,7 +970,7 @@ onUnmounted(stopLive);
|
|||||||
<n-checkbox v-model:checked="rememberPassword">记住账号密码</n-checkbox>
|
<n-checkbox v-model:checked="rememberPassword">记住账号密码</n-checkbox>
|
||||||
</n-form-item>
|
</n-form-item>
|
||||||
</template>
|
</template>
|
||||||
<n-form-item v-else-if="method === 'adb'" label="设备">
|
<n-form-item v-else-if="platform === 'rapt' && method === 'adb'" label="设备">
|
||||||
<div class="device-line">
|
<div class="device-line">
|
||||||
<n-select
|
<n-select
|
||||||
v-model:value="serial"
|
v-model:value="serial"
|
||||||
@@ -884,12 +982,12 @@ onUnmounted(stopLive);
|
|||||||
<n-button :loading="devicesBusy" @click="probeMumu">探测 MuMu</n-button>
|
<n-button :loading="devicesBusy" @click="probeMumu">探测 MuMu</n-button>
|
||||||
</div>
|
</div>
|
||||||
</n-form-item>
|
</n-form-item>
|
||||||
<n-text v-if="method === 'guest'" class="hint" depth="3">将注册一个新的游客账号,并读取它的个人信息。</n-text>
|
<n-text v-if="platform === 'rapt' && method === 'guest'" class="hint" depth="3">将注册一个新的游客账号,并读取它的个人信息。</n-text>
|
||||||
<n-text v-if="method === 'adb' && !devicesBusy && devices.length === 0" class="hint" depth="3">没有检测到已连接的设备。</n-text>
|
<n-text v-if="platform === 'rapt' && method === 'adb' && !devicesBusy && devices.length === 0" class="hint" depth="3">没有检测到已连接的设备。</n-text>
|
||||||
<n-text v-if="method === 'adb'" class="hint" depth="3">从已 root 的设备读取当前登录账号。未 root 的设备无法获取登录信息。默认同时读取这台设备的品牌、型号和系统版本,可在右下角设置里修改。</n-text>
|
<n-text v-if="platform === 'rapt' && method === 'adb'" class="hint" depth="3">从已 root 的设备读取当前登录账号。未 root 的设备无法获取登录信息。默认同时读取这台设备的品牌、型号和系统版本,可在右下角设置里修改。</n-text>
|
||||||
<n-alert v-if="error" class="hint" type="error" :show-icon="false">{{ error }}</n-alert>
|
<n-alert v-if="error" class="hint" type="error" :show-icon="false">{{ error }}</n-alert>
|
||||||
<div class="login-actions">
|
<div class="login-actions">
|
||||||
<n-button type="primary" attr-type="submit" :loading="busy">登录</n-button>
|
<n-button type="primary" attr-type="submit" :loading="busy">{{ platform === "huangdou" ? "进入" : "登录" }}</n-button>
|
||||||
</div>
|
</div>
|
||||||
</n-form>
|
</n-form>
|
||||||
</div>
|
</div>
|
||||||
@@ -914,7 +1012,7 @@ onUnmounted(stopLive);
|
|||||||
<n-modal v-model:show="settingsOpen" preset="card" title="设置" style="width: 640px">
|
<n-modal v-model:show="settingsOpen" preset="card" title="设置" style="width: 640px">
|
||||||
<div class="settings-modal-body">
|
<div class="settings-modal-body">
|
||||||
<n-alert v-if="settingsError" class="hint" type="error" :show-icon="false">{{ settingsError }}</n-alert>
|
<n-alert v-if="settingsError" class="hint" type="error" :show-icon="false">{{ settingsError }}</n-alert>
|
||||||
<SettingsPanel v-model:tab="settingsTab" :draft="draft" @choose="chooseDownloadDirectory" />
|
<SettingsPanel v-model:tab="settingsTab" :draft="draft" :hide-device="platform === 'huangdou'" @choose="chooseDownloadDirectory" />
|
||||||
</div>
|
</div>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<div class="modal-actions">
|
<div class="modal-actions">
|
||||||
@@ -979,6 +1077,12 @@ html { color-scheme: dark; }
|
|||||||
min-height: 0;
|
min-height: 0;
|
||||||
}
|
}
|
||||||
.sider { height: 100%; min-height: 100%; display: flex; flex-direction: column; box-sizing: border-box; padding: 12px 8px; }
|
.sider { height: 100%; min-height: 100%; display: flex; flex-direction: column; box-sizing: border-box; padding: 12px 8px; }
|
||||||
|
.platform-mark {
|
||||||
|
padding: 2px 12px 10px;
|
||||||
|
color: rgba(255, 255, 255, 0.55);
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
.user-nav {
|
.user-nav {
|
||||||
margin-top: auto;
|
margin-top: auto;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -1142,6 +1246,8 @@ html { color-scheme: dark; }
|
|||||||
.login-shell > .n-layout-scroll-container,
|
.login-shell > .n-layout-scroll-container,
|
||||||
.login-shell .n-layout-content,
|
.login-shell .n-layout-content,
|
||||||
.login-shell .n-layout-content > .n-layout-scroll-container { height: 100%; }
|
.login-shell .n-layout-content > .n-layout-scroll-container { height: 100%; }
|
||||||
|
.login-shell .n-layout-sider,
|
||||||
|
.login-shell .n-layout-sider > .n-layout-sider-scroll-container { height: 100%; }
|
||||||
.login-center {
|
.login-center {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -16,7 +16,9 @@ interface Job {
|
|||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
active: Job[];
|
active: Job[];
|
||||||
done: Job[];
|
done: Job[];
|
||||||
|
apiBase?: string;
|
||||||
}>();
|
}>();
|
||||||
|
const apiBase = computed(() => props.apiBase || "/api");
|
||||||
|
|
||||||
const tab = ref<"active" | "done">("active");
|
const tab = ref<"active" | "done">("active");
|
||||||
const holding = ref(false);
|
const holding = ref(false);
|
||||||
@@ -38,14 +40,14 @@ async function holdAll() {
|
|||||||
if (!props.active.length || holding.value) return;
|
if (!props.active.length || holding.value) return;
|
||||||
holding.value = true;
|
holding.value = true;
|
||||||
try {
|
try {
|
||||||
await fetch(resumeAll.value ? "/api/downloads/resume-all" : "/api/downloads/pause-all", { method: "POST" });
|
await fetch(resumeAll.value ? `${apiBase.value}/downloads/resume-all` : `${apiBase.value}/downloads/pause-all`, { method: "POST" });
|
||||||
} finally {
|
} finally {
|
||||||
holding.value = false;
|
holding.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function act(id: string, action: string) {
|
async function act(id: string, action: string) {
|
||||||
await fetch(`/api/downloads/${id}/${action}`, { method: "POST" });
|
await fetch(`${apiBase.value}/downloads/${id}/${action}`, { method: "POST" });
|
||||||
}
|
}
|
||||||
|
|
||||||
async function remuxSaved() {
|
async function remuxSaved() {
|
||||||
@@ -53,7 +55,7 @@ async function remuxSaved() {
|
|||||||
remuxing.value = true;
|
remuxing.value = true;
|
||||||
remuxNote.value = "";
|
remuxNote.value = "";
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/downloads/remux", { method: "POST" });
|
const response = await fetch(`${apiBase.value}/downloads/remux`, { method: "POST" });
|
||||||
const data = await response.json().catch(() => ({}));
|
const data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
remuxNote.value = data.detail || "重新合成失败";
|
remuxNote.value = data.detail || "重新合成失败";
|
||||||
@@ -73,7 +75,7 @@ async function remuxOne(id: string) {
|
|||||||
remuxingId.value = id;
|
remuxingId.value = id;
|
||||||
remuxNote.value = "";
|
remuxNote.value = "";
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/downloads/${id}/remux`, { method: "POST" });
|
const response = await fetch(`${apiBase.value}/downloads/${id}/remux`, { method: "POST" });
|
||||||
const data = await response.json().catch(() => ({}));
|
const data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
remuxNote.value = data.detail || "重新合成失败";
|
remuxNote.value = data.detail || "重新合成失败";
|
||||||
@@ -92,7 +94,7 @@ async function redownload(id: string) {
|
|||||||
if (remuxing.value || remuxingId.value) return;
|
if (remuxing.value || remuxingId.value) return;
|
||||||
remuxNote.value = "";
|
remuxNote.value = "";
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/downloads/${id}/redownload`, { method: "POST" });
|
const response = await fetch(`${apiBase.value}/downloads/${id}/redownload`, { method: "POST" });
|
||||||
const data = await response.json().catch(() => ({}));
|
const data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
remuxNote.value = data.detail || "重新下载失败";
|
remuxNote.value = data.detail || "重新下载失败";
|
||||||
@@ -105,7 +107,7 @@ async function redownload(id: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function remove(id: string) {
|
async function remove(id: string) {
|
||||||
await fetch(`/api/downloads/${id}`, { method: "DELETE" });
|
await fetch(`${apiBase.value}/downloads/${id}`, { method: "DELETE" });
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -6,13 +6,18 @@ interface Episode {
|
|||||||
idx: number;
|
idx: number;
|
||||||
title: string;
|
title: string;
|
||||||
playable: boolean;
|
playable: boolean;
|
||||||
|
media?: string;
|
||||||
|
locked_reason?: string;
|
||||||
|
is_preview?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
token: string;
|
token: string;
|
||||||
device: object | null;
|
device: object | null;
|
||||||
dramaId: number;
|
dramaId: string | number;
|
||||||
|
apiBase?: string;
|
||||||
}>();
|
}>();
|
||||||
|
const apiBase = computed(() => props.apiBase || "/api");
|
||||||
|
|
||||||
const episodes = ref<Episode[]>([]);
|
const episodes = ref<Episode[]>([]);
|
||||||
const current = ref<number | null>(null);
|
const current = ref<number | null>(null);
|
||||||
@@ -27,7 +32,7 @@ async function load() {
|
|||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = "";
|
error.value = "";
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/play/episodes", {
|
const response = await fetch(`${apiBase.value}/play/episodes`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ token: props.token, device: props.device, vid: props.dramaId }),
|
body: JSON.stringify({ token: props.token, device: props.device, vid: props.dramaId }),
|
||||||
@@ -62,7 +67,13 @@ function attach(cid: number) {
|
|||||||
const video = videoRef.value;
|
const video = videoRef.value;
|
||||||
if (!video) return;
|
if (!video) return;
|
||||||
stop();
|
stop();
|
||||||
const url = `/api/play/${props.dramaId}/${cid}/index.m3u8`;
|
const episode = episodes.value.find((item) => item.cid === cid);
|
||||||
|
if (episode?.media === "file") {
|
||||||
|
video.src = `${apiBase.value}/play/${props.dramaId}/${cid}/file`;
|
||||||
|
video.play().catch(() => undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const url = `${apiBase.value}/play/${props.dramaId}/${cid}/index.m3u8`;
|
||||||
if (Hls.isSupported()) {
|
if (Hls.isSupported()) {
|
||||||
const player = new Hls();
|
const player = new Hls();
|
||||||
hls = player;
|
hls = player;
|
||||||
@@ -115,7 +126,8 @@ onUnmounted(stop);
|
|||||||
@click="select(episode)"
|
@click="select(episode)"
|
||||||
>
|
>
|
||||||
<span class="play-episode-title">{{ episode.title }}</span>
|
<span class="play-episode-title">{{ episode.title }}</span>
|
||||||
<span v-if="!episode.playable" class="play-episode-lock">无地址</span>
|
<span v-if="!episode.playable" class="play-episode-lock">{{ episode.locked_reason || "无地址" }}</span>
|
||||||
|
<span v-else-if="episode.is_preview" class="play-episode-lock">试看</span>
|
||||||
</button>
|
</button>
|
||||||
<div v-if="!loading && episodes.length === 0" class="play-empty">没有分集</div>
|
<div v-if="!loading && episodes.length === 0" class="play-empty">没有分集</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -157,8 +169,9 @@ onUnmounted(stop);
|
|||||||
.play-episode {
|
.play-episode {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 8px;
|
gap: 4px 8px;
|
||||||
min-height: 36px;
|
min-height: 36px;
|
||||||
margin: 0 0 4px;
|
margin: 0 0 4px;
|
||||||
padding: 6px 10px;
|
padding: 6px 10px;
|
||||||
@@ -173,6 +186,6 @@ onUnmounted(stop);
|
|||||||
.play-episode.current { background: rgba(99, 226, 183, 0.16); }
|
.play-episode.current { background: rgba(99, 226, 183, 0.16); }
|
||||||
.play-episode:disabled { color: rgba(255, 255, 255, 0.35); cursor: default; }
|
.play-episode:disabled { color: rgba(255, 255, 255, 0.35); cursor: default; }
|
||||||
.play-episode-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.play-episode-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.play-episode-lock { flex: none; font-size: 12px; }
|
.play-episode-lock { flex: 1 1 100%; font-size: 12px; line-height: 1.3; white-space: normal; }
|
||||||
.play-empty { padding: 8px 10px; color: rgba(255, 255, 255, 0.45); }
|
.play-empty { padding: 8px 10px; color: rgba(255, 255, 255, 0.45); }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ interface SettingsDraft {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const tab = defineModel<"device" | "proxy" | "download">("tab", { required: true });
|
const tab = defineModel<"device" | "proxy" | "download">("tab", { required: true });
|
||||||
const props = defineProps<{ draft: SettingsDraft }>();
|
const props = defineProps<{ draft: SettingsDraft; hideDevice?: boolean }>();
|
||||||
const emit = defineEmits<{ choose: [] }>();
|
const emit = defineEmits<{ choose: [] }>();
|
||||||
|
|
||||||
const deviceFields: { key: keyof DeviceProfile; label: string; kind?: "select" | "switch" | "language" }[] = [
|
const deviceFields: { key: keyof DeviceProfile; label: string; kind?: "select" | "switch" | "language" }[] = [
|
||||||
@@ -64,7 +64,7 @@ function setDraftField(key: keyof DeviceProfile, value: string | boolean) {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<n-tabs v-model:value="tab" type="line" size="small">
|
<n-tabs v-model:value="tab" type="line" size="small">
|
||||||
<n-tab-pane name="device" tab="设备信息" display-directive="if">
|
<n-tab-pane v-if="!hideDevice" name="device" tab="设备信息" display-directive="if">
|
||||||
<n-form class="settings-form" label-placement="left" label-width="96" size="small" :show-feedback="false">
|
<n-form class="settings-form" label-placement="left" label-width="96" size="small" :show-feedback="false">
|
||||||
<n-form-item v-for="field in deviceFields" :key="field.key" :label="field.label">
|
<n-form-item v-for="field in deviceFields" :key="field.key" :label="field.label">
|
||||||
<n-switch
|
<n-switch
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
interface Drama {
|
interface Drama {
|
||||||
id: number;
|
id: string | number;
|
||||||
title: string;
|
title: string;
|
||||||
image: string;
|
image: string;
|
||||||
|
payType?: string;
|
||||||
|
corner?: string;
|
||||||
|
locked?: boolean;
|
||||||
|
limitedFree?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Section {
|
interface Section {
|
||||||
@@ -16,11 +20,14 @@ interface Section {
|
|||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
token: string;
|
token: string;
|
||||||
device: object | null;
|
device: object | null;
|
||||||
|
apiBase?: string;
|
||||||
|
remoteSearch?: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
const apiBase = computed(() => props.apiBase || "/api");
|
||||||
|
|
||||||
const sections = ref<Section[]>([]);
|
const sections = ref<Section[]>([]);
|
||||||
const expanded = ref<string[]>([]);
|
const expanded = ref<string[]>([]);
|
||||||
const selected = ref<Set<number>>(new Set());
|
const selected = ref<Set<string>>(new Set());
|
||||||
const busy = ref(false);
|
const busy = ref(false);
|
||||||
const error = ref("");
|
const error = ref("");
|
||||||
const query = ref("");
|
const query = ref("");
|
||||||
@@ -40,7 +47,7 @@ const scrollEl = ref<HTMLElement | null>(null);
|
|||||||
|
|
||||||
function coverOf(image: string) {
|
function coverOf(image: string) {
|
||||||
if (!image) return "";
|
if (!image) return "";
|
||||||
if (image.startsWith("/api/covers/")) return image;
|
if (image.startsWith("/api/")) return image;
|
||||||
if (image.startsWith("http")) return image;
|
if (image.startsWith("http")) return image;
|
||||||
return `https://apis.raptdrama.com${image.startsWith("/") ? image : `/${image}`}`;
|
return `https://apis.raptdrama.com${image.startsWith("/") ? image : `/${image}`}`;
|
||||||
}
|
}
|
||||||
@@ -56,7 +63,7 @@ function toggleExpanded(key: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function selectedCount(section: Section) {
|
function selectedCount(section: Section) {
|
||||||
return section.items.filter((item) => selected.value.has(item.id)).length;
|
return section.items.filter((item) => selected.value.has(dramaKey(item.id))).length;
|
||||||
}
|
}
|
||||||
|
|
||||||
function allChecked(section: Section) {
|
function allChecked(section: Section) {
|
||||||
@@ -68,18 +75,24 @@ function someChecked(section: Section) {
|
|||||||
return count > 0 && count < section.items.length;
|
return count > 0 && count < section.items.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleDrama(id: number, checked: boolean) {
|
function dramaKey(id: string | number) {
|
||||||
|
return String(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleDrama(id: string | number, checked: boolean) {
|
||||||
const next = new Set(selected.value);
|
const next = new Set(selected.value);
|
||||||
if (checked) next.add(id);
|
const key = dramaKey(id);
|
||||||
else next.delete(id);
|
if (checked) next.add(key);
|
||||||
|
else next.delete(key);
|
||||||
selected.value = next;
|
selected.value = next;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleSection(section: Section, checked: boolean) {
|
function toggleSection(section: Section, checked: boolean) {
|
||||||
const next = new Set(selected.value);
|
const next = new Set(selected.value);
|
||||||
for (const item of section.items) {
|
for (const item of section.items) {
|
||||||
if (checked) next.add(item.id);
|
const key = dramaKey(item.id);
|
||||||
else next.delete(item.id);
|
if (checked) next.add(key);
|
||||||
|
else next.delete(key);
|
||||||
}
|
}
|
||||||
selected.value = next;
|
selected.value = next;
|
||||||
}
|
}
|
||||||
@@ -89,7 +102,7 @@ function clearSelection() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function pruneSelection() {
|
function pruneSelection() {
|
||||||
const ids = new Set(sections.value.flatMap((section) => section.items.map((item) => item.id)));
|
const ids = new Set(sections.value.flatMap((section) => section.items.map((item) => dramaKey(item.id))));
|
||||||
selected.value = new Set([...selected.value].filter((id) => ids.has(id)));
|
selected.value = new Set([...selected.value].filter((id) => ids.has(id)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,7 +135,7 @@ async function reload(refresh = false) {
|
|||||||
error.value = "";
|
error.value = "";
|
||||||
busy.value = true;
|
busy.value = true;
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/catalog", {
|
const response = await fetch(`${apiBase.value}/catalog`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ token: props.token, device: props.device, refresh }),
|
body: JSON.stringify({ token: props.token, device: props.device, refresh }),
|
||||||
@@ -173,13 +186,13 @@ async function reload(refresh = false) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function cardKey(sectionKey: string, id: number) {
|
function cardKey(sectionKey: string, id: string | number) {
|
||||||
return `${sectionKey}-${id}`;
|
return `${sectionKey}-${dramaKey(id)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function matches() {
|
function matches() {
|
||||||
const keyword = query.value.trim().toLowerCase();
|
const keyword = query.value.trim().toLowerCase();
|
||||||
const found: { sectionKey: string; id: number }[] = [];
|
const found: { sectionKey: string; id: string | number }[] = [];
|
||||||
if (!keyword) return found;
|
if (!keyword) return found;
|
||||||
for (const section of sections.value) {
|
for (const section of sections.value) {
|
||||||
for (const item of section.items) {
|
for (const item of section.items) {
|
||||||
@@ -250,7 +263,12 @@ async function find(keyword = query.value) {
|
|||||||
searchHint.value = "请输入名称";
|
searchHint.value = "请输入名称";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const found = matches();
|
let found = matches();
|
||||||
|
if (!found.length && props.remoteSearch) {
|
||||||
|
await searchRemote(text, generation);
|
||||||
|
if (generation !== revealGeneration) return;
|
||||||
|
found = matches();
|
||||||
|
}
|
||||||
if (!found.length) {
|
if (!found.length) {
|
||||||
searchHint.value = "没有找到";
|
searchHint.value = "没有找到";
|
||||||
flashKey.value = "";
|
flashKey.value = "";
|
||||||
@@ -289,8 +307,44 @@ onMounted(() => {
|
|||||||
});
|
});
|
||||||
defineExpose({ reload, busy, find, searchHint, clearSearch, loadDirectory });
|
defineExpose({ reload, busy, find, searchHint, clearSearch, loadDirectory });
|
||||||
|
|
||||||
|
async function searchRemote(keyword: string, generation: number) {
|
||||||
|
searchHint.value = "正在搜索";
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${apiBase.value}/search`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ token: props.token, device: props.device, keyword }),
|
||||||
|
});
|
||||||
|
const payload = await response.json().catch(() => ({}));
|
||||||
|
if (generation !== revealGeneration) return;
|
||||||
|
if (!response.ok) {
|
||||||
|
searchHint.value = typeof payload.detail === "string" ? payload.detail : "搜索失败";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const items = Array.isArray(payload.items) ? payload.items : [];
|
||||||
|
const key = "search";
|
||||||
|
const existing = sections.value.find((section) => section.key === key);
|
||||||
|
if (existing) {
|
||||||
|
existing.items = items;
|
||||||
|
existing.loading = false;
|
||||||
|
existing.note = items.length ? "" : "没有搜索结果";
|
||||||
|
} else {
|
||||||
|
sections.value.unshift({
|
||||||
|
key,
|
||||||
|
name: "搜索结果",
|
||||||
|
note: items.length ? "" : "没有搜索结果",
|
||||||
|
items,
|
||||||
|
loading: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!isExpanded(key)) expanded.value = [...expanded.value, key];
|
||||||
|
} catch {
|
||||||
|
if (generation === revealGeneration) searchHint.value = "搜索失败";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function loadDirectory() {
|
async function loadDirectory() {
|
||||||
const response = await fetch("/api/downloads");
|
const response = await fetch(`${apiBase.value}/downloads`);
|
||||||
if (!response.ok) return;
|
if (!response.ok) return;
|
||||||
const payload = await response.json();
|
const payload = await response.json();
|
||||||
directory.value = payload.directory || "";
|
directory.value = payload.directory || "";
|
||||||
@@ -298,7 +352,7 @@ async function loadDirectory() {
|
|||||||
|
|
||||||
async function chooseDirectory() {
|
async function chooseDirectory() {
|
||||||
footError.value = "";
|
footError.value = "";
|
||||||
const response = await fetch("/api/downloads/pick", { method: "POST" });
|
const response = await fetch(`${apiBase.value}/downloads/pick`, { method: "POST" });
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const payload = await response.json().catch(() => ({}));
|
const payload = await response.json().catch(() => ({}));
|
||||||
const detail = typeof payload.detail === "string" ? payload.detail : "";
|
const detail = typeof payload.detail === "string" ? payload.detail : "";
|
||||||
@@ -310,20 +364,21 @@ async function chooseDirectory() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function startDownload() {
|
async function startDownload() {
|
||||||
const seen = new Set<number>();
|
const seen = new Set<string>();
|
||||||
const items: { id: number; title: string; image: string }[] = [];
|
const items: { id: string; title: string; image: string }[] = [];
|
||||||
for (const section of sections.value) {
|
for (const section of sections.value) {
|
||||||
for (const item of section.items) {
|
for (const item of section.items) {
|
||||||
if (!selected.value.has(item.id) || seen.has(item.id)) continue;
|
const key = dramaKey(item.id);
|
||||||
seen.add(item.id);
|
if (!selected.value.has(key) || seen.has(key)) continue;
|
||||||
items.push({ id: item.id, title: item.title, image: item.image });
|
seen.add(key);
|
||||||
|
items.push({ id: key, title: item.title, image: item.image });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!items.length) return;
|
if (!items.length) return;
|
||||||
starting.value = true;
|
starting.value = true;
|
||||||
footError.value = "";
|
footError.value = "";
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/downloads", {
|
const response = await fetch(`${apiBase.value}/downloads`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ token: props.token, device: props.device, items }),
|
body: JSON.stringify({ token: props.token, device: props.device, items }),
|
||||||
@@ -384,10 +439,11 @@ async function startDownload() {
|
|||||||
:key="item.id"
|
:key="item.id"
|
||||||
class="drama-card"
|
class="drama-card"
|
||||||
:data-card="cardKey(section.key, item.id)"
|
:data-card="cardKey(section.key, item.id)"
|
||||||
@click="toggleDrama(item.id, !selected.has(item.id))"
|
@click="toggleDrama(item.id, !selected.has(dramaKey(item.id)))"
|
||||||
>
|
>
|
||||||
<div class="cover">
|
<div class="cover">
|
||||||
<img v-if="item.image" :src="coverOf(item.image)" :alt="item.title" />
|
<img v-if="item.image" :src="coverOf(item.image)" :alt="item.title" />
|
||||||
|
<span v-if="item.corner || item.locked || item.limitedFree" class="cover-tag">{{ item.corner || (item.limitedFree ? "限免" : item.payType || "付费") }}</span>
|
||||||
<div class="cover-play-layer">
|
<div class="cover-play-layer">
|
||||||
<n-tooltip placement="top">
|
<n-tooltip placement="top">
|
||||||
<template #trigger>
|
<template #trigger>
|
||||||
@@ -402,7 +458,7 @@ async function startDownload() {
|
|||||||
<div class="pick" @click.stop>
|
<div class="pick" @click.stop>
|
||||||
<n-tooltip placement="left">
|
<n-tooltip placement="left">
|
||||||
<template #trigger>
|
<template #trigger>
|
||||||
<n-checkbox :checked="selected.has(item.id)" @update:checked="toggleDrama(item.id, $event)" />
|
<n-checkbox :checked="selected.has(dramaKey(item.id))" @update:checked="toggleDrama(item.id, $event)" />
|
||||||
</template>
|
</template>
|
||||||
{{ selected.has(item.id) ? "取消选择" : "选择" }}
|
{{ selected.has(item.id) ? "取消选择" : "选择" }}
|
||||||
</n-tooltip>
|
</n-tooltip>
|
||||||
@@ -496,6 +552,22 @@ async function startDownload() {
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.cover { position: relative; background: #2a2a2a; }
|
.cover { position: relative; background: #2a2a2a; }
|
||||||
|
.cover-tag {
|
||||||
|
position: absolute;
|
||||||
|
left: 6px;
|
||||||
|
top: 6px;
|
||||||
|
z-index: 2;
|
||||||
|
max-width: calc(100% - 12px);
|
||||||
|
padding: 1px 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: rgba(0, 0, 0, 0.62);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 16px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
.cover img { display: block; width: 100%; aspect-ratio: 3 / 4; object-fit: cover; }
|
.cover img { display: block; width: 100%; aspect-ratio: 3 / 4; object-fit: cover; }
|
||||||
.cover:not(:has(img)) { aspect-ratio: 3 / 4; }
|
.cover:not(:has(img)) { aspect-ratio: 3 / 4; }
|
||||||
.cover-play-layer {
|
.cover-play-layer {
|
||||||
|
|||||||
@@ -34,6 +34,13 @@ export default defineConfig(() => ({
|
|||||||
port: 8799,
|
port: 8799,
|
||||||
strictPort: true,
|
strictPort: true,
|
||||||
host: host || false,
|
host: host || false,
|
||||||
|
proxy: {
|
||||||
|
"/api": {
|
||||||
|
target: process.env.RAPTD_DEV_API || "http://127.0.0.1:18799",
|
||||||
|
changeOrigin: true,
|
||||||
|
ws: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
hmr: host
|
hmr: host
|
||||||
? {
|
? {
|
||||||
protocol: "ws",
|
protocol: "ws",
|
||||||
|
|||||||
Reference in New Issue
Block a user