Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c2105c786 |
@@ -1,11 +1,11 @@
|
||||
# RaptDrama Download Tools
|
||||
# VideosDownTools
|
||||
|
||||
Windows 桌面程序,用来登录 RaptDrama、浏览剧目、播放已缓存的分集,以及把剧集下载成 MP4。
|
||||
Windows 桌面程序,用来登录 RaptDrama、黄豆短剧和 DramaBox,浏览剧目、播放分集,以及把剧集下载成 MP4。
|
||||
|
||||
## 使用分发包
|
||||
|
||||
1. 解压 `dist/RaptDrama-Download-Tools-windows-x64.zip`。
|
||||
2. 进入 `RaptDrama-Download-Tools`,运行 `raptdrama.exe`。
|
||||
1. 解压 `dist/VideosDownTools-windows-x64.zip`。
|
||||
2. 进入 `VideosDownTools`,运行 `VideosDownTools.exe`。
|
||||
3. 压缩包里已经带有 Python、adb、ffmpeg 和 WebView2 离线安装包。本机如果还没有 WebView2,程序启动时会静默安装。
|
||||
|
||||
程序会在自己的目录里写入:
|
||||
@@ -46,6 +46,6 @@ python scripts\package.py
|
||||
- `tools/ffmpeg/ffmpeg.exe`
|
||||
- `vendor/webview2/MicrosoftEdgeWebView2RuntimeInstallerX64.exe`
|
||||
|
||||
adb 和 WebView2 打包时不再下载。完成后得到 `dist/RaptDrama-Download-Tools-windows-x64.zip`。
|
||||
adb 和 WebView2 打包时不再下载。完成后得到 `dist/VideosDownTools-windows-x64.zip`。
|
||||
|
||||
打包脚本是 Python,公共步骤和平台相关的运行时是分开的。目前只接好了 Windows。macOS 和 Linux 以后把对应文件放进 `vendor` 即可。
|
||||
|
||||
Generated
+2
-2
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "raptdrama",
|
||||
"name": "videosdowntools",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "raptdrama",
|
||||
"name": "videosdowntools",
|
||||
"version": "0.1.0",
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2"
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "raptdrama",
|
||||
"name": "videosdowntools",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"scripts": {
|
||||
|
||||
+3
-3
@@ -23,7 +23,7 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DIST = ROOT / "dist"
|
||||
CACHE = DIST / "cache"
|
||||
STAGE_NAME = "RaptDrama-Download-Tools"
|
||||
STAGE_NAME = "VideosDownTools"
|
||||
|
||||
PYTHON_VERSION = "3.13.15"
|
||||
PYTHON_EMBED_URL = (
|
||||
@@ -50,7 +50,7 @@ def download(url: str, dest: Path) -> None:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = dest.with_suffix(dest.suffix + ".part")
|
||||
log(f"下载 {url}")
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "RaptDrama"})
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "VideosDownTools"})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=120) as response, temporary.open("wb") as handle:
|
||||
total = int(response.headers.get("Content-Length") or 0)
|
||||
@@ -91,7 +91,7 @@ def build_desktop() -> Path:
|
||||
text=True,
|
||||
)
|
||||
target = Path(json.loads(meta)["target_directory"]) / "release"
|
||||
name = "raptdrama.exe" if sys.platform == "win32" else "raptdrama"
|
||||
name = "VideosDownTools.exe" if sys.platform == "win32" else "VideosDownTools"
|
||||
exe = target / name
|
||||
if not exe.is_file():
|
||||
raise SystemExit(f"没有找到桌面程序 {exe}")
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ from server.services.dramabox.downloads import downloads as dramabox_downloads
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(title="RaptDrama")
|
||||
app = FastAPI(title="VideosDownTools")
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
|
||||
@@ -11,10 +11,12 @@ 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 import accounts as hd_accounts
|
||||
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.huangdou.downloads import enqueue_download
|
||||
from server.services.playlist import is_direct_media
|
||||
|
||||
router = APIRouter(prefix="/api/huangdou")
|
||||
@@ -24,6 +26,37 @@ class TokenBody(BaseModel):
|
||||
token: str = ""
|
||||
refresh: bool = False
|
||||
keyword: str = ""
|
||||
host: str = ""
|
||||
|
||||
|
||||
class FingerprintBody(BaseModel):
|
||||
browserName: str = ""
|
||||
language: str = ""
|
||||
userAgent: str = ""
|
||||
platform: str = ""
|
||||
|
||||
|
||||
class SavedAccountBody(BaseModel):
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
nickname: str = ""
|
||||
|
||||
|
||||
class SavedAccountsBody(BaseModel):
|
||||
accounts: list[SavedAccountBody] = []
|
||||
|
||||
|
||||
class LoginBody(BaseModel):
|
||||
host: str = ""
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
|
||||
|
||||
class AccountBody(BaseModel):
|
||||
token: str = ""
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
rotate_fingerprint: bool = False
|
||||
|
||||
|
||||
class DownloadItem(BaseModel):
|
||||
@@ -34,6 +67,7 @@ class DownloadItem(BaseModel):
|
||||
|
||||
class DownloadStartBody(BaseModel):
|
||||
token: str = ""
|
||||
download_points: bool = False
|
||||
items: list[DownloadItem] = []
|
||||
|
||||
|
||||
@@ -59,9 +93,52 @@ def _require_token(token: str) -> None:
|
||||
client.token = token
|
||||
|
||||
|
||||
@router.post("/fingerprint")
|
||||
def adopt_fingerprint(body: FingerprintBody):
|
||||
client.adopt_browser_fingerprint(body.model_dump())
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/fingerprint/roll")
|
||||
def roll_fingerprint():
|
||||
client.roll_account_fingerprint()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/accounts")
|
||||
def list_accounts():
|
||||
return {"accounts": hd_accounts.load()}
|
||||
|
||||
|
||||
@router.put("/accounts")
|
||||
def save_accounts(body: SavedAccountsBody):
|
||||
return {"accounts": hd_accounts.replace([item.model_dump() for item in body.accounts])}
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(body: LoginBody):
|
||||
def action():
|
||||
entered = hd_login.enter(body.host)
|
||||
if body.username.strip() and body.password:
|
||||
return hd_login.login_account(body.username, body.password)
|
||||
return entered
|
||||
|
||||
return call(action)
|
||||
|
||||
|
||||
@router.post("/login/device")
|
||||
def login_device():
|
||||
return call(hd_login.enter)
|
||||
def login_device(body: TokenBody | None = None):
|
||||
host = body.host if body else ""
|
||||
return call(lambda: hd_login.enter(host))
|
||||
|
||||
|
||||
@router.post("/login/account")
|
||||
def login_account(body: AccountBody):
|
||||
def action():
|
||||
_require_token(body.token)
|
||||
return hd_login.login_account(body.username, body.password, body.rotate_fingerprint)
|
||||
|
||||
return call(action)
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
@@ -131,7 +208,8 @@ def list_episodes(body: PlayBody):
|
||||
"cid": ep["cid"],
|
||||
"idx": ep["idx"],
|
||||
"title": ep["title"],
|
||||
"playable": bool(ep.get("src")),
|
||||
"playable": bool(ep.get("playable")),
|
||||
"points": int(ep.get("points") or 0),
|
||||
"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")),
|
||||
@@ -156,7 +234,7 @@ def _public_url(url: str) -> str:
|
||||
def play_segment(url: str):
|
||||
target = _public_url(url)
|
||||
try:
|
||||
upstream = http.open_stream(target, headers={"User-Agent": USER_AGENT, "Referer": "https://pmihlvee.cc/"})
|
||||
upstream = http.open_stream(target, headers={"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"})
|
||||
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"
|
||||
@@ -179,7 +257,7 @@ def play_file(vid: str, cid: int):
|
||||
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/"})
|
||||
upstream = http.open_stream(src, headers={"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"})
|
||||
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"
|
||||
@@ -236,7 +314,12 @@ def list_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])
|
||||
hd_downloads._headers["Referer"] = client.host.rstrip("/") + "/"
|
||||
return enqueue_download(
|
||||
body.token,
|
||||
[item.model_dump() for item in body.items],
|
||||
body.download_points,
|
||||
)
|
||||
|
||||
return call(action)
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
PATH = ROOT / "cache" / "huangdou" / "accounts.json"
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def load() -> list[dict]:
|
||||
with _lock:
|
||||
return _parse()
|
||||
|
||||
|
||||
def replace(rows: list) -> list[dict]:
|
||||
cleaned = []
|
||||
seen: set[str] = set()
|
||||
if isinstance(rows, list):
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
username = str(item.get("username") or "").strip()
|
||||
password = str(item.get("password") or "")
|
||||
if not username or not password or username in seen:
|
||||
continue
|
||||
seen.add(username)
|
||||
cleaned.append(
|
||||
{
|
||||
"username": username,
|
||||
"password": password,
|
||||
"nickname": str(item.get("nickname") or "").strip(),
|
||||
}
|
||||
)
|
||||
if len(cleaned) >= 30:
|
||||
break
|
||||
with _lock:
|
||||
PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = PATH.with_suffix(".json.tmp")
|
||||
temporary.write_text(json.dumps({"accounts": cleaned}, ensure_ascii=False), encoding="utf-8")
|
||||
temporary.replace(PATH)
|
||||
return cleaned
|
||||
|
||||
|
||||
def _parse() -> list[dict]:
|
||||
if not PATH.is_file():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(PATH.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return []
|
||||
rows = data.get("accounts") if isinstance(data, dict) else None
|
||||
if not isinstance(rows, list):
|
||||
return []
|
||||
cleaned = []
|
||||
seen: set[str] = set()
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
username = str(item.get("username") or "").strip()
|
||||
password = str(item.get("password") or "")
|
||||
if not username or not password or username in seen:
|
||||
continue
|
||||
seen.add(username)
|
||||
cleaned.append(
|
||||
{
|
||||
"username": username,
|
||||
"password": password,
|
||||
"nickname": str(item.get("nickname") or "").strip(),
|
||||
}
|
||||
)
|
||||
return cleaned
|
||||
@@ -2,7 +2,16 @@ from server.services.huangdou.client import ApiError, TokenExpired, client
|
||||
from server.services.huangdou.crypto import USER_AGENT
|
||||
|
||||
|
||||
def device_info() -> dict:
|
||||
def device_info(identity: str = "guest") -> dict:
|
||||
if identity == "account":
|
||||
client._ensure_fingerprint()
|
||||
info = client.device_info
|
||||
else:
|
||||
if not client.guest_device_id:
|
||||
client.roll_guest_fingerprint()
|
||||
info = client.guest_device_info
|
||||
if isinstance(info, dict) and info:
|
||||
return dict(info)
|
||||
return {
|
||||
"browserName": "Chrome",
|
||||
"language": "zh-CN",
|
||||
@@ -33,8 +42,34 @@ def login_device(*, force_new: bool = False) -> dict:
|
||||
return data
|
||||
|
||||
|
||||
def user_info() -> dict:
|
||||
data = client.request("/user/info", {}, auth=True)
|
||||
def login_username(username: str, password: str, channel_code: str = "") -> dict:
|
||||
data = client.request(
|
||||
"/login/username",
|
||||
{
|
||||
"line_code": "china_1",
|
||||
"share_code": "",
|
||||
"channel_code": channel_code,
|
||||
"username": username.strip(),
|
||||
"password": password,
|
||||
"clipboard_text": "",
|
||||
"device_info": device_info("account"),
|
||||
},
|
||||
auth=False,
|
||||
identity="account",
|
||||
)
|
||||
if not isinstance(data, dict):
|
||||
raise RuntimeError("账号登录没有返回数据")
|
||||
token = str(data.get("token") or "").strip()
|
||||
if not token:
|
||||
raise RuntimeError("账号登录没有返回 token")
|
||||
client.account_token = token
|
||||
client.account_username = username.strip()
|
||||
client.save()
|
||||
return data
|
||||
|
||||
|
||||
def user_info(*, identity: str = "guest") -> dict:
|
||||
data = client.request("/user/info", {}, auth=True, identity=identity)
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
@@ -110,13 +145,21 @@ def limited_free(page: int = 1, size: int = 50) -> dict:
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def drama_detail(drama_id: str) -> dict:
|
||||
data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True)
|
||||
def drama_detail(drama_id: str, *, identity: str = "guest") -> dict:
|
||||
data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True, identity=identity)
|
||||
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)
|
||||
def drama_play(drama_id: str, seq: int, *, identity: str = "guest") -> dict:
|
||||
data = client.request("/drama/play", {"id": str(drama_id), "seq": str(seq)}, auth=True, identity=identity)
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def drama_buy(drama_id: str, seq: int, method: str = "") -> dict:
|
||||
body = {"id": str(drama_id), "seq": str(seq)}
|
||||
if method:
|
||||
body["method"] = method
|
||||
data = client.request("/drama/doBuy", body, auth=True, identity="account")
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
@@ -141,7 +184,9 @@ __all__ = [
|
||||
"drama_list",
|
||||
"drama_play",
|
||||
"limited_free",
|
||||
"drama_buy",
|
||||
"login_device",
|
||||
"login_username",
|
||||
"nav_block",
|
||||
"nav_list",
|
||||
"system_info",
|
||||
|
||||
@@ -19,21 +19,15 @@ 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",
|
||||
)
|
||||
DEFAULT_HOST = "https://pmihlvee.cc"
|
||||
|
||||
LINE_CODE = "china_1"
|
||||
DEFAULT_DEVICE_INFO = {
|
||||
"browserName": "Chrome",
|
||||
"language": LANG,
|
||||
"userAgent": USER_AGENT,
|
||||
"platform": "Win32",
|
||||
}
|
||||
|
||||
|
||||
class TokenExpired(RuntimeError):
|
||||
@@ -48,12 +42,20 @@ class ApiError(RuntimeError):
|
||||
|
||||
class HuangdouClient:
|
||||
def __init__(self) -> None:
|
||||
self.device_id = new_uuid()
|
||||
self.session_id = session_id_of("")
|
||||
self.device_id = ""
|
||||
self.session_id = ""
|
||||
self.device_info: dict = {}
|
||||
self.device_info_source = ""
|
||||
self.guest_device_id = ""
|
||||
self.guest_session_id = ""
|
||||
self.guest_device_info: dict = {}
|
||||
self.token = ""
|
||||
self.host = HOSTS[0]
|
||||
self.account_token = ""
|
||||
self.account_username = ""
|
||||
self.host = DEFAULT_HOST
|
||||
self.profile: dict = {}
|
||||
self._load()
|
||||
self._ensure_fingerprint()
|
||||
|
||||
def _load(self) -> None:
|
||||
if not SESSION_PATH.is_file():
|
||||
@@ -65,10 +67,21 @@ class HuangdouClient:
|
||||
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.session_id = str(data.get("session_id") or self.session_id)
|
||||
info = data.get("device_info")
|
||||
if isinstance(info, dict) and info:
|
||||
self.device_info = dict(info)
|
||||
self.device_info_source = str(data.get("device_info_source") or "")
|
||||
self.guest_device_id = str(data.get("guest_device_id") or "")
|
||||
self.guest_session_id = str(data.get("guest_session_id") or "")
|
||||
guest_info = data.get("guest_device_info")
|
||||
if isinstance(guest_info, dict) and guest_info:
|
||||
self.guest_device_info = dict(guest_info)
|
||||
self.token = str(data.get("token") or "")
|
||||
self.account_token = str(data.get("account_token") or "")
|
||||
self.account_username = str(data.get("account_username") or "")
|
||||
host = str(data.get("host") or "")
|
||||
if host.startswith("https://"):
|
||||
if host.startswith("http://") or host.startswith("https://"):
|
||||
self.host = host.rstrip("/")
|
||||
profile = data.get("profile")
|
||||
if isinstance(profile, dict):
|
||||
@@ -79,7 +92,14 @@ class HuangdouClient:
|
||||
payload = {
|
||||
"device_id": self.device_id,
|
||||
"session_id": self.session_id,
|
||||
"device_info": self.device_info,
|
||||
"device_info_source": self.device_info_source,
|
||||
"guest_device_id": self.guest_device_id,
|
||||
"guest_session_id": self.guest_session_id,
|
||||
"guest_device_info": self.guest_device_info,
|
||||
"token": self.token,
|
||||
"account_token": self.account_token,
|
||||
"account_username": self.account_username,
|
||||
"host": self.host,
|
||||
"profile": self.profile,
|
||||
}
|
||||
@@ -87,32 +107,123 @@ class HuangdouClient:
|
||||
temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
temporary.replace(SESSION_PATH)
|
||||
|
||||
def _ensure_fingerprint(self) -> None:
|
||||
changed = False
|
||||
if not self.device_id:
|
||||
self.device_id = new_uuid()
|
||||
changed = True
|
||||
if not self.session_id:
|
||||
self.session_id = session_id_of("")
|
||||
changed = True
|
||||
if not self.device_info:
|
||||
self.device_info = dict(DEFAULT_DEVICE_INFO)
|
||||
self.device_info_source = "default"
|
||||
changed = True
|
||||
if changed:
|
||||
self.save()
|
||||
|
||||
def _new_device_info(self) -> dict:
|
||||
return dict(self.device_info) if self.device_info else dict(DEFAULT_DEVICE_INFO)
|
||||
|
||||
def adopt_browser_fingerprint(self, info: dict) -> bool:
|
||||
self._ensure_fingerprint()
|
||||
if self.device_info_source in {"browser", "fixed"}:
|
||||
return False
|
||||
cleaned = {
|
||||
"browserName": str((info or {}).get("browserName") or "").strip() or "Chrome",
|
||||
"language": str((info or {}).get("language") or "").strip() or LANG,
|
||||
"userAgent": str((info or {}).get("userAgent") or "").strip(),
|
||||
"platform": str((info or {}).get("platform") or "").strip() or "Win32",
|
||||
}
|
||||
if not cleaned["userAgent"]:
|
||||
return False
|
||||
self.device_info = cleaned
|
||||
self.device_info_source = "browser"
|
||||
self.save()
|
||||
return True
|
||||
|
||||
def roll_guest_fingerprint(self) -> None:
|
||||
self.guest_device_id = new_uuid()
|
||||
self.guest_session_id = session_id_of("")
|
||||
self.guest_device_info = self._new_device_info()
|
||||
self.token = ""
|
||||
self.save()
|
||||
|
||||
def roll_account_fingerprint(self) -> None:
|
||||
self._ensure_fingerprint()
|
||||
info = dict(self.device_info) if self.device_info else dict(DEFAULT_DEVICE_INFO)
|
||||
self.device_id = new_uuid()
|
||||
self.session_id = session_id_of("")
|
||||
self.device_info = info
|
||||
self.device_info_source = "fixed"
|
||||
self.account_token = ""
|
||||
self.save()
|
||||
|
||||
def clear_token(self) -> None:
|
||||
self.token = ""
|
||||
self.guest_device_id = ""
|
||||
self.guest_session_id = ""
|
||||
self.guest_device_info = {}
|
||||
self.account_token = ""
|
||||
self.account_username = ""
|
||||
self.profile = {}
|
||||
self.save()
|
||||
|
||||
def request(self, path: str, data: dict | None = None, *, auth: bool = True) -> dict | list | None:
|
||||
def set_host(self, host: str) -> str:
|
||||
text = normalize_host(host)
|
||||
if text:
|
||||
self.host = text
|
||||
self.save()
|
||||
return self.host
|
||||
|
||||
def request(self, path: str, data: dict | None = None, *, auth: bool = True, identity: str = "guest") -> dict | list | None:
|
||||
token, device_id, session_id, info = self._identity(identity, auth)
|
||||
user_agent = str((info or {}).get("userAgent") or USER_AGENT)
|
||||
last_error: Exception | None = None
|
||||
hosts = [self.host, *[item for item in HOSTS if item != self.host]]
|
||||
for host in hosts:
|
||||
for _ in range(2):
|
||||
try:
|
||||
payload = self._call(host, path, data or {}, auth=auth)
|
||||
self.host = host
|
||||
return payload
|
||||
return self._call(
|
||||
self.host,
|
||||
path,
|
||||
data or {},
|
||||
token=token,
|
||||
device_id=device_id,
|
||||
session_id=session_id,
|
||||
user_agent=user_agent,
|
||||
)
|
||||
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:
|
||||
def _identity(self, identity: str, auth: bool) -> tuple[str, str, str, dict]:
|
||||
if identity == "account":
|
||||
self._ensure_fingerprint()
|
||||
token = self.account_token if auth else ""
|
||||
return token, self.device_id, self.session_id, self.device_info
|
||||
if not self.guest_device_id or not self.guest_session_id:
|
||||
self.roll_guest_fingerprint()
|
||||
token = self.token if auth else ""
|
||||
return token, self.guest_device_id, self.guest_session_id, self.guest_device_info
|
||||
|
||||
def _call(
|
||||
self,
|
||||
host: str,
|
||||
path: str,
|
||||
data: dict,
|
||||
*,
|
||||
token: str,
|
||||
device_id: str,
|
||||
session_id: str,
|
||||
user_agent: str,
|
||||
) -> 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,
|
||||
"token": token,
|
||||
"deviceId": device_id,
|
||||
"data": data,
|
||||
}
|
||||
headers = {
|
||||
@@ -121,13 +232,13 @@ class HuangdouClient:
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Origin": host,
|
||||
"Referer": host + "/",
|
||||
"User-Agent": USER_AGENT,
|
||||
"User-Agent": user_agent,
|
||||
"version": APP_VERSION,
|
||||
"deviceType": DEVICE_TYPE,
|
||||
"time": now,
|
||||
"sign": sign_header(self.session_id, request_id, now, url),
|
||||
"sign": sign_header(session_id, request_id, now, url),
|
||||
"requestId": request_id,
|
||||
"sessionId": self.session_id,
|
||||
"sessionId": session_id,
|
||||
"deviceBrand": "",
|
||||
"deviceModel": "",
|
||||
"systemName": "",
|
||||
@@ -144,9 +255,18 @@ class HuangdouClient:
|
||||
if parsed.get("status") == "n":
|
||||
code = parsed.get("errorCode")
|
||||
if str(code) == "2002":
|
||||
raise TokenExpired("登录已失效")
|
||||
raise TokenExpired(str(parsed.get("error") or "登录已失效"))
|
||||
raise ApiError(str(parsed.get("error") or "网络请求异常"), code)
|
||||
return parsed.get("data")
|
||||
|
||||
|
||||
def normalize_host(host: str) -> str:
|
||||
text = (host or "").strip().rstrip("/")
|
||||
if text and "://" not in text:
|
||||
text = "https://" + text
|
||||
if text and not (text.startswith("https://") or text.startswith("http://")):
|
||||
raise RuntimeError("域名需要以 http 或 https 开头")
|
||||
return text
|
||||
|
||||
|
||||
client = HuangdouClient()
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
PAID_TYPES = {"coin", "coins", "point", "points", "pay", "money"}
|
||||
VIP_TYPES = {"vip"}
|
||||
FREE_TYPES = {"", "free", "0", "none"}
|
||||
|
||||
|
||||
def episode_kind(item: dict) -> str:
|
||||
return str(item.get("type") or "free").strip().lower()
|
||||
|
||||
|
||||
def already_bought(item: dict) -> bool:
|
||||
value = item.get("is_buy")
|
||||
if value is None or value is True:
|
||||
return True
|
||||
return str(value).strip().lower() in {"1", "y", "yes", "true"}
|
||||
|
||||
|
||||
def price_of(item: dict) -> int:
|
||||
for key in ("price", "points", "point", "integral"):
|
||||
number = _int(item.get(key))
|
||||
if number:
|
||||
return number
|
||||
return 0
|
||||
|
||||
|
||||
def paid_cost(item: dict) -> int:
|
||||
if episode_kind(item) in FREE_TYPES or already_bought(item):
|
||||
return 0
|
||||
return price_of(item)
|
||||
|
||||
|
||||
def episode_note(item: dict, *, account_vip: bool) -> tuple[bool, str, int]:
|
||||
cost = paid_cost(item)
|
||||
if cost > 0:
|
||||
return False, f"{cost} 积分", cost
|
||||
if episode_kind(item) in VIP_TYPES and not already_bought(item) and not account_vip:
|
||||
return False, "需要 VIP", 0
|
||||
return True, "", 0
|
||||
|
||||
|
||||
def public_lock_reason(item: dict, message: str) -> str:
|
||||
price = price_of(item) or _int(item.get("points"))
|
||||
text = (message or "").strip()
|
||||
if not already_bought(item) and price > 0:
|
||||
return f"{price} 积分"
|
||||
if any(word in text for word in ("不含", "权益", "解锁")):
|
||||
return "这一集暂时不能播放"
|
||||
return text or "这一集暂时不能播放"
|
||||
|
||||
|
||||
def summarize(rows) -> dict:
|
||||
coins = 0
|
||||
coin_count = 0
|
||||
free_count = 0
|
||||
vip_count = 0
|
||||
if isinstance(rows, list):
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
cost = paid_cost(item)
|
||||
if cost > 0:
|
||||
coins += cost
|
||||
coin_count += 1
|
||||
continue
|
||||
kind = episode_kind(item)
|
||||
if kind in VIP_TYPES:
|
||||
vip_count += 1
|
||||
else:
|
||||
free_count += 1
|
||||
return {
|
||||
"coins": coins,
|
||||
"coin_count": coin_count,
|
||||
"free_count": free_count,
|
||||
"vip_count": vip_count,
|
||||
}
|
||||
|
||||
|
||||
def allow_payment(pay: bool, has_account: bool, balance: int, coins: int) -> bool:
|
||||
return bool(pay and has_account and coins > 0 and balance >= coins)
|
||||
|
||||
|
||||
def keep_episode(item: dict, *, allow_paid: bool, account_vip: bool) -> bool:
|
||||
if paid_cost(item) > 0:
|
||||
return allow_paid
|
||||
if episode_kind(item) in VIP_TYPES and not already_bought(item):
|
||||
return account_vip
|
||||
return True
|
||||
|
||||
|
||||
def buy_method(item: dict) -> str:
|
||||
methods = item.get("methods")
|
||||
if not isinstance(methods, list):
|
||||
return ""
|
||||
for method in methods:
|
||||
if isinstance(method, str) and method.strip():
|
||||
return method.strip()
|
||||
if isinstance(method, dict):
|
||||
for key in ("code", "method", "type", "id", "name"):
|
||||
text = str(method.get(key) or "").strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def _int(value) -> int:
|
||||
try:
|
||||
number = int(float(str(value)))
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
return number if number > 0 else 0
|
||||
@@ -1,3 +1,4 @@
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from server.services.downloads import DownloadManager, _plain_text
|
||||
@@ -5,13 +6,31 @@ 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 login as hd_login
|
||||
from server.services.huangdou import playlist as hd_playlist
|
||||
|
||||
_pay_lock = threading.Lock()
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
|
||||
|
||||
def _load_episodes(_token, _device, drama_id: str, _locale: str = "") -> list[dict]:
|
||||
return hd_playlist.load_episodes(str(drama_id))
|
||||
return hd_playlist.load_for_download(
|
||||
str(drama_id),
|
||||
allow_paid=bool(getattr(downloads, "allow_paid", False)),
|
||||
account_vip=bool(getattr(downloads, "account_vip", False)),
|
||||
)
|
||||
|
||||
|
||||
def enqueue_download(token: str, items: list[dict], download_points: bool) -> dict:
|
||||
with _pay_lock:
|
||||
downloads.allow_paid = bool(download_points and client.account_token)
|
||||
downloads.account_vip = hd_login.account_is_vip()
|
||||
try:
|
||||
return downloads.enqueue(token, None, items)
|
||||
finally:
|
||||
downloads.allow_paid = False
|
||||
downloads.account_vip = False
|
||||
|
||||
|
||||
def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device) -> None:
|
||||
@@ -20,8 +39,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device)
|
||||
pay_type = ""
|
||||
free_episodes = ""
|
||||
vip_episodes = ""
|
||||
points_price = ""
|
||||
money = ""
|
||||
try:
|
||||
detail = api.drama_detail(str(drama_id))
|
||||
fetched = str(detail.get("name") or "").strip()
|
||||
@@ -31,8 +48,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device)
|
||||
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 = [
|
||||
@@ -42,8 +57,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device)
|
||||
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")
|
||||
|
||||
@@ -3,23 +3,45 @@ 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
|
||||
def enter(host: str = "") -> dict:
|
||||
if host:
|
||||
client.set_host(host)
|
||||
client.account_token = ""
|
||||
client.account_username = ""
|
||||
client.roll_guest_fingerprint()
|
||||
raw = api.login_device(force_new=False)
|
||||
guest = _user_from_login(raw)
|
||||
if guest:
|
||||
profile = _profile(guest)
|
||||
profile["has_login"] = ""
|
||||
profile["host"] = client.host
|
||||
else:
|
||||
profile = public_profile(None)
|
||||
client.profile = profile
|
||||
client.save()
|
||||
return {"token": client.token, "profile": profile}
|
||||
|
||||
|
||||
def login_account(username: str, password: str, rotate_fingerprint: bool = False) -> dict:
|
||||
username = (username or "").strip()
|
||||
password = password or ""
|
||||
if not username or not password:
|
||||
raise RuntimeError("请填写账号和密码")
|
||||
if not client.token:
|
||||
raise RuntimeError("请先进入")
|
||||
previous = None
|
||||
if rotate_fingerprint:
|
||||
previous = (client.device_id, client.session_id, dict(client.device_info), client.account_token)
|
||||
client.roll_account_fingerprint()
|
||||
try:
|
||||
info = api.user_info()
|
||||
except RuntimeError:
|
||||
info = raw
|
||||
profile = _profile(info if isinstance(info, dict) else raw)
|
||||
raw = api.login_username(username, password)
|
||||
info = _user_from_login(raw) or api.user_info(identity="account")
|
||||
except Exception:
|
||||
if previous is not None:
|
||||
client.device_id, client.session_id, client.device_info, client.account_token = previous
|
||||
client.save()
|
||||
raise
|
||||
profile = public_profile(info if isinstance(info, dict) else {})
|
||||
client.profile = profile
|
||||
client.save()
|
||||
return {"token": client.token, "profile": profile}
|
||||
@@ -36,17 +58,76 @@ def current(token: str) -> dict:
|
||||
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
|
||||
raise RuntimeError("登录已失效")
|
||||
account = _account_info()
|
||||
profile = public_profile(account)
|
||||
client.profile = profile
|
||||
client.save()
|
||||
return {"token": client.token, "profile": profile}
|
||||
|
||||
|
||||
def account_balance() -> int:
|
||||
if not client.account_token:
|
||||
return 0
|
||||
try:
|
||||
info = api.user_info(identity="account")
|
||||
except (TokenExpired, RuntimeError):
|
||||
return _number(client.profile.get("balance") if isinstance(client.profile, dict) else 0)
|
||||
return _number(info.get("balance") if isinstance(info, dict) else 0)
|
||||
|
||||
|
||||
def account_is_vip() -> bool:
|
||||
if not client.account_token:
|
||||
return False
|
||||
profile = client.profile if isinstance(client.profile, dict) else {}
|
||||
return _truthy(profile.get("is_vip")) or bool(profile.get("badge"))
|
||||
|
||||
|
||||
def _user_from_login(data: dict) -> dict:
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
for key in ("user", "userInfo", "user_info", "info"):
|
||||
nested = data.get(key)
|
||||
if isinstance(nested, dict) and (nested.get("id") or nested.get("username") or nested.get("nickname")):
|
||||
return nested
|
||||
if data.get("id") or data.get("username") or data.get("nickname"):
|
||||
return data
|
||||
return {}
|
||||
|
||||
|
||||
def _account_info() -> dict:
|
||||
if not client.account_token:
|
||||
return {}
|
||||
try:
|
||||
info = api.user_info(identity="account")
|
||||
except TokenExpired:
|
||||
client.account_token = ""
|
||||
client.save()
|
||||
return {}
|
||||
except RuntimeError:
|
||||
return {}
|
||||
return info if isinstance(info, dict) else {}
|
||||
|
||||
|
||||
def public_profile(account: dict | None = None) -> dict:
|
||||
if account and client.account_token:
|
||||
profile = _profile(account)
|
||||
profile["has_login"] = "1"
|
||||
profile["username"] = client.account_username or profile.get("username") or ""
|
||||
else:
|
||||
guest = {}
|
||||
if client.token:
|
||||
try:
|
||||
fetched = api.user_info()
|
||||
except (TokenExpired, RuntimeError):
|
||||
fetched = {}
|
||||
guest = fetched if isinstance(fetched, dict) else {}
|
||||
profile = _profile(guest)
|
||||
profile["has_login"] = ""
|
||||
profile["host"] = client.host
|
||||
return profile
|
||||
|
||||
|
||||
def logout(token: str) -> None:
|
||||
if token and token == client.token:
|
||||
client.clear_token()
|
||||
|
||||
@@ -1,41 +1,70 @@
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
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.huangdou.client import client
|
||||
from server.services.huangdou.coins import (
|
||||
PAID_TYPES,
|
||||
VIP_TYPES,
|
||||
already_bought,
|
||||
buy_method,
|
||||
episode_kind,
|
||||
episode_note,
|
||||
keep_episode,
|
||||
price_of,
|
||||
public_lock_reason,
|
||||
)
|
||||
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/"}
|
||||
_cache_lock = threading.Lock()
|
||||
|
||||
|
||||
def _cdn_headers() -> dict:
|
||||
return {"User-Agent": USER_AGENT, "Referer": client.host.rstrip("/") + "/"}
|
||||
|
||||
|
||||
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)
|
||||
detail = api.drama_detail(drama_id, identity=_viewer_identity())
|
||||
rows = detail.get("episodes") if isinstance(detail, dict) else None
|
||||
if not isinstance(rows, list) or not rows:
|
||||
raise RuntimeError("没有读到分集")
|
||||
fresh = _menu_rows(rows)
|
||||
if not fresh:
|
||||
raise RuntimeError("没有读到分集")
|
||||
merged = _keep_sources(_read_cache(drama_id), fresh)
|
||||
_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 {}
|
||||
drama_id = str(drama_id or "").strip()
|
||||
row = _cached_row(drama_id, cid)
|
||||
if row is None:
|
||||
row = _cached_row(drama_id, cid, refresh=True)
|
||||
if not row:
|
||||
return {}
|
||||
if not row.get("playable") or row.get("src"):
|
||||
return row
|
||||
played = _play_rows(drama_id, [dict(row)], allow_buy=False)
|
||||
updated = played[0] if played else row
|
||||
_store_row(drama_id, updated)
|
||||
return updated
|
||||
|
||||
|
||||
def playback_playlist(src: str) -> str:
|
||||
if is_direct_media(src):
|
||||
raise RuntimeError("这一集是整段视频")
|
||||
text = http.read_text(src, headers=CDN_HEADERS)
|
||||
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("#")),
|
||||
"",
|
||||
@@ -45,7 +74,7 @@ def playback_playlist(src: str) -> str:
|
||||
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)
|
||||
return _rewrite_playlist(http.read_text(variant_url, headers=_cdn_headers()), variant_url)
|
||||
|
||||
|
||||
def decode_key(value: str) -> bytes:
|
||||
@@ -122,8 +151,11 @@ def apply_hls_key(text: str, source_dir: Path, key: str) -> str:
|
||||
return "\n".join(result) + "\n"
|
||||
|
||||
|
||||
def _fetch_episodes(drama_id: str) -> list[dict]:
|
||||
detail = api.drama_detail(drama_id)
|
||||
def load_for_download(drama_id: str, *, allow_paid: bool, account_vip: bool) -> list[dict]:
|
||||
drama_id = str(drama_id or "").strip()
|
||||
if not drama_id:
|
||||
raise RuntimeError("没有这部剧")
|
||||
detail = api.drama_detail(drama_id, identity=_viewer_identity())
|
||||
rows = detail.get("episodes") if isinstance(detail, dict) else None
|
||||
if not isinstance(rows, list) or not rows:
|
||||
raise RuntimeError("没有读到分集")
|
||||
@@ -131,36 +163,89 @@ def _fetch_episodes(drama_id: str) -> list[dict]:
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
seq = _int(item.get("seq"))
|
||||
if seq <= 0:
|
||||
if not keep_episode(item, allow_paid=allow_paid, account_vip=account_vip):
|
||||
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": "",
|
||||
})
|
||||
row = _skeleton_row(item, account_vip=account_vip)
|
||||
if row:
|
||||
skeleton.append(row)
|
||||
return _play_rows(drama_id, skeleton, allow_buy=allow_paid)
|
||||
|
||||
|
||||
def _viewer_identity() -> str:
|
||||
return "account" if client.account_token else "guest"
|
||||
|
||||
|
||||
def _menu_rows(rows: list) -> list[dict]:
|
||||
from server.services.huangdou.login import account_is_vip
|
||||
|
||||
vip = account_is_vip()
|
||||
skeleton = []
|
||||
for item in rows:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
row = _skeleton_row(item, account_vip=vip)
|
||||
if row:
|
||||
skeleton.append(row)
|
||||
return skeleton
|
||||
|
||||
|
||||
def _skeleton_row(item: dict, *, account_vip: bool) -> dict | None:
|
||||
seq = _int(item.get("seq"))
|
||||
if seq <= 0:
|
||||
return None
|
||||
kind = str(item.get("type") or "free").strip() or "free"
|
||||
playable, reason, points = episode_note(item, account_vip=account_vip)
|
||||
return {
|
||||
"cid": seq,
|
||||
"idx": seq,
|
||||
"title": str(item.get("name") or f"第{seq}集").strip() or f"第{seq}集",
|
||||
"src": "",
|
||||
"type": kind,
|
||||
"price": price_of(item),
|
||||
"points": points,
|
||||
"playable": playable,
|
||||
"needs_coin": points > 0,
|
||||
"is_buy": item.get("is_buy"),
|
||||
"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": reason,
|
||||
}
|
||||
|
||||
|
||||
def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[dict]:
|
||||
if not skeleton:
|
||||
raise RuntimeError("没有读到分集")
|
||||
return []
|
||||
|
||||
def play_one(row: dict) -> dict:
|
||||
if row.get("needs_coin") and not already_bought(row):
|
||||
if not allow_buy or not client.account_token:
|
||||
row["src"] = ""
|
||||
row["playable"] = False
|
||||
row["locked_reason"] = public_lock_reason(row, row.get("locked_reason") or "")
|
||||
return row
|
||||
try:
|
||||
api.drama_buy(drama_id, int(row["cid"]), buy_method(row))
|
||||
except RuntimeError as exc:
|
||||
row["src"] = ""
|
||||
row["playable"] = False
|
||||
row["locked_reason"] = public_lock_reason(row, str(exc))
|
||||
return row
|
||||
row["is_buy"] = True
|
||||
row["needs_coin"] = False
|
||||
row["points"] = 0
|
||||
identity = "account" if _uses_account(row) else "guest"
|
||||
try:
|
||||
played = api.drama_play(drama_id, int(row["cid"]))
|
||||
played = api.drama_play(drama_id, int(row["cid"]), identity=identity)
|
||||
except RuntimeError as exc:
|
||||
row["locked_reason"] = str(exc) or "这一集暂时不能下载"
|
||||
row["src"] = ""
|
||||
row["playable"] = False
|
||||
row["locked_reason"] = public_lock_reason(row, str(exc))
|
||||
return row
|
||||
preview = str(played.get("preview_m3u8") or "").strip()
|
||||
row["hls_key"] = str(played.get("hls_key") or "").strip()
|
||||
@@ -171,10 +256,13 @@ def _fetch_episodes(drama_id: str) -> list[dict]:
|
||||
row["src"] = src
|
||||
row["src_kind"] = kind
|
||||
if src:
|
||||
row["playable"] = True
|
||||
if kind == "file" or row["is_preview"]:
|
||||
row["is_preview"] = True
|
||||
row["locked_reason"] = "当前账号只能下到试看"
|
||||
row["locked_reason"] = ""
|
||||
row["points"] = 0
|
||||
else:
|
||||
row["playable"] = False
|
||||
row["locked_reason"] = _lock_reason(row)
|
||||
return row
|
||||
|
||||
@@ -190,41 +278,66 @@ def _fetch_episodes(drama_id: str) -> list[dict]:
|
||||
return updated
|
||||
|
||||
|
||||
def _uses_account(row: dict) -> bool:
|
||||
if not client.account_token:
|
||||
return False
|
||||
kind = episode_kind(row)
|
||||
if kind in VIP_TYPES:
|
||||
return True
|
||||
if kind in PAID_TYPES or _int(row.get("price")) > 0:
|
||||
return bool(already_bought(row) or row.get("needs_coin"))
|
||||
return False
|
||||
|
||||
|
||||
def _lock_reason(row: dict) -> str:
|
||||
kind = str(row.get("type") or "free")
|
||||
if kind in {"vip", "VIP"}:
|
||||
if _int(row.get("points") or row.get("price")) > 0 and not already_bought(row):
|
||||
return public_lock_reason(row, "")
|
||||
kind = episode_kind(row)
|
||||
if kind in VIP_TYPES:
|
||||
return "需要 VIP"
|
||||
if kind in {"coin", "points", "point", "pay"}:
|
||||
return "需要积分或付费"
|
||||
if not row.get("is_buy"):
|
||||
return "尚未购买"
|
||||
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 _cached_row(drama_id: str, cid: int, *, refresh: bool = False) -> dict | None:
|
||||
rows = load_episodes(drama_id) if refresh else _read_cache(drama_id)
|
||||
for ep in rows:
|
||||
if int(ep.get("cid") or 0) == int(cid):
|
||||
return ep
|
||||
return None
|
||||
|
||||
|
||||
def _keep_sources(cached: list[dict], fresh: list[dict]) -> list[dict]:
|
||||
previous = {int(ep.get("cid") or 0): ep for ep in cached if int(ep.get("cid") or 0) > 0}
|
||||
merged = []
|
||||
for row in fresh:
|
||||
old = previous.get(int(row["cid"]))
|
||||
if old and old.get("is_preview"):
|
||||
row["is_preview"] = True
|
||||
if row.get("playable") and old and old.get("src") and not old.get("is_preview"):
|
||||
row["src"] = old.get("src") or ""
|
||||
row["src_kind"] = old.get("src_kind") or ""
|
||||
row["hls_key"] = old.get("hls_key") or ""
|
||||
row["preview_seconds"] = old.get("preview_seconds") or 0
|
||||
row["preview_m3u8"] = old.get("preview_m3u8") or ""
|
||||
merged.append(row)
|
||||
return merged
|
||||
|
||||
|
||||
def _store_row(drama_id: str, row: dict) -> None:
|
||||
with _cache_lock:
|
||||
rows = _read_cache(drama_id)
|
||||
cid = int(row.get("cid") or 0)
|
||||
replaced = False
|
||||
updated = []
|
||||
for item in rows:
|
||||
if int(item.get("cid") or 0) == cid:
|
||||
updated.append(row)
|
||||
replaced = True
|
||||
else:
|
||||
updated.append(item)
|
||||
if not replaced:
|
||||
updated.append(row)
|
||||
_write_cache(drama_id, updated)
|
||||
|
||||
|
||||
def _read_cache(drama_id: str) -> list[dict]:
|
||||
|
||||
Generated
+13
-13
@@ -2701,19 +2701,6 @@ version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "raptdrama"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-opener",
|
||||
"webview2-com",
|
||||
"windows-core 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raw-window-handle"
|
||||
version = "0.6.2"
|
||||
@@ -4129,6 +4116,19 @@ version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "videosdowntools"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-opener",
|
||||
"webview2-com",
|
||||
"windows-core 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vswhom"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
[package]
|
||||
name = "raptdrama"
|
||||
name = "videosdowntools"
|
||||
version = "0.1.0"
|
||||
description = "RaptDrama desktop shell"
|
||||
description = "VideosDownTools desktop shell"
|
||||
authors = ["nixevol"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[[bin]]
|
||||
name = "VideosDownTools"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
# The `_lib` suffix may seem redundant but it is necessary
|
||||
# to make the lib name unique and wouldn't conflict with the bin name.
|
||||
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
|
||||
name = "raptdrama_lib"
|
||||
name = "videosdowntools_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>RaptDrama Download Tools</title>
|
||||
<title>VideosDownTools</title>
|
||||
<style>
|
||||
html, body { height: 100%; margin: 0; background: #101014; color: #f2f2f2; font: 16px/1.5 "Segoe UI", sans-serif; }
|
||||
body { display: flex; align-items: center; justify-content: center; }
|
||||
@@ -13,7 +13,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>RaptDrama</h1>
|
||||
<h1>VideosDownTools</h1>
|
||||
<p id="status">程序正在启动</p>
|
||||
</main>
|
||||
<script>
|
||||
|
||||
@@ -242,7 +242,7 @@ fn boot(handle: &AppHandle, window: &tauri::WebviewWindow) -> Result<(), String>
|
||||
while Instant::now() < deadline {
|
||||
if health_ok(port) {
|
||||
let url = Url::parse(&format!("http://127.0.0.1:{port}/")).map_err(|err| err.to_string())?;
|
||||
eprintln!("RaptDrama http://127.0.0.1:{port}/");
|
||||
eprintln!("VideosDownTools http://127.0.0.1:{port}/");
|
||||
let _ = std::io::Write::flush(&mut std::io::stderr());
|
||||
window.navigate(url).map_err(|err| err.to_string())?;
|
||||
return Ok(());
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
raptdrama_lib::run()
|
||||
videosdowntools_lib::run()
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "RaptDrama",
|
||||
"productName": "VideosDownTools",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.raptdrama.desktop",
|
||||
"identifier": "com.videosdowntools.desktop",
|
||||
"build": {
|
||||
"beforeDevCommand": {
|
||||
"script": "npm run build --prefix ui",
|
||||
@@ -19,7 +19,7 @@
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "RaptDrama Download Tools",
|
||||
"title": "VideosDownTools",
|
||||
"width": 1080,
|
||||
"height": 800,
|
||||
"center": true,
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
from server.services.huangdou.client import normalize_host
|
||||
from server.services.huangdou.coins import allow_payment, episode_note, keep_episode, paid_cost, public_lock_reason, summarize
|
||||
|
||||
|
||||
def test_paid_cost_sums_only_unbought_coin_episodes() -> None:
|
||||
rows = [
|
||||
{"type": "free", "price": 0, "is_buy": False},
|
||||
{"type": "vip", "price": 0, "is_buy": False},
|
||||
{"type": "coin", "price": 10, "is_buy": False},
|
||||
{"type": "points", "price": 5, "is_buy": False},
|
||||
{"type": "coin", "price": 8, "is_buy": True},
|
||||
{"type": "coin", "price": 7, "is_buy": None},
|
||||
{"type": "coin", "price": 9, "is_buy": "n"},
|
||||
{"type": "coin", "price": 4, "is_buy": "y"},
|
||||
]
|
||||
assert paid_cost(rows[2]) == 10
|
||||
assert paid_cost(rows[3]) == 5
|
||||
assert paid_cost(rows[4]) == 0
|
||||
assert paid_cost(rows[5]) == 0
|
||||
assert paid_cost(rows[6]) == 9
|
||||
assert paid_cost(rows[7]) == 0
|
||||
assert summarize(rows)["coins"] == 24
|
||||
assert summarize(rows)["coin_count"] == 3
|
||||
assert summarize(rows)["vip_count"] == 1
|
||||
|
||||
|
||||
def test_payment_and_episode_choice() -> None:
|
||||
free = {"type": "free", "price": 0, "is_buy": True}
|
||||
vip = {"type": "vip", "price": 0, "is_buy": False}
|
||||
coin = {"type": "coin", "price": 12, "is_buy": False}
|
||||
assert allow_payment(True, True, 20, 12) is True
|
||||
assert allow_payment(True, True, 11, 12) is False
|
||||
assert allow_payment(False, True, 20, 12) is False
|
||||
assert keep_episode(free, allow_paid=False, account_vip=False) is True
|
||||
assert keep_episode(vip, allow_paid=False, account_vip=False) is False
|
||||
assert keep_episode(vip, allow_paid=False, account_vip=True) is True
|
||||
assert keep_episode(coin, allow_paid=False, account_vip=True) is False
|
||||
assert keep_episode(coin, allow_paid=True, account_vip=True) is True
|
||||
bought = {"type": "coin", "price": 12, "is_buy": True}
|
||||
priced_vip = {"type": "vip", "price": 6, "is_buy": False}
|
||||
assert keep_episode(bought, allow_paid=False, account_vip=False) is True
|
||||
assert keep_episode(priced_vip, allow_paid=False, account_vip=True) is False
|
||||
assert episode_note(priced_vip, account_vip=True) == (False, "6 积分", 6)
|
||||
assert episode_note(bought, account_vip=False)[0] is True
|
||||
assert public_lock_reason(
|
||||
{"type": "vip", "price": 6, "is_buy": False},
|
||||
"创作者作品需单独解锁(会员权益不含创作者作品)",
|
||||
) == "6 积分"
|
||||
assert public_lock_reason(bought, "创作者作品需单独解锁(会员权益不含创作者作品)") == "这一集暂时不能播放"
|
||||
|
||||
|
||||
def test_account_login_reuses_the_same_device_fingerprint() -> None:
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from server.services.huangdou import client as client_module
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "session.json"
|
||||
with patch.object(client_module, "SESSION_PATH", path):
|
||||
first = client_module.HuangdouClient()
|
||||
device_id = first.device_id
|
||||
session_id = first.session_id
|
||||
info = dict(first.device_info)
|
||||
assert device_id
|
||||
assert session_id
|
||||
assert info.get("userAgent")
|
||||
guest_device, guest_session = first._identity("guest", False)[1:3]
|
||||
assert guest_device
|
||||
assert guest_device != device_id
|
||||
assert guest_session != session_id
|
||||
assert first._identity("account", False)[1] == device_id
|
||||
again_device, again_session = first._identity("guest", False)[1:3]
|
||||
assert again_device == guest_device
|
||||
assert again_session == guest_session
|
||||
first.roll_guest_fingerprint()
|
||||
rolled_device = first._identity("guest", False)[1]
|
||||
assert rolled_device != guest_device
|
||||
assert first.device_id == device_id
|
||||
first.roll_account_fingerprint()
|
||||
assert first.device_id != device_id
|
||||
assert first.session_id != session_id
|
||||
assert first._identity("account", False)[1] == first.device_id
|
||||
account_device = first.device_id
|
||||
account_session = first.session_id
|
||||
first.set_host("https://example.com")
|
||||
assert first.device_id == account_device
|
||||
second = client_module.HuangdouClient()
|
||||
assert second.device_id == account_device
|
||||
assert second.session_id == account_session
|
||||
assert second._identity("account", True)[1] == account_device
|
||||
assert second.guest_device_id == rolled_device
|
||||
|
||||
|
||||
def test_saved_accounts_roundtrip() -> None:
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from server.services.huangdou import accounts as accounts_module
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "accounts.json"
|
||||
with patch.object(accounts_module, "PATH", path):
|
||||
saved = accounts_module.replace(
|
||||
[
|
||||
{"username": "13800000001", "password": "secret-one", "nickname": "甲"},
|
||||
{"username": " 13800000001 ", "password": "secret-one", "nickname": "重复"},
|
||||
{"username": "", "password": "x", "nickname": ""},
|
||||
]
|
||||
)
|
||||
assert [item["username"] for item in saved] == ["13800000001"]
|
||||
assert accounts_module.load()[0]["nickname"] == "甲"
|
||||
assert accounts_module.load()[0]["password"] == "secret-one"
|
||||
|
||||
|
||||
def test_host_keeps_scheme() -> None:
|
||||
assert normalize_host("pmihlvee.cc") == "https://pmihlvee.cc"
|
||||
assert normalize_host("https://example.com/") == "https://example.com"
|
||||
assert normalize_host("") == ""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_paid_cost_sums_only_unbought_coin_episodes()
|
||||
test_payment_and_episode_choice()
|
||||
test_account_login_reuses_the_same_device_fingerprint()
|
||||
test_saved_accounts_roundtrip()
|
||||
test_host_keeps_scheme()
|
||||
print("ok")
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>RaptDrama Download Tools</title>
|
||||
<title>VideosDownTools</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
Generated
+2
-2
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "raptdrama-ui",
|
||||
"name": "videosdowntools-ui",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "raptdrama-ui",
|
||||
"name": "videosdowntools-ui",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2",
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "raptdrama-ui",
|
||||
"name": "videosdowntools-ui",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
|
||||
+297
-12
@@ -30,6 +30,7 @@ interface Profile {
|
||||
balance?: string | number;
|
||||
is_vip?: string | number;
|
||||
has_login?: string;
|
||||
host?: string;
|
||||
country?: string;
|
||||
language?: string;
|
||||
native?: string;
|
||||
@@ -51,6 +52,12 @@ interface SavedAccount {
|
||||
uid: string;
|
||||
}
|
||||
|
||||
interface HuangdouAccount {
|
||||
username: string;
|
||||
password: string;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
interface DeviceProfile {
|
||||
brand: string;
|
||||
model: string;
|
||||
@@ -92,6 +99,9 @@ const SESSION_DEVICE_KEY = "rapt-device";
|
||||
const ACCOUNTS_KEY = "rapt-accounts";
|
||||
const PLATFORM_KEY = "rapt-platform";
|
||||
const DRAMABOX_LANG_KEY = "dramabox-language";
|
||||
const HUANGDOU_HOST_KEY = "huangdou-host";
|
||||
const HUANGDOU_ACCOUNTS_KEY = "huangdou-accounts";
|
||||
const HUANGDOU_REMEMBER_KEY = "huangdou-remember";
|
||||
const DRAMABOX_DEVICE_KEY = "dramabox-device";
|
||||
|
||||
const themeOverrides: GlobalThemeOverrides = {
|
||||
@@ -113,11 +123,19 @@ const apiBase = computed(() => {
|
||||
return "/api";
|
||||
});
|
||||
const platformLabel = computed(() => {
|
||||
const name = platforms.find((item) => item.key === platform.value)?.label || "RaptDrama";
|
||||
const name = platforms.find((item) => item.key === platform.value)?.label || "VideosDownTools";
|
||||
if (platform.value === "dramabox" && profile.value?.nickname) return `${name} · ${profile.value.nickname}`;
|
||||
return name;
|
||||
});
|
||||
const dramaboxLang = ref("th");
|
||||
const huangdouHost = ref(readHuangdouHost());
|
||||
const huangdouUser = ref("");
|
||||
const huangdouPassword = ref("");
|
||||
const huangdouRemember = ref(readHuangdouRemember());
|
||||
const huangdouAccounts = ref<HuangdouAccount[]>([]);
|
||||
const huangdouSelected = ref<string | null>(null);
|
||||
const huangdouFingerprintBusy = ref(false);
|
||||
const huangdouFingerprintNote = ref("");
|
||||
const dramaboxLangs = ref<{ label: string; value: string }[]>([]);
|
||||
const accountBusy = ref(false);
|
||||
const activeProxyUrl = ref("");
|
||||
@@ -193,6 +211,68 @@ const menuValue = computed(() => {
|
||||
return page.value;
|
||||
});
|
||||
|
||||
function currentBrowserFingerprint() {
|
||||
const ua = navigator.userAgent || "";
|
||||
let browserName = "Chrome";
|
||||
if (ua.includes("Edg/")) browserName = "Edge";
|
||||
else if (ua.includes("Firefox/")) browserName = "Firefox";
|
||||
else if (ua.includes("Safari/") && !ua.includes("Chrome/")) browserName = "Safari";
|
||||
return {
|
||||
browserName,
|
||||
language: navigator.language || "zh-CN",
|
||||
userAgent: ua,
|
||||
platform: navigator.platform || "Win32",
|
||||
};
|
||||
}
|
||||
|
||||
async function sendHuangdouFingerprint() {
|
||||
try {
|
||||
await fetch("/api/huangdou/fingerprint", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(currentBrowserFingerprint()),
|
||||
});
|
||||
} catch {
|
||||
// 首次指纹沿用代码里的默认值
|
||||
}
|
||||
}
|
||||
|
||||
async function rollHuangdouFingerprint() {
|
||||
huangdouFingerprintNote.value = "";
|
||||
error.value = "";
|
||||
huangdouFingerprintBusy.value = true;
|
||||
try {
|
||||
const response = await fetch("/api/huangdou/fingerprint/roll", { method: "POST" });
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(typeof payload.detail === "string" ? payload.detail : "更换失败");
|
||||
}
|
||||
huangdouFingerprintNote.value = "已更换设备指纹";
|
||||
} catch (exc) {
|
||||
error.value = exc instanceof Error ? exc.message : "更换失败";
|
||||
} finally {
|
||||
huangdouFingerprintBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function readHuangdouRemember() {
|
||||
try {
|
||||
return localStorage.getItem(HUANGDOU_REMEMBER_KEY) !== "0";
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function readHuangdouHost() {
|
||||
try {
|
||||
const value = localStorage.getItem(HUANGDOU_HOST_KEY) || "";
|
||||
if (value.trim()) return value.trim();
|
||||
} catch {
|
||||
// 沿用默认域名
|
||||
}
|
||||
return "https://pmihlvee.cc";
|
||||
}
|
||||
|
||||
function readPlatform(): Platform {
|
||||
try {
|
||||
const value = localStorage.getItem(PLATFORM_KEY);
|
||||
@@ -212,6 +292,7 @@ function selectPlatform(key: string) {
|
||||
void loadDramaboxLanguages();
|
||||
void loadDevices();
|
||||
}
|
||||
if (key === "huangdou") void sendHuangdouFingerprint();
|
||||
}
|
||||
|
||||
function tokenKey() {
|
||||
@@ -310,6 +391,18 @@ const methods: { id: Method; label: string }[] = [
|
||||
{ id: "adb", label: "ADB" },
|
||||
];
|
||||
|
||||
const profileSub = computed(() => {
|
||||
if (!profile.value) return "";
|
||||
if (platform.value === "huangdou") {
|
||||
if (profile.value.has_login === "1") {
|
||||
return profile.value.username || profile.value.phone || profile.value.email || "";
|
||||
}
|
||||
return "访客";
|
||||
}
|
||||
if (platform.value === "dramabox") return profile.value.native || profile.value.email || "";
|
||||
return profile.value.email || "未绑定邮箱";
|
||||
});
|
||||
|
||||
const accountFields = computed(() => {
|
||||
if (platform.value === "huangdou") {
|
||||
return [
|
||||
@@ -631,6 +724,13 @@ const accountOptions = computed(() =>
|
||||
})),
|
||||
);
|
||||
|
||||
const huangdouAccountOptions = computed(() =>
|
||||
huangdouAccounts.value.map((item) => ({
|
||||
label: item.nickname ? `${item.nickname} · ${item.username}` : item.username,
|
||||
value: item.username,
|
||||
})),
|
||||
);
|
||||
|
||||
function readList<T>(key: string): T[] {
|
||||
try {
|
||||
const data = JSON.parse(localStorage.getItem(key) || "[]");
|
||||
@@ -678,6 +778,91 @@ function saveAccount(info: Profile) {
|
||||
selectedAccount.value = next.email;
|
||||
}
|
||||
|
||||
let huangdouAccountsReady = false;
|
||||
let huangdouAccountTimer = 0;
|
||||
|
||||
function writeHuangdouAccounts() {
|
||||
window.clearTimeout(huangdouAccountTimer);
|
||||
huangdouAccountTimer = window.setTimeout(() => {
|
||||
const accounts = huangdouAccounts.value.map((item) => ({
|
||||
username: item.username,
|
||||
password: item.password,
|
||||
nickname: item.nickname || "",
|
||||
}));
|
||||
void fetch("/api/huangdou/accounts", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ accounts }),
|
||||
});
|
||||
}, 200);
|
||||
}
|
||||
|
||||
function usableHuangdouAccounts(rows: HuangdouAccount[]) {
|
||||
return rows.filter((item) => Boolean(item?.username) && typeof item.password === "string" && item.password);
|
||||
}
|
||||
|
||||
async function loadHuangdouAccounts() {
|
||||
const local = usableHuangdouAccounts(readList<HuangdouAccount>(HUANGDOU_ACCOUNTS_KEY));
|
||||
let remote: HuangdouAccount[] = [];
|
||||
try {
|
||||
const response = await fetch("/api/huangdou/accounts");
|
||||
if (response.ok) {
|
||||
const payload = await response.json();
|
||||
remote = usableHuangdouAccounts(Array.isArray(payload.accounts) ? payload.accounts : []);
|
||||
}
|
||||
} catch {
|
||||
remote = [];
|
||||
}
|
||||
huangdouAccounts.value = remote.length ? remote : local;
|
||||
if (!remote.length && local.length) writeHuangdouAccounts();
|
||||
if (huangdouAccounts.value[0]) applyHuangdouAccount(huangdouAccounts.value[0].username);
|
||||
}
|
||||
|
||||
function applyHuangdouAccount(username: string) {
|
||||
const found = huangdouAccounts.value.find((item) => item.username === username);
|
||||
if (!found) return;
|
||||
huangdouSelected.value = found.username;
|
||||
huangdouUser.value = found.username;
|
||||
huangdouPassword.value = found.password;
|
||||
huangdouRemember.value = true;
|
||||
}
|
||||
|
||||
function removeHuangdouAccount() {
|
||||
if (!huangdouSelected.value) return;
|
||||
const removing = huangdouSelected.value;
|
||||
huangdouAccounts.value = huangdouAccounts.value.filter((item) => item.username !== removing);
|
||||
writeHuangdouAccounts();
|
||||
if (huangdouUser.value === removing) {
|
||||
huangdouUser.value = "";
|
||||
huangdouPassword.value = "";
|
||||
}
|
||||
huangdouSelected.value = huangdouAccounts.value[0]?.username ?? null;
|
||||
if (huangdouSelected.value) applyHuangdouAccount(huangdouSelected.value);
|
||||
}
|
||||
|
||||
function saveHuangdouAccount(info: Profile) {
|
||||
const username = huangdouUser.value.trim();
|
||||
if (!username || !huangdouPassword.value) return;
|
||||
const next: HuangdouAccount = {
|
||||
username,
|
||||
password: huangdouPassword.value,
|
||||
nickname: info.nickname || info.username || "",
|
||||
};
|
||||
huangdouAccounts.value = [next, ...huangdouAccounts.value.filter((item) => item.username !== username)];
|
||||
writeHuangdouAccounts();
|
||||
huangdouSelected.value = username;
|
||||
}
|
||||
|
||||
function forgetHuangdouAccount(username: string) {
|
||||
const name = username.trim();
|
||||
if (!name) return;
|
||||
const next = huangdouAccounts.value.filter((item) => item.username !== name);
|
||||
if (next.length === huangdouAccounts.value.length) return;
|
||||
huangdouAccounts.value = next;
|
||||
writeHuangdouAccounts();
|
||||
if (huangdouSelected.value === name) huangdouSelected.value = next[0]?.username ?? null;
|
||||
}
|
||||
|
||||
function profileText(key: keyof Profile) {
|
||||
if (key === "loginType") {
|
||||
const kind = String(profile.value?.loginType || "").trim().toLowerCase();
|
||||
@@ -772,15 +957,82 @@ watch(method, (value) => {
|
||||
if (value === "adb") loadDevices();
|
||||
});
|
||||
|
||||
async function loginHuangdou() {
|
||||
watch(huangdouRemember, (value) => {
|
||||
try {
|
||||
localStorage.setItem(HUANGDOU_REMEMBER_KEY, value ? "1" : "0");
|
||||
} catch {
|
||||
// 勾选状态只影响本机
|
||||
}
|
||||
});
|
||||
|
||||
watch(huangdouUser, (value) => {
|
||||
const found = huangdouAccounts.value.find((item) => item.username === value.trim());
|
||||
huangdouSelected.value = found ? found.username : null;
|
||||
});
|
||||
|
||||
watch([huangdouRemember, huangdouUser, huangdouPassword], () => {
|
||||
if (!huangdouAccountsReady) return;
|
||||
const username = huangdouUser.value.trim();
|
||||
if (!username) return;
|
||||
if (huangdouRemember.value && huangdouPassword.value) {
|
||||
const existing = huangdouAccounts.value.find((item) => item.username === username);
|
||||
if (
|
||||
existing &&
|
||||
existing.password === huangdouPassword.value &&
|
||||
huangdouAccounts.value[0]?.username === username
|
||||
) {
|
||||
huangdouSelected.value = username;
|
||||
return;
|
||||
}
|
||||
huangdouAccounts.value = [
|
||||
{
|
||||
username,
|
||||
password: huangdouPassword.value,
|
||||
nickname: existing?.nickname || "",
|
||||
},
|
||||
...huangdouAccounts.value.filter((item) => item.username !== username),
|
||||
];
|
||||
huangdouSelected.value = username;
|
||||
writeHuangdouAccounts();
|
||||
return;
|
||||
}
|
||||
if (!huangdouRemember.value) {
|
||||
const next = huangdouAccounts.value.filter((item) => item.username !== username);
|
||||
if (next.length === huangdouAccounts.value.length) return;
|
||||
huangdouAccounts.value = next;
|
||||
if (huangdouSelected.value === username) huangdouSelected.value = next[0]?.username ?? null;
|
||||
writeHuangdouAccounts();
|
||||
}
|
||||
});
|
||||
|
||||
async function loginHuangdou(asGuest = false) {
|
||||
error.value = "";
|
||||
if (!asGuest && (!huangdouUser.value.trim() || !huangdouPassword.value)) {
|
||||
error.value = "请填写账号和密码";
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
const response = await fetch("/api/huangdou/login/device", { method: "POST" });
|
||||
const host = huangdouHost.value.trim() || "https://pmihlvee.cc";
|
||||
huangdouHost.value = host;
|
||||
localStorage.setItem(HUANGDOU_HOST_KEY, host);
|
||||
const response = await fetch("/api/huangdou/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
host,
|
||||
username: asGuest ? "" : huangdouUser.value.trim(),
|
||||
password: asGuest ? "" : huangdouPassword.value,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json();
|
||||
if (!response.ok) {
|
||||
throw new Error(typeof payload.detail === "string" ? payload.detail : "登录失败");
|
||||
}
|
||||
if (!asGuest) {
|
||||
if (huangdouRemember.value) saveHuangdouAccount(payload.profile || {});
|
||||
else forgetHuangdouAccount(huangdouUser.value);
|
||||
}
|
||||
token.value = payload.token;
|
||||
profile.value = payload.profile;
|
||||
writeSavedToken(payload.token);
|
||||
@@ -868,7 +1120,7 @@ async function loginDramabox() {
|
||||
|
||||
async function login() {
|
||||
if (platform.value === "huangdou") {
|
||||
await loginHuangdou();
|
||||
await loginHuangdou(false);
|
||||
return;
|
||||
}
|
||||
if (platform.value === "dramabox") {
|
||||
@@ -974,6 +1226,9 @@ async function logout() {
|
||||
token.value = "";
|
||||
profile.value = null;
|
||||
page.value = "download";
|
||||
if (platform.value === "huangdou" && huangdouAccounts.value.length) {
|
||||
applyHuangdouAccount(huangdouSelected.value || huangdouAccounts.value[0].username);
|
||||
}
|
||||
forgetSavedToken();
|
||||
sessionStorage.removeItem(SESSION_DEVICE_KEY);
|
||||
try {
|
||||
@@ -1043,7 +1298,7 @@ async function confirmQuit() {
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
document.title = "RaptDrama Download Tools";
|
||||
document.title = "VideosDownTools";
|
||||
void watchClose();
|
||||
await loadDeviceDefaults();
|
||||
loadSettings();
|
||||
@@ -1054,10 +1309,13 @@ onMounted(async () => {
|
||||
}
|
||||
savedAccounts.value = readList<SavedAccount>(ACCOUNTS_KEY);
|
||||
if (savedAccounts.value[0]) applyAccount(savedAccounts.value[0].email);
|
||||
await loadHuangdouAccounts();
|
||||
huangdouAccountsReady = true;
|
||||
if (platform.value === "dramabox") {
|
||||
await loadDramaboxLanguages();
|
||||
void loadDevices();
|
||||
}
|
||||
if (platform.value === "huangdou") void sendHuangdouFingerprint();
|
||||
let saved = readSavedToken();
|
||||
if (!saved && isolated.value) {
|
||||
try {
|
||||
@@ -1182,6 +1440,7 @@ onUnmounted(stopLive);
|
||||
:device="sessionDevice()"
|
||||
:api-base="apiBase"
|
||||
:remote-search="isolated"
|
||||
:show-point-download="platform === 'huangdou'"
|
||||
@started="page = 'progress'"
|
||||
@play="openPlay"
|
||||
/>
|
||||
@@ -1205,8 +1464,9 @@ onUnmounted(stopLive);
|
||||
<div class="profile-name-row">
|
||||
<span class="profile-name">{{ profile.nickname || "未命名" }}</span>
|
||||
<n-tag v-if="profile.badge" size="small" :bordered="false" type="success">{{ profile.badge }}</n-tag>
|
||||
<n-tag v-if="platform === 'huangdou'" size="small" :bordered="false" :type="profile.has_login === '1' ? 'success' : 'default'">{{ profile.has_login === "1" ? "已登录" : "访客" }}</n-tag>
|
||||
</div>
|
||||
<span class="profile-sub">{{ profile.email || (platform === "dramabox" ? profile.native || "" : "未绑定邮箱") }}</span>
|
||||
<span class="profile-sub">{{ profileSub }}</span>
|
||||
</div>
|
||||
<n-tooltip placement="bottom">
|
||||
<template #trigger>
|
||||
@@ -1271,6 +1531,35 @@ onUnmounted(stopLive);
|
||||
<n-tab v-for="item in methods" :key="item.id" :name="item.id">{{ item.label }}</n-tab>
|
||||
</n-tabs>
|
||||
<n-form label-placement="left" label-width="96" size="small" :show-feedback="false" @submit.prevent="login">
|
||||
<template v-if="platform === 'huangdou'">
|
||||
<n-form-item label="域名">
|
||||
<n-input v-model:value="huangdouHost" placeholder="https://pmihlvee.cc" />
|
||||
</n-form-item>
|
||||
<n-form-item v-if="huangdouAccounts.length" label="已保存">
|
||||
<div class="device-line">
|
||||
<n-select
|
||||
:value="huangdouSelected"
|
||||
:options="huangdouAccountOptions"
|
||||
placeholder="选择已保存的账号"
|
||||
@update:value="applyHuangdouAccount"
|
||||
/>
|
||||
<n-button attr-type="button" :disabled="!huangdouSelected" @click="removeHuangdouAccount">删除</n-button>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-form-item label="账号">
|
||||
<n-input v-model:value="huangdouUser" placeholder="手机号或邮箱" autocomplete="username" />
|
||||
</n-form-item>
|
||||
<n-form-item label="密码">
|
||||
<n-input v-model:value="huangdouPassword" type="password" show-password-on="click" placeholder="密码" autocomplete="current-password" />
|
||||
</n-form-item>
|
||||
<n-form-item label="记住">
|
||||
<n-checkbox v-model:checked="huangdouRemember">记住账号密码</n-checkbox>
|
||||
</n-form-item>
|
||||
<n-form-item label="指纹">
|
||||
<n-button attr-type="button" secondary :loading="huangdouFingerprintBusy" @click="rollHuangdouFingerprint">更换新设备指纹</n-button>
|
||||
</n-form-item>
|
||||
<n-text v-if="huangdouFingerprintNote" class="hint" depth="3">{{ huangdouFingerprintNote }}</n-text>
|
||||
</template>
|
||||
<n-form-item v-if="platform === 'dramabox'" label="地区">
|
||||
<n-select v-model:value="dramaboxLang" filterable :options="dramaboxLangs" placeholder="选择国家 / 语言" />
|
||||
</n-form-item>
|
||||
@@ -1315,15 +1604,11 @@ onUnmounted(stopLive);
|
||||
<n-button :loading="devicesBusy" @click="probeMumu">探测 MuMu</n-button>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<n-text v-if="platform === 'dramabox' && !devicesBusy && devices.length === 0" class="hint" depth="3">当前没有可用设备,可先访客进入。</n-text>
|
||||
<n-text v-if="platform === 'dramabox'" class="hint" depth="3">选好地区后点访客进入即可浏览。解锁内容和下载请先从设备登录。</n-text>
|
||||
<n-text v-if="platform === 'rapt' && method === 'guest'" 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="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>
|
||||
<div class="login-actions">
|
||||
<n-button v-if="platform === 'dramabox'" attr-type="button" secondary :loading="busy" :disabled="!dramaboxDeviceReady" @click="loginDramaboxAdb">从设备登录</n-button>
|
||||
<n-button type="primary" attr-type="submit" :loading="busy">{{ platform === "dramabox" ? "访客进入" : isolated ? "进入" : "登录" }}</n-button>
|
||||
<n-button v-if="platform === 'huangdou'" attr-type="button" secondary :loading="busy" @click="loginHuangdou(true)">访客进入</n-button>
|
||||
<n-button type="primary" attr-type="submit" :loading="busy">{{ platform === "dramabox" ? "访客进入" : platform === "huangdou" ? "登录" : isolated ? "进入" : "登录" }}</n-button>
|
||||
</div>
|
||||
</n-form>
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@ interface Episode {
|
||||
idx: number;
|
||||
title: string;
|
||||
playable: boolean;
|
||||
points?: number;
|
||||
media?: string;
|
||||
locked_reason?: string;
|
||||
is_preview?: boolean;
|
||||
@@ -56,6 +57,13 @@ async function load() {
|
||||
}
|
||||
}
|
||||
|
||||
function episodeNote(episode: Episode): string {
|
||||
if (episode.points) return `${episode.points} 积分`;
|
||||
const text = episode.locked_reason || "";
|
||||
if (text.includes("不含") || text.includes("权益") || text.includes("解锁")) return "需要积分";
|
||||
return text || "无地址";
|
||||
}
|
||||
|
||||
function select(episode: Episode) {
|
||||
if (!episode.playable || episode.cid === current.value) return;
|
||||
current.value = episode.cid;
|
||||
@@ -126,7 +134,7 @@ onUnmounted(stop);
|
||||
@click="select(episode)"
|
||||
>
|
||||
<span class="play-episode-title">{{ episode.title }}</span>
|
||||
<span v-if="!episode.playable" class="play-episode-lock">{{ episode.locked_reason || "无地址" }}</span>
|
||||
<span v-if="!episode.playable" class="play-episode-lock">{{ episodeNote(episode) }}</span>
|
||||
<span v-else-if="episode.is_preview" class="play-episode-lock">试看</span>
|
||||
</button>
|
||||
<div v-if="!loading && episodes.length === 0" class="play-empty">没有分集</div>
|
||||
|
||||
@@ -99,8 +99,6 @@ function setDraftField(key: keyof DeviceProfile, value: string | boolean) {
|
||||
<n-radio value="settings">使用上面的设置</n-radio>
|
||||
</n-radio-group>
|
||||
</n-form-item>
|
||||
<n-text class="hint" depth="3">保存后下次登录生效。当前这次登录已经绑定的设备信息不会中途更换。</n-text>
|
||||
<n-text class="hint" depth="3">从设备读取时会带上品牌、型号、系统版本、设备 ID 和已安装的 App 版本。指纹和语言仍用当前设置里的值。</n-text>
|
||||
</n-form>
|
||||
</n-tab-pane>
|
||||
<n-tab-pane name="proxy" tab="代理" display-directive="if">
|
||||
|
||||
@@ -40,6 +40,7 @@ const props = defineProps<{
|
||||
device: object | null;
|
||||
apiBase?: string;
|
||||
remoteSearch?: boolean;
|
||||
showPointDownload?: boolean;
|
||||
}>();
|
||||
const apiBase = computed(() => props.apiBase || "/api");
|
||||
|
||||
@@ -63,13 +64,12 @@ const directory = ref("");
|
||||
const starting = ref(false);
|
||||
const footError = ref("");
|
||||
const coverStatus = reactive<Record<string, "ready" | "failed">>({});
|
||||
const coverDone = ref(0);
|
||||
const coverTotal = ref(0);
|
||||
const scrollTop = ref(0);
|
||||
const viewHeight = ref(800);
|
||||
const gridWidth = ref(720);
|
||||
const gridTops = ref<Record<string, number>>({});
|
||||
const emit = defineEmits<{ started: []; play: [Drama] }>();
|
||||
const downloadPoints = ref(false);
|
||||
const scrollEl = ref<HTMLElement | null>(null);
|
||||
const grids = new Map<string, HTMLElement>();
|
||||
const gridBinders = new Map<string, (el: unknown) => void>();
|
||||
@@ -79,6 +79,8 @@ let flushFrame = 0;
|
||||
let pendingPages: PageEvent[] = [];
|
||||
let coverQueue: string[] = [];
|
||||
const coverQueued = new Set<string>();
|
||||
const coverOwners = new Map<string, Set<string>>();
|
||||
const coverAbort = new Map<string, AbortController>();
|
||||
let coverRunning = 0;
|
||||
let coverToken = 0;
|
||||
const COVER_CONCURRENCY = 2;
|
||||
@@ -116,60 +118,110 @@ function resetCovers() {
|
||||
coverToken += 1;
|
||||
coverQueue = [];
|
||||
coverQueued.clear();
|
||||
coverOwners.clear();
|
||||
for (const controller of coverAbort.values()) controller.abort();
|
||||
coverAbort.clear();
|
||||
coverRunning = 0;
|
||||
coverDone.value = 0;
|
||||
coverTotal.value = 0;
|
||||
for (const key of Object.keys(coverStatus)) delete coverStatus[key];
|
||||
}
|
||||
|
||||
function enqueueCovers(items: Drama[]) {
|
||||
const token = coverToken;
|
||||
let added = 0;
|
||||
for (const item of items) {
|
||||
function enqueueSectionCovers(sectionKey: string) {
|
||||
if (!isExpanded(sectionKey)) return;
|
||||
const section = sections.value.find((item) => item.key === sectionKey);
|
||||
if (!section) return;
|
||||
let added = false;
|
||||
for (const item of section.items) {
|
||||
const src = coverOf(item.image);
|
||||
if (!src || coverStatus[src] || coverQueued.has(src)) continue;
|
||||
if (!src || coverStatus[src]) continue;
|
||||
let owners = coverOwners.get(src);
|
||||
if (!owners) {
|
||||
owners = new Set();
|
||||
coverOwners.set(src, owners);
|
||||
}
|
||||
owners.add(sectionKey);
|
||||
if (coverQueued.has(src) || coverAbort.has(src)) continue;
|
||||
coverQueued.add(src);
|
||||
coverQueue.push(src);
|
||||
added += 1;
|
||||
added = true;
|
||||
}
|
||||
if (added) pumpCovers(coverToken);
|
||||
}
|
||||
|
||||
function stopSectionCovers(sectionKey: string) {
|
||||
for (const [src, owners] of [...coverOwners]) {
|
||||
if (!owners.delete(sectionKey)) continue;
|
||||
if (owners.size) continue;
|
||||
coverOwners.delete(src);
|
||||
coverQueue = coverQueue.filter((item) => item !== src);
|
||||
coverQueued.delete(src);
|
||||
const controller = coverAbort.get(src);
|
||||
if (controller) controller.abort();
|
||||
}
|
||||
if (!added) return;
|
||||
coverTotal.value += added;
|
||||
pumpCovers(token);
|
||||
}
|
||||
|
||||
function pumpCovers(token: number) {
|
||||
while (coverRunning < COVER_CONCURRENCY && coverQueue.length) {
|
||||
const src = coverQueue.shift();
|
||||
if (!src) break;
|
||||
if (!coverOwners.get(src)?.size) {
|
||||
coverQueued.delete(src);
|
||||
continue;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
coverAbort.set(src, controller);
|
||||
coverRunning += 1;
|
||||
void prefetchCover(src).then(
|
||||
(ok) => settleCover(token, src, ok),
|
||||
() => settleCover(token, src, false),
|
||||
void prefetchCover(src, controller.signal).then(
|
||||
(ok) => settleCover(token, src, ok, false),
|
||||
(exc: unknown) => settleCover(token, src, false, exc instanceof DOMException && exc.name === "AbortError"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function prefetchCover(src: string) {
|
||||
async function prefetchCover(src: string, signal: AbortSignal) {
|
||||
if (src.startsWith("/api/")) {
|
||||
const response = await fetch(src);
|
||||
const response = await fetch(src, { signal });
|
||||
if (!response.ok) return false;
|
||||
await response.arrayBuffer();
|
||||
return true;
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const image = new Image();
|
||||
image.onload = () => resolve();
|
||||
image.onerror = () => reject(new Error("cover"));
|
||||
const done = () => {
|
||||
signal.removeEventListener("abort", abort);
|
||||
resolve();
|
||||
};
|
||||
const abort = () => {
|
||||
image.onload = null;
|
||||
image.onerror = null;
|
||||
image.src = "";
|
||||
reject(new DOMException("aborted", "AbortError"));
|
||||
};
|
||||
if (signal.aborted) {
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
image.onload = done;
|
||||
image.onerror = () => {
|
||||
signal.removeEventListener("abort", abort);
|
||||
reject(new Error("cover"));
|
||||
};
|
||||
image.src = src;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function settleCover(token: number, src: string, ok: boolean) {
|
||||
function settleCover(token: number, src: string, ok: boolean, aborted: boolean) {
|
||||
if (token !== coverToken) return;
|
||||
coverRunning = Math.max(0, coverRunning - 1);
|
||||
markCover(src, ok);
|
||||
coverDone.value += 1;
|
||||
coverAbort.delete(src);
|
||||
if (aborted || !coverOwners.get(src)?.size) {
|
||||
coverQueued.delete(src);
|
||||
} else {
|
||||
markCover(src, ok);
|
||||
coverOwners.delete(src);
|
||||
coverQueued.delete(src);
|
||||
}
|
||||
pumpCovers(token);
|
||||
}
|
||||
|
||||
@@ -178,9 +230,10 @@ function isExpanded(key: string) {
|
||||
}
|
||||
|
||||
function toggleExpanded(key: string) {
|
||||
expanded.value = isExpanded(key)
|
||||
? expanded.value.filter((item) => item !== key)
|
||||
: [...expanded.value, key];
|
||||
const open = isExpanded(key);
|
||||
expanded.value = open ? expanded.value.filter((item) => item !== key) : [...expanded.value, key];
|
||||
if (open) stopSectionCovers(key);
|
||||
else enqueueSectionCovers(key);
|
||||
void nextTick(() => measure());
|
||||
}
|
||||
|
||||
@@ -279,7 +332,7 @@ function applyPage(event: PageEvent) {
|
||||
if (event.pages) section.pages = event.pages;
|
||||
if (event.items?.length) {
|
||||
section.items.push(...event.items);
|
||||
enqueueCovers(event.items);
|
||||
enqueueSectionCovers(section.key);
|
||||
}
|
||||
if (event.done) section.loading = false;
|
||||
}
|
||||
@@ -571,6 +624,7 @@ async function find(keyword = query.value) {
|
||||
flashKey.value = "";
|
||||
if (!isExpanded(hit.sectionKey)) {
|
||||
expanded.value = [...expanded.value, hit.sectionKey];
|
||||
enqueueSectionCovers(hit.sectionKey);
|
||||
}
|
||||
await nextTick();
|
||||
if (generation !== revealGeneration) return;
|
||||
@@ -589,12 +643,8 @@ async function find(keyword = query.value) {
|
||||
const loadedCount = computed(() =>
|
||||
sections.value.reduce((sum, section) => sum + (section.key === "search" ? 0 : section.items.length), 0),
|
||||
);
|
||||
const coverPending = computed(() => coverTotal.value > 0 && coverDone.value < coverTotal.value);
|
||||
const showProgress = computed(() => busy.value || stopped.value || coverPending.value);
|
||||
const showProgress = computed(() => busy.value || stopped.value);
|
||||
const progress = computed(() => {
|
||||
if (!busy.value && coverPending.value && coverTotal.value) {
|
||||
return Math.min(100, Math.round((coverDone.value / coverTotal.value) * 100));
|
||||
}
|
||||
let got = 0;
|
||||
let total = 0;
|
||||
for (const section of sections.value) {
|
||||
@@ -608,11 +658,7 @@ const progress = computed(() => {
|
||||
const progressText = computed(() => {
|
||||
const count = loadedCount.value;
|
||||
if (busy.value) return `已加载 ${count} 部`;
|
||||
if (stopped.value && coverPending.value) {
|
||||
return `已停止,共 ${count} 部,封面 ${coverDone.value}/${coverTotal.value}`;
|
||||
}
|
||||
if (stopped.value) return `已停止,共 ${count} 部`;
|
||||
if (coverPending.value) return `封面 ${coverDone.value}/${coverTotal.value}`;
|
||||
return "";
|
||||
});
|
||||
|
||||
@@ -666,10 +712,10 @@ async function searchRemote(keyword: string, generation: number) {
|
||||
pages: 0,
|
||||
});
|
||||
}
|
||||
enqueueCovers(items);
|
||||
publishSections();
|
||||
syncSelectedCounts();
|
||||
if (!isExpanded(key)) expanded.value = [...expanded.value, key];
|
||||
enqueueSectionCovers(key);
|
||||
void nextTick(() => measure());
|
||||
} catch {
|
||||
if (generation === revealGeneration) searchHint.value = "搜索失败";
|
||||
@@ -714,7 +760,12 @@ async function startDownload() {
|
||||
const response = await fetch(`${apiBase.value}/downloads`, {
|
||||
method: "POST",
|
||||
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,
|
||||
download_points: props.showPointDownload ? downloadPoints.value : false,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json();
|
||||
if (!response.ok) {
|
||||
@@ -738,7 +789,7 @@ async function startDownload() {
|
||||
type="line"
|
||||
:percentage="progress"
|
||||
:show-indicator="false"
|
||||
:processing="busy || coverPending"
|
||||
:processing="busy"
|
||||
:height="8"
|
||||
/>
|
||||
</div>
|
||||
@@ -746,7 +797,7 @@ async function startDownload() {
|
||||
<template #trigger>
|
||||
<n-button size="small" secondary @click="stopLoad">停止</n-button>
|
||||
</template>
|
||||
停止后不再获取新剧目,已拿到的封面会继续加载
|
||||
停止后不再获取新剧目
|
||||
</n-tooltip>
|
||||
</div>
|
||||
<div class="download-body">
|
||||
@@ -845,6 +896,7 @@ async function startDownload() {
|
||||
<div class="foot-selected">
|
||||
<n-text>已选 {{ selected.size }} 部</n-text>
|
||||
<n-button secondary size="small" :disabled="selected.size === 0" @click="clearSelection">取消选择</n-button>
|
||||
<n-checkbox v-if="showPointDownload" v-model:checked="downloadPoints">下载积分视频</n-checkbox>
|
||||
</div>
|
||||
<div class="foot-actions">
|
||||
<n-text class="foot-dir" depth="3" :title="directory">{{ directory || "未设置下载目录" }}</n-text>
|
||||
@@ -890,7 +942,9 @@ async function startDownload() {
|
||||
padding: 12px 20px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.12);
|
||||
background: #18181c;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.foot-selected { flex-wrap: wrap; }
|
||||
.foot-actions { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.foot-selected { display: flex; align-items: center; gap: 8px; flex: none; }
|
||||
.foot-dir { max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
Reference in New Issue
Block a user