feat: 将工具更名为 VideosDownTools,并完善黄豆登录与清单

This commit is contained in:
Nixevol
2026-10-25 01:58:29 +08:00
parent 7253217e18
commit 3c2105c786
27 changed files with 1349 additions and 237 deletions
+5 -5
View File
@@ -1,11 +1,11 @@
# RaptDrama Download Tools # VideosDownTools
Windows 桌面程序,用来登录 RaptDrama、浏览剧目、播放已缓存的分集,以及把剧集下载成 MP4。 Windows 桌面程序,用来登录 RaptDrama、黄豆短剧和 DramaBox,浏览剧目、播放分集,以及把剧集下载成 MP4。
## 使用分发包 ## 使用分发包
1. 解压 `dist/RaptDrama-Download-Tools-windows-x64.zip`。 1. 解压 `dist/VideosDownTools-windows-x64.zip`。
2. 进入 `RaptDrama-Download-Tools`,运行 `raptdrama.exe`。 2. 进入 `VideosDownTools`,运行 `VideosDownTools.exe`。
3. 压缩包里已经带有 Python、adb、ffmpeg 和 WebView2 离线安装包。本机如果还没有 WebView2,程序启动时会静默安装。 3. 压缩包里已经带有 Python、adb、ffmpeg 和 WebView2 离线安装包。本机如果还没有 WebView2,程序启动时会静默安装。
程序会在自己的目录里写入: 程序会在自己的目录里写入:
@@ -46,6 +46,6 @@ python scripts\package.py
- `tools/ffmpeg/ffmpeg.exe` - `tools/ffmpeg/ffmpeg.exe`
- `vendor/webview2/MicrosoftEdgeWebView2RuntimeInstallerX64.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` 即可。 打包脚本是 Python,公共步骤和平台相关的运行时是分开的。目前只接好了 Windows。macOS 和 Linux 以后把对应文件放进 `vendor` 即可。
+2 -2
View File
@@ -1,11 +1,11 @@
{ {
"name": "raptdrama", "name": "videosdowntools",
"version": "0.1.0", "version": "0.1.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "raptdrama", "name": "videosdowntools",
"version": "0.1.0", "version": "0.1.0",
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2" "@tauri-apps/cli": "^2"
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"name": "raptdrama", "name": "videosdowntools",
"private": true, "private": true,
"version": "0.1.0", "version": "0.1.0",
"scripts": { "scripts": {
+3 -3
View File
@@ -23,7 +23,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
DIST = ROOT / "dist" DIST = ROOT / "dist"
CACHE = DIST / "cache" CACHE = DIST / "cache"
STAGE_NAME = "RaptDrama-Download-Tools" STAGE_NAME = "VideosDownTools"
PYTHON_VERSION = "3.13.15" PYTHON_VERSION = "3.13.15"
PYTHON_EMBED_URL = ( PYTHON_EMBED_URL = (
@@ -50,7 +50,7 @@ def download(url: str, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True) dest.parent.mkdir(parents=True, exist_ok=True)
temporary = dest.with_suffix(dest.suffix + ".part") temporary = dest.with_suffix(dest.suffix + ".part")
log(f"下载 {url}") log(f"下载 {url}")
request = urllib.request.Request(url, headers={"User-Agent": "RaptDrama"}) request = urllib.request.Request(url, headers={"User-Agent": "VideosDownTools"})
try: try:
with urllib.request.urlopen(request, timeout=120) as response, temporary.open("wb") as handle: with urllib.request.urlopen(request, timeout=120) as response, temporary.open("wb") as handle:
total = int(response.headers.get("Content-Length") or 0) total = int(response.headers.get("Content-Length") or 0)
@@ -91,7 +91,7 @@ def build_desktop() -> Path:
text=True, text=True,
) )
target = Path(json.loads(meta)["target_directory"]) / "release" 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 exe = target / name
if not exe.is_file(): if not exe.is_file():
raise SystemExit(f"没有找到桌面程序 {exe}") raise SystemExit(f"没有找到桌面程序 {exe}")
+1 -1
View File
@@ -23,7 +23,7 @@ from server.services.dramabox.downloads import downloads as dramabox_downloads
def create_app() -> FastAPI: def create_app() -> FastAPI:
app = FastAPI(title="RaptDrama") app = FastAPI(title="VideosDownTools")
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=["*"], allow_origins=["*"],
+89 -6
View File
@@ -11,10 +11,12 @@ from server.services.http import http
from server.services.huangdou import catalog as hd_catalog from server.services.huangdou import catalog as hd_catalog
from server.services.huangdou import login as hd_login from server.services.huangdou import login as hd_login
from server.services.huangdou import playlist as hd_playlist 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.client import client
from server.services.huangdou.covers import covers from server.services.huangdou.covers import covers
from server.services.huangdou.crypto import USER_AGENT from server.services.huangdou.crypto import USER_AGENT
from server.services.huangdou.downloads import downloads as hd_downloads 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 from server.services.playlist import is_direct_media
router = APIRouter(prefix="/api/huangdou") router = APIRouter(prefix="/api/huangdou")
@@ -24,6 +26,37 @@ class TokenBody(BaseModel):
token: str = "" token: str = ""
refresh: bool = False refresh: bool = False
keyword: str = "" 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): class DownloadItem(BaseModel):
@@ -34,6 +67,7 @@ class DownloadItem(BaseModel):
class DownloadStartBody(BaseModel): class DownloadStartBody(BaseModel):
token: str = "" token: str = ""
download_points: bool = False
items: list[DownloadItem] = [] items: list[DownloadItem] = []
@@ -59,9 +93,52 @@ def _require_token(token: str) -> None:
client.token = token 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") @router.post("/login/device")
def login_device(): def login_device(body: TokenBody | None = None):
return call(hd_login.enter) 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") @router.post("/resume")
@@ -131,7 +208,8 @@ def list_episodes(body: PlayBody):
"cid": ep["cid"], "cid": ep["cid"],
"idx": ep["idx"], "idx": ep["idx"],
"title": ep["title"], "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 "", "type": ep.get("type") or "",
"media": "file" if (ep.get("src_kind") == "file" or is_direct_media(ep.get("src") or "")) else "hls", "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")), "is_preview": bool(ep.get("is_preview")),
@@ -156,7 +234,7 @@ def _public_url(url: str) -> str:
def play_segment(url: str): def play_segment(url: str):
target = _public_url(url) target = _public_url(url)
try: 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: except (httpx.HTTPError, TimeoutError, OSError, RuntimeError) as exc:
raise HTTPException(status_code=502, detail="分片读取失败") from exc raise HTTPException(status_code=502, detail="分片读取失败") from exc
media = upstream.headers.get("content-type", "video/mp2t").split(";", 1)[0].strip() or "video/mp2t" 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: if not src:
raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址") raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址")
try: 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: except (httpx.HTTPError, TimeoutError, OSError, RuntimeError) as exc:
raise HTTPException(status_code=502, detail="分片读取失败") from exc raise HTTPException(status_code=502, detail="分片读取失败") from exc
media = upstream.headers.get("content-type", "video/mp4").split(";", 1)[0].strip() or "video/mp4" 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 start_downloads(body: DownloadStartBody):
def action(): def action():
_require_token(body.token) _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) return call(action)
+71
View File
@@ -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
+52 -7
View File
@@ -2,7 +2,16 @@ from server.services.huangdou.client import ApiError, TokenExpired, client
from server.services.huangdou.crypto import USER_AGENT 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 { return {
"browserName": "Chrome", "browserName": "Chrome",
"language": "zh-CN", "language": "zh-CN",
@@ -33,8 +42,34 @@ def login_device(*, force_new: bool = False) -> dict:
return data return data
def user_info() -> dict: def login_username(username: str, password: str, channel_code: str = "") -> dict:
data = client.request("/user/info", {}, auth=True) 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 {} 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 {} return data if isinstance(data, dict) else {}
def drama_detail(drama_id: str) -> dict: def drama_detail(drama_id: str, *, identity: str = "guest") -> dict:
data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True) data = client.request("/drama/detail", {"id": str(drama_id)}, auth=True, identity=identity)
return data if isinstance(data, dict) else {} return data if isinstance(data, dict) else {}
def drama_play(drama_id: str, seq: int) -> dict: 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) 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 {} return data if isinstance(data, dict) else {}
@@ -141,7 +184,9 @@ __all__ = [
"drama_list", "drama_list",
"drama_play", "drama_play",
"limited_free", "limited_free",
"drama_buy",
"login_device", "login_device",
"login_username",
"nav_block", "nav_block",
"nav_list", "nav_list",
"system_info", "system_info",
+151 -31
View File
@@ -19,21 +19,15 @@ ROOT = Path(__file__).resolve().parents[3]
STATE_DIR = ROOT / "cache" / "huangdou" STATE_DIR = ROOT / "cache" / "huangdou"
SESSION_PATH = STATE_DIR / "session.json" SESSION_PATH = STATE_DIR / "session.json"
HOSTS = ( DEFAULT_HOST = "https://pmihlvee.cc"
"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" LINE_CODE = "china_1"
DEFAULT_DEVICE_INFO = {
"browserName": "Chrome",
"language": LANG,
"userAgent": USER_AGENT,
"platform": "Win32",
}
class TokenExpired(RuntimeError): class TokenExpired(RuntimeError):
@@ -48,12 +42,20 @@ class ApiError(RuntimeError):
class HuangdouClient: class HuangdouClient:
def __init__(self) -> None: def __init__(self) -> None:
self.device_id = new_uuid() self.device_id = ""
self.session_id = session_id_of("") 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.token = ""
self.host = HOSTS[0] self.account_token = ""
self.account_username = ""
self.host = DEFAULT_HOST
self.profile: dict = {} self.profile: dict = {}
self._load() self._load()
self._ensure_fingerprint()
def _load(self) -> None: def _load(self) -> None:
if not SESSION_PATH.is_file(): if not SESSION_PATH.is_file():
@@ -65,10 +67,21 @@ class HuangdouClient:
if not isinstance(data, dict): if not isinstance(data, dict):
return return
self.device_id = str(data.get("device_id") or self.device_id) 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.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 "") host = str(data.get("host") or "")
if host.startswith("https://"): if host.startswith("http://") or host.startswith("https://"):
self.host = host.rstrip("/") self.host = host.rstrip("/")
profile = data.get("profile") profile = data.get("profile")
if isinstance(profile, dict): if isinstance(profile, dict):
@@ -79,7 +92,14 @@ class HuangdouClient:
payload = { payload = {
"device_id": self.device_id, "device_id": self.device_id,
"session_id": self.session_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, "token": self.token,
"account_token": self.account_token,
"account_username": self.account_username,
"host": self.host, "host": self.host,
"profile": self.profile, "profile": self.profile,
} }
@@ -87,32 +107,123 @@ class HuangdouClient:
temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
temporary.replace(SESSION_PATH) 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: def clear_token(self) -> None:
self.token = "" self.token = ""
self.guest_device_id = ""
self.guest_session_id = ""
self.guest_device_info = {}
self.account_token = ""
self.account_username = ""
self.profile = {} self.profile = {}
self.save() 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 last_error: Exception | None = None
hosts = [self.host, *[item for item in HOSTS if item != self.host]] for _ in range(2):
for host in hosts:
try: try:
payload = self._call(host, path, data or {}, auth=auth) return self._call(
self.host = host self.host,
return payload path,
data or {},
token=token,
device_id=device_id,
session_id=session_id,
user_agent=user_agent,
)
except (TokenExpired, ApiError): except (TokenExpired, ApiError):
raise raise
except RuntimeError as exc: except RuntimeError as exc:
last_error = exc last_error = exc
raise last_error or RuntimeError("网络请求异常") 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 url = host.rstrip("/") + "/api" + path
request_id = new_uuid() request_id = new_uuid()
now = str(int(time.time())) now = str(int(time.time()))
body = { body = {
"token": self.token if auth else "", "token": token,
"deviceId": self.device_id, "deviceId": device_id,
"data": data, "data": data,
} }
headers = { headers = {
@@ -121,13 +232,13 @@ class HuangdouClient:
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
"Origin": host, "Origin": host,
"Referer": host + "/", "Referer": host + "/",
"User-Agent": USER_AGENT, "User-Agent": user_agent,
"version": APP_VERSION, "version": APP_VERSION,
"deviceType": DEVICE_TYPE, "deviceType": DEVICE_TYPE,
"time": now, "time": now,
"sign": sign_header(self.session_id, request_id, now, url), "sign": sign_header(session_id, request_id, now, url),
"requestId": request_id, "requestId": request_id,
"sessionId": self.session_id, "sessionId": session_id,
"deviceBrand": "", "deviceBrand": "",
"deviceModel": "", "deviceModel": "",
"systemName": "", "systemName": "",
@@ -144,9 +255,18 @@ class HuangdouClient:
if parsed.get("status") == "n": if parsed.get("status") == "n":
code = parsed.get("errorCode") code = parsed.get("errorCode")
if str(code) == "2002": if str(code) == "2002":
raise TokenExpired("登录已失效") raise TokenExpired(str(parsed.get("error") or "登录已失效"))
raise ApiError(str(parsed.get("error") or "网络请求异常"), code) raise ApiError(str(parsed.get("error") or "网络请求异常"), code)
return parsed.get("data") 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() client = HuangdouClient()
+109
View File
@@ -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
+20 -7
View File
@@ -1,3 +1,4 @@
import threading
from pathlib import Path from pathlib import Path
from server.services.downloads import DownloadManager, _plain_text 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.client import client
from server.services.huangdou.covers import covers from server.services.huangdou.covers import covers
from server.services.huangdou.crypto import USER_AGENT 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 from server.services.huangdou import playlist as hd_playlist
_pay_lock = threading.Lock()
ROOT = Path(__file__).resolve().parents[3] ROOT = Path(__file__).resolve().parents[3]
def _load_episodes(_token, _device, drama_id: str, _locale: str = "") -> list[dict]: 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: 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 = "" pay_type = ""
free_episodes = "" free_episodes = ""
vip_episodes = "" vip_episodes = ""
points_price = ""
money = ""
try: try:
detail = api.drama_detail(str(drama_id)) detail = api.drama_detail(str(drama_id))
fetched = str(detail.get("name") or "").strip() 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")) pay_type = _field(detail.get("pay_type"))
free_episodes = _field(detail.get("free_episodes")) free_episodes = _field(detail.get("free_episodes"))
vip_episodes = _field(detail.get("vip_episodes")) vip_episodes = _field(detail.get("vip_episodes"))
points_price = _field(detail.get("points_price"))
money = _field(detail.get("money"))
except Exception: except Exception:
pass pass
lines = [ lines = [
@@ -42,8 +57,6 @@ def _write_intro(folder: Path, drama_id: str, title: str, _token: str, _device)
f"付费类型: {pay_type or '—'}", f"付费类型: {pay_type or '—'}",
f"免费集数: {free_episodes or '—'}", f"免费集数: {free_episodes or '—'}",
f"VIP 集: {vip_episodes or '—'}", f"VIP 集: {vip_episodes or '—'}",
f"积分价格: {points_price or '—'}",
f"金额: {money or '—'}",
"", "",
] ]
(folder / "简介.txt").write_text("\n".join(lines), encoding="utf-8") (folder / "简介.txt").write_text("\n".join(lines), encoding="utf-8")
+102 -21
View File
@@ -3,23 +3,45 @@ from server.services.huangdou.client import TokenExpired, client
from server.services.huangdou.covers import covers as huangdou_covers from server.services.huangdou.covers import covers as huangdou_covers
def enter() -> dict: def enter(host: str = "") -> dict:
try: if host:
if client.token: client.set_host(host)
profile = _profile(api.user_info()) client.account_token = ""
client.profile = profile client.account_username = ""
client.save() client.roll_guest_fingerprint()
return {"token": client.token, "profile": profile}
except TokenExpired:
client.clear_token()
except RuntimeError:
pass
raw = api.login_device(force_new=False) 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: try:
info = api.user_info() raw = api.login_username(username, password)
except RuntimeError: info = _user_from_login(raw) or api.user_info(identity="account")
info = raw except Exception:
profile = _profile(info if isinstance(info, dict) else raw) 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.profile = profile
client.save() client.save()
return {"token": client.token, "profile": profile} return {"token": client.token, "profile": profile}
@@ -36,17 +58,76 @@ def current(token: str) -> dict:
if not token: if not token:
raise RuntimeError("请先登录") raise RuntimeError("请先登录")
if token != client.token: if token != client.token:
client.token = token raise RuntimeError("登录已失效")
try: account = _account_info()
profile = _profile(api.user_info()) profile = public_profile(account)
except TokenExpired as exc:
client.clear_token()
raise RuntimeError("登录已失效") from exc
client.profile = profile client.profile = profile
client.save() client.save()
return {"token": client.token, "profile": profile} 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: def logout(token: str) -> None:
if token and token == client.token: if token and token == client.token:
client.clear_token() client.clear_token()
+183 -70
View File
@@ -1,41 +1,70 @@
import json import json
import re import re
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path from pathlib import Path
from urllib.parse import quote, urljoin from urllib.parse import quote, urljoin
from server.services.huangdou import api 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.http import http
from server.services.huangdou.crypto import USER_AGENT from server.services.huangdou.crypto import USER_AGENT
from server.services.playlist import is_direct_media, looks_like_segment from server.services.playlist import is_direct_media, looks_like_segment
CACHE_DIR = Path(__file__).resolve().parents[3] / "cache" / "huangdou" / "playlists" 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]: def load_episodes(drama_id: str) -> list[dict]:
drama_id = str(drama_id or "").strip() drama_id = str(drama_id or "").strip()
if not drama_id: if not drama_id:
raise RuntimeError("没有这部剧") raise RuntimeError("没有这部剧")
cached = _read_cache(drama_id) detail = api.drama_detail(drama_id, identity=_viewer_identity())
fresh = _fetch_episodes(drama_id) rows = detail.get("episodes") if isinstance(detail, dict) else None
merged, save = _merge(cached, fresh) if not isinstance(rows, list) or not rows:
if save or (not cached and merged): raise RuntimeError("没有读到分集")
_write_cache(drama_id, merged) fresh = _menu_rows(rows)
if not fresh:
raise RuntimeError("没有读到分集")
merged = _keep_sources(_read_cache(drama_id), fresh)
_write_cache(drama_id, merged)
return merged return merged
def episode_src(drama_id: str, cid: int) -> dict: def episode_src(drama_id: str, cid: int) -> dict:
for ep in load_episodes(drama_id): drama_id = str(drama_id or "").strip()
if int(ep.get("cid") or 0) == int(cid): row = _cached_row(drama_id, cid)
return ep if row is None:
return {} 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: def playback_playlist(src: str) -> str:
if is_direct_media(src): if is_direct_media(src):
raise RuntimeError("这一集是整段视频") raise RuntimeError("这一集是整段视频")
text = http.read_text(src, headers=CDN_HEADERS) text = http.read_text(src, headers=_cdn_headers())
variant_rel = next( variant_rel = next(
(line.strip() for line in text.splitlines() if line.strip() and not line.startswith("#")), (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): if looks_like_segment(variant_rel):
return _rewrite_playlist(text, src) return _rewrite_playlist(text, src)
variant_url = urljoin(src, variant_rel) 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: 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" return "\n".join(result) + "\n"
def _fetch_episodes(drama_id: str) -> list[dict]: def load_for_download(drama_id: str, *, allow_paid: bool, account_vip: bool) -> list[dict]:
detail = api.drama_detail(drama_id) 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 rows = detail.get("episodes") if isinstance(detail, dict) else None
if not isinstance(rows, list) or not rows: if not isinstance(rows, list) or not rows:
raise RuntimeError("没有读到分集") raise RuntimeError("没有读到分集")
@@ -131,36 +163,89 @@ def _fetch_episodes(drama_id: str) -> list[dict]:
for item in rows: for item in rows:
if not isinstance(item, dict): if not isinstance(item, dict):
continue continue
seq = _int(item.get("seq")) if not keep_episode(item, allow_paid=allow_paid, account_vip=account_vip):
if seq <= 0:
continue continue
kind = str(item.get("type") or "free").strip() or "free" row = _skeleton_row(item, account_vip=account_vip)
skeleton.append({ if row:
"cid": seq, skeleton.append(row)
"idx": seq, return _play_rows(drama_id, skeleton, allow_buy=allow_paid)
"title": str(item.get("name") or f"第{seq}集").strip() or f"第{seq}集",
"src": "",
"type": kind, def _viewer_identity() -> str:
"price": _int(item.get("price")), return "account" if client.account_token else "guest"
"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")), def _menu_rows(rows: list) -> list[dict]:
"methods": item.get("methods") if isinstance(item.get("methods"), list) else [], from server.services.huangdou.login import account_is_vip
"is_preview": False,
"preview_seconds": 0, vip = account_is_vip()
"preview_m3u8": "", skeleton = []
"hls_key": "", for item in rows:
"src_kind": "", if not isinstance(item, dict):
"locked_reason": "", 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: if not skeleton:
raise RuntimeError("没有读到分集") return []
def play_one(row: dict) -> dict: 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: 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: 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 return row
preview = str(played.get("preview_m3u8") or "").strip() preview = str(played.get("preview_m3u8") or "").strip()
row["hls_key"] = str(played.get("hls_key") 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"] = src
row["src_kind"] = kind row["src_kind"] = kind
if src: if src:
row["playable"] = True
if kind == "file" or row["is_preview"]: if kind == "file" or row["is_preview"]:
row["is_preview"] = True row["is_preview"] = True
row["locked_reason"] = "当前账号只能下到试看" row["locked_reason"] = ""
row["points"] = 0
else: else:
row["playable"] = False
row["locked_reason"] = _lock_reason(row) row["locked_reason"] = _lock_reason(row)
return row return row
@@ -190,41 +278,66 @@ def _fetch_episodes(drama_id: str) -> list[dict]:
return updated 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: def _lock_reason(row: dict) -> str:
kind = str(row.get("type") or "free") if _int(row.get("points") or row.get("price")) > 0 and not already_bought(row):
if kind in {"vip", "VIP"}: return public_lock_reason(row, "")
kind = episode_kind(row)
if kind in VIP_TYPES:
return "需要 VIP" return "需要 VIP"
if kind in {"coin", "points", "point", "pay"}: return "没有可播放的地址"
return "需要积分或付费"
if not row.get("is_buy"):
return "尚未购买"
return "没有可下载的地址"
def _merge(cached: list[dict], fresh: list[dict]) -> tuple[list[dict], bool]: def _cached_row(drama_id: str, cid: int, *, refresh: bool = False) -> dict | None:
by_cid: dict[int, dict] = {} rows = load_episodes(drama_id) if refresh else _read_cache(drama_id)
for source in (cached, fresh): for ep in rows:
for ep in source: if int(ep.get("cid") or 0) == int(cid):
cid = _int(ep.get("cid")) return ep
if cid <= 0: return None
continue
current = by_cid.get(cid)
if current is None: def _keep_sources(cached: list[dict], fresh: list[dict]) -> list[dict]:
by_cid[cid] = dict(ep) previous = {int(ep.get("cid") or 0): ep for ep in cached if int(ep.get("cid") or 0) > 0}
by_cid[cid]["cid"] = cid merged = []
by_cid[cid]["idx"] = _int(ep.get("idx") or cid) for row in fresh:
continue old = previous.get(int(row["cid"]))
for key, value in ep.items(): if old and old.get("is_preview"):
if key == "src": row["is_preview"] = True
if value: if row.get("playable") and old and old.get("src") and not old.get("is_preview"):
current["src"] = value row["src"] = old.get("src") or ""
continue row["src_kind"] = old.get("src_kind") or ""
if value not in (None, "", [], {}): row["hls_key"] = old.get("hls_key") or ""
current[key] = value row["preview_seconds"] = old.get("preview_seconds") or 0
merged = sorted(by_cid.values(), key=lambda item: (int(item.get("idx") or 0), int(item["cid"]))) row["preview_m3u8"] = old.get("preview_m3u8") or ""
filled_fresh = sum(1 for ep in fresh if ep.get("src")) merged.append(row)
filled_cached = sum(1 for ep in cached if ep.get("src")) return merged
return merged, filled_fresh >= filled_cached and filled_fresh > 0
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]: def _read_cache(drama_id: str) -> list[dict]:
+13 -13
View File
@@ -2701,19 +2701,6 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" 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]] [[package]]
name = "raw-window-handle" name = "raw-window-handle"
version = "0.6.2" version = "0.6.2"
@@ -4129,6 +4116,19 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" 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]] [[package]]
name = "vswhom" name = "vswhom"
version = "0.1.0" version = "0.1.0"
+6 -4
View File
@@ -1,17 +1,19 @@
[package] [package]
name = "raptdrama" name = "videosdowntools"
version = "0.1.0" version = "0.1.0"
description = "RaptDrama desktop shell" description = "VideosDownTools desktop shell"
authors = ["nixevol"] authors = ["nixevol"]
edition = "2021" 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] [lib]
# The `_lib` suffix may seem redundant but it is necessary # The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name. # 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 # 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"] crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies] [build-dependencies]
+2 -2
View File
@@ -2,7 +2,7 @@
<html lang="zh-CN"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>RaptDrama Download Tools</title> <title>VideosDownTools</title>
<style> <style>
html, body { height: 100%; margin: 0; background: #101014; color: #f2f2f2; font: 16px/1.5 "Segoe UI", sans-serif; } 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; } body { display: flex; align-items: center; justify-content: center; }
@@ -13,7 +13,7 @@
</head> </head>
<body> <body>
<main> <main>
<h1>RaptDrama</h1> <h1>VideosDownTools</h1>
<p id="status">程序正在启动</p> <p id="status">程序正在启动</p>
</main> </main>
<script> <script>
+1 -1
View File
@@ -242,7 +242,7 @@ fn boot(handle: &AppHandle, window: &tauri::WebviewWindow) -> Result<(), String>
while Instant::now() < deadline { while Instant::now() < deadline {
if health_ok(port) { if health_ok(port) {
let url = Url::parse(&format!("http://127.0.0.1:{port}/")).map_err(|err| err.to_string())?; 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()); let _ = std::io::Write::flush(&mut std::io::stderr());
window.navigate(url).map_err(|err| err.to_string())?; window.navigate(url).map_err(|err| err.to_string())?;
return Ok(()); return Ok(());
+1 -1
View File
@@ -2,5 +2,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() { fn main() {
raptdrama_lib::run() videosdowntools_lib::run()
} }
+3 -3
View File
@@ -1,8 +1,8 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "RaptDrama", "productName": "VideosDownTools",
"version": "0.1.0", "version": "0.1.0",
"identifier": "com.raptdrama.desktop", "identifier": "com.videosdowntools.desktop",
"build": { "build": {
"beforeDevCommand": { "beforeDevCommand": {
"script": "npm run build --prefix ui", "script": "npm run build --prefix ui",
@@ -19,7 +19,7 @@
"windows": [ "windows": [
{ {
"label": "main", "label": "main",
"title": "RaptDrama Download Tools", "title": "VideosDownTools",
"width": 1080, "width": 1080,
"height": 800, "height": 800,
"center": true, "center": true,
+130
View File
@@ -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
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/favicon.png" /> <link rel="icon" type="image/png" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>RaptDrama Download Tools</title> <title>VideosDownTools</title>
</head> </head>
<body> <body>
+2 -2
View File
@@ -1,11 +1,11 @@
{ {
"name": "raptdrama-ui", "name": "videosdowntools-ui",
"version": "0.1.0", "version": "0.1.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "raptdrama-ui", "name": "videosdowntools-ui",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2", "@tauri-apps/api": "^2",
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"name": "raptdrama-ui", "name": "videosdowntools-ui",
"private": true, "private": true,
"version": "0.1.0", "version": "0.1.0",
"type": "module", "type": "module",
+297 -12
View File
@@ -30,6 +30,7 @@ interface Profile {
balance?: string | number; balance?: string | number;
is_vip?: string | number; is_vip?: string | number;
has_login?: string; has_login?: string;
host?: string;
country?: string; country?: string;
language?: string; language?: string;
native?: string; native?: string;
@@ -51,6 +52,12 @@ interface SavedAccount {
uid: string; uid: string;
} }
interface HuangdouAccount {
username: string;
password: string;
nickname: string;
}
interface DeviceProfile { interface DeviceProfile {
brand: string; brand: string;
model: string; model: string;
@@ -92,6 +99,9 @@ const SESSION_DEVICE_KEY = "rapt-device";
const ACCOUNTS_KEY = "rapt-accounts"; const ACCOUNTS_KEY = "rapt-accounts";
const PLATFORM_KEY = "rapt-platform"; const PLATFORM_KEY = "rapt-platform";
const DRAMABOX_LANG_KEY = "dramabox-language"; 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 DRAMABOX_DEVICE_KEY = "dramabox-device";
const themeOverrides: GlobalThemeOverrides = { const themeOverrides: GlobalThemeOverrides = {
@@ -113,11 +123,19 @@ const apiBase = computed(() => {
return "/api"; return "/api";
}); });
const platformLabel = computed(() => { 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}`; if (platform.value === "dramabox" && profile.value?.nickname) return `${name} · ${profile.value.nickname}`;
return name; return name;
}); });
const dramaboxLang = ref("th"); 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 dramaboxLangs = ref<{ label: string; value: string }[]>([]);
const accountBusy = ref(false); const accountBusy = ref(false);
const activeProxyUrl = ref(""); const activeProxyUrl = ref("");
@@ -193,6 +211,68 @@ const menuValue = computed(() => {
return page.value; 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 { function readPlatform(): Platform {
try { try {
const value = localStorage.getItem(PLATFORM_KEY); const value = localStorage.getItem(PLATFORM_KEY);
@@ -212,6 +292,7 @@ function selectPlatform(key: string) {
void loadDramaboxLanguages(); void loadDramaboxLanguages();
void loadDevices(); void loadDevices();
} }
if (key === "huangdou") void sendHuangdouFingerprint();
} }
function tokenKey() { function tokenKey() {
@@ -310,6 +391,18 @@ const methods: { id: Method; label: string }[] = [
{ id: "adb", label: "ADB" }, { 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(() => { const accountFields = computed(() => {
if (platform.value === "huangdou") { if (platform.value === "huangdou") {
return [ 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[] { function readList<T>(key: string): T[] {
try { try {
const data = JSON.parse(localStorage.getItem(key) || "[]"); const data = JSON.parse(localStorage.getItem(key) || "[]");
@@ -678,6 +778,91 @@ function saveAccount(info: Profile) {
selectedAccount.value = next.email; 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) { function profileText(key: keyof Profile) {
if (key === "loginType") { if (key === "loginType") {
const kind = String(profile.value?.loginType || "").trim().toLowerCase(); const kind = String(profile.value?.loginType || "").trim().toLowerCase();
@@ -772,15 +957,82 @@ watch(method, (value) => {
if (value === "adb") loadDevices(); 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 = ""; error.value = "";
if (!asGuest && (!huangdouUser.value.trim() || !huangdouPassword.value)) {
error.value = "请填写账号和密码";
return;
}
busy.value = true; busy.value = true;
try { 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(); const payload = await response.json();
if (!response.ok) { if (!response.ok) {
throw new Error(typeof payload.detail === "string" ? payload.detail : "登录失败"); 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; token.value = payload.token;
profile.value = payload.profile; profile.value = payload.profile;
writeSavedToken(payload.token); writeSavedToken(payload.token);
@@ -868,7 +1120,7 @@ async function loginDramabox() {
async function login() { async function login() {
if (platform.value === "huangdou") { if (platform.value === "huangdou") {
await loginHuangdou(); await loginHuangdou(false);
return; return;
} }
if (platform.value === "dramabox") { if (platform.value === "dramabox") {
@@ -974,6 +1226,9 @@ async function logout() {
token.value = ""; token.value = "";
profile.value = null; profile.value = null;
page.value = "download"; page.value = "download";
if (platform.value === "huangdou" && huangdouAccounts.value.length) {
applyHuangdouAccount(huangdouSelected.value || huangdouAccounts.value[0].username);
}
forgetSavedToken(); forgetSavedToken();
sessionStorage.removeItem(SESSION_DEVICE_KEY); sessionStorage.removeItem(SESSION_DEVICE_KEY);
try { try {
@@ -1043,7 +1298,7 @@ async function confirmQuit() {
} }
onMounted(async () => { onMounted(async () => {
document.title = "RaptDrama Download Tools"; document.title = "VideosDownTools";
void watchClose(); void watchClose();
await loadDeviceDefaults(); await loadDeviceDefaults();
loadSettings(); loadSettings();
@@ -1054,10 +1309,13 @@ 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);
await loadHuangdouAccounts();
huangdouAccountsReady = true;
if (platform.value === "dramabox") { if (platform.value === "dramabox") {
await loadDramaboxLanguages(); await loadDramaboxLanguages();
void loadDevices(); void loadDevices();
} }
if (platform.value === "huangdou") void sendHuangdouFingerprint();
let saved = readSavedToken(); let saved = readSavedToken();
if (!saved && isolated.value) { if (!saved && isolated.value) {
try { try {
@@ -1182,6 +1440,7 @@ onUnmounted(stopLive);
:device="sessionDevice()" :device="sessionDevice()"
:api-base="apiBase" :api-base="apiBase"
:remote-search="isolated" :remote-search="isolated"
:show-point-download="platform === 'huangdou'"
@started="page = 'progress'" @started="page = 'progress'"
@play="openPlay" @play="openPlay"
/> />
@@ -1205,8 +1464,9 @@ onUnmounted(stopLive);
<div class="profile-name-row"> <div class="profile-name-row">
<span class="profile-name">{{ profile.nickname || "未命名" }}</span> <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="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> </div>
<span class="profile-sub">{{ profile.email || (platform === "dramabox" ? profile.native || "" : "未绑定邮箱") }}</span> <span class="profile-sub">{{ profileSub }}</span>
</div> </div>
<n-tooltip placement="bottom"> <n-tooltip placement="bottom">
<template #trigger> <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-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="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-form-item v-if="platform === 'dramabox'" label="地区">
<n-select v-model:value="dramaboxLang" filterable :options="dramaboxLangs" placeholder="选择国家 / 语言" /> <n-select v-model:value="dramaboxLang" filterable :options="dramaboxLangs" placeholder="选择国家 / 语言" />
</n-form-item> </n-form-item>
@@ -1315,15 +1604,11 @@ 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="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> <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 v-if="platform === 'dramabox'" attr-type="button" secondary :loading="busy" :disabled="!dramaboxDeviceReady" @click="loginDramaboxAdb">从设备登录</n-button> <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> </div>
</n-form> </n-form>
</div> </div>
+9 -1
View File
@@ -6,6 +6,7 @@ interface Episode {
idx: number; idx: number;
title: string; title: string;
playable: boolean; playable: boolean;
points?: number;
media?: string; media?: string;
locked_reason?: string; locked_reason?: string;
is_preview?: boolean; 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) { function select(episode: Episode) {
if (!episode.playable || episode.cid === current.value) return; if (!episode.playable || episode.cid === current.value) return;
current.value = episode.cid; current.value = episode.cid;
@@ -126,7 +134,7 @@ 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">{{ 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> <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>
-2
View File
@@ -99,8 +99,6 @@ function setDraftField(key: keyof DeviceProfile, value: string | boolean) {
<n-radio value="settings">使用上面的设置</n-radio> <n-radio value="settings">使用上面的设置</n-radio>
</n-radio-group> </n-radio-group>
</n-form-item> </n-form-item>
<n-text class="hint" depth="3">保存后下次登录生效。当前这次登录已经绑定的设备信息不会中途更换。</n-text>
<n-text class="hint" depth="3">从设备读取时会带上品牌、型号、系统版本、设备 ID 和已安装的 App 版本。指纹和语言仍用当前设置里的值。</n-text>
</n-form> </n-form>
</n-tab-pane> </n-tab-pane>
<n-tab-pane name="proxy" tab="代理" display-directive="if"> <n-tab-pane name="proxy" tab="代理" display-directive="if">
+94 -40
View File
@@ -40,6 +40,7 @@ const props = defineProps<{
device: object | null; device: object | null;
apiBase?: string; apiBase?: string;
remoteSearch?: boolean; remoteSearch?: boolean;
showPointDownload?: boolean;
}>(); }>();
const apiBase = computed(() => props.apiBase || "/api"); const apiBase = computed(() => props.apiBase || "/api");
@@ -63,13 +64,12 @@ const directory = ref("");
const starting = ref(false); const starting = ref(false);
const footError = ref(""); const footError = ref("");
const coverStatus = reactive<Record<string, "ready" | "failed">>({}); const coverStatus = reactive<Record<string, "ready" | "failed">>({});
const coverDone = ref(0);
const coverTotal = ref(0);
const scrollTop = ref(0); const scrollTop = ref(0);
const viewHeight = ref(800); const viewHeight = ref(800);
const gridWidth = ref(720); const gridWidth = ref(720);
const gridTops = ref<Record<string, number>>({}); const gridTops = ref<Record<string, number>>({});
const emit = defineEmits<{ started: []; play: [Drama] }>(); const emit = defineEmits<{ started: []; play: [Drama] }>();
const downloadPoints = ref(false);
const scrollEl = ref<HTMLElement | null>(null); const scrollEl = ref<HTMLElement | null>(null);
const grids = new Map<string, HTMLElement>(); const grids = new Map<string, HTMLElement>();
const gridBinders = new Map<string, (el: unknown) => void>(); const gridBinders = new Map<string, (el: unknown) => void>();
@@ -79,6 +79,8 @@ let flushFrame = 0;
let pendingPages: PageEvent[] = []; let pendingPages: PageEvent[] = [];
let coverQueue: string[] = []; let coverQueue: string[] = [];
const coverQueued = new Set<string>(); const coverQueued = new Set<string>();
const coverOwners = new Map<string, Set<string>>();
const coverAbort = new Map<string, AbortController>();
let coverRunning = 0; let coverRunning = 0;
let coverToken = 0; let coverToken = 0;
const COVER_CONCURRENCY = 2; const COVER_CONCURRENCY = 2;
@@ -116,60 +118,110 @@ function resetCovers() {
coverToken += 1; coverToken += 1;
coverQueue = []; coverQueue = [];
coverQueued.clear(); coverQueued.clear();
coverOwners.clear();
for (const controller of coverAbort.values()) controller.abort();
coverAbort.clear();
coverRunning = 0; coverRunning = 0;
coverDone.value = 0;
coverTotal.value = 0;
for (const key of Object.keys(coverStatus)) delete coverStatus[key]; for (const key of Object.keys(coverStatus)) delete coverStatus[key];
} }
function enqueueCovers(items: Drama[]) { function enqueueSectionCovers(sectionKey: string) {
const token = coverToken; if (!isExpanded(sectionKey)) return;
let added = 0; const section = sections.value.find((item) => item.key === sectionKey);
for (const item of items) { if (!section) return;
let added = false;
for (const item of section.items) {
const src = coverOf(item.image); 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); coverQueued.add(src);
coverQueue.push(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) { function pumpCovers(token: number) {
while (coverRunning < COVER_CONCURRENCY && coverQueue.length) { while (coverRunning < COVER_CONCURRENCY && coverQueue.length) {
const src = coverQueue.shift(); const src = coverQueue.shift();
if (!src) break; if (!src) break;
if (!coverOwners.get(src)?.size) {
coverQueued.delete(src);
continue;
}
const controller = new AbortController();
coverAbort.set(src, controller);
coverRunning += 1; coverRunning += 1;
void prefetchCover(src).then( void prefetchCover(src, controller.signal).then(
(ok) => settleCover(token, src, ok), (ok) => settleCover(token, src, ok, false),
() => settleCover(token, src, 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/")) { if (src.startsWith("/api/")) {
const response = await fetch(src); const response = await fetch(src, { signal });
if (!response.ok) return false; if (!response.ok) return false;
await response.arrayBuffer(); await response.arrayBuffer();
return true; return true;
} }
await new Promise<void>((resolve, reject) => { await new Promise<void>((resolve, reject) => {
const image = new Image(); const image = new Image();
image.onload = () => resolve(); const done = () => {
image.onerror = () => reject(new Error("cover")); 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; image.src = src;
}); });
return true; return true;
} }
function settleCover(token: number, src: string, ok: boolean) { function settleCover(token: number, src: string, ok: boolean, aborted: boolean) {
if (token !== coverToken) return; if (token !== coverToken) return;
coverRunning = Math.max(0, coverRunning - 1); coverRunning = Math.max(0, coverRunning - 1);
markCover(src, ok); coverAbort.delete(src);
coverDone.value += 1; if (aborted || !coverOwners.get(src)?.size) {
coverQueued.delete(src);
} else {
markCover(src, ok);
coverOwners.delete(src);
coverQueued.delete(src);
}
pumpCovers(token); pumpCovers(token);
} }
@@ -178,9 +230,10 @@ function isExpanded(key: string) {
} }
function toggleExpanded(key: string) { function toggleExpanded(key: string) {
expanded.value = isExpanded(key) const open = isExpanded(key);
? expanded.value.filter((item) => item !== key) expanded.value = open ? expanded.value.filter((item) => item !== key) : [...expanded.value, key];
: [...expanded.value, key]; if (open) stopSectionCovers(key);
else enqueueSectionCovers(key);
void nextTick(() => measure()); void nextTick(() => measure());
} }
@@ -279,7 +332,7 @@ function applyPage(event: PageEvent) {
if (event.pages) section.pages = event.pages; if (event.pages) section.pages = event.pages;
if (event.items?.length) { if (event.items?.length) {
section.items.push(...event.items); section.items.push(...event.items);
enqueueCovers(event.items); enqueueSectionCovers(section.key);
} }
if (event.done) section.loading = false; if (event.done) section.loading = false;
} }
@@ -571,6 +624,7 @@ async function find(keyword = query.value) {
flashKey.value = ""; flashKey.value = "";
if (!isExpanded(hit.sectionKey)) { if (!isExpanded(hit.sectionKey)) {
expanded.value = [...expanded.value, hit.sectionKey]; expanded.value = [...expanded.value, hit.sectionKey];
enqueueSectionCovers(hit.sectionKey);
} }
await nextTick(); await nextTick();
if (generation !== revealGeneration) return; if (generation !== revealGeneration) return;
@@ -589,12 +643,8 @@ async function find(keyword = query.value) {
const loadedCount = computed(() => const loadedCount = computed(() =>
sections.value.reduce((sum, section) => sum + (section.key === "search" ? 0 : section.items.length), 0), 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);
const showProgress = computed(() => busy.value || stopped.value || coverPending.value);
const progress = computed(() => { 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 got = 0;
let total = 0; let total = 0;
for (const section of sections.value) { for (const section of sections.value) {
@@ -608,11 +658,7 @@ const progress = computed(() => {
const progressText = computed(() => { const progressText = computed(() => {
const count = loadedCount.value; const count = loadedCount.value;
if (busy.value) return `已加载 ${count} 部`; if (busy.value) return `已加载 ${count} 部`;
if (stopped.value && coverPending.value) {
return `已停止,共 ${count} 部,封面 ${coverDone.value}/${coverTotal.value}`;
}
if (stopped.value) return `已停止,共 ${count} 部`; if (stopped.value) return `已停止,共 ${count} 部`;
if (coverPending.value) return `封面 ${coverDone.value}/${coverTotal.value}`;
return ""; return "";
}); });
@@ -666,10 +712,10 @@ async function searchRemote(keyword: string, generation: number) {
pages: 0, pages: 0,
}); });
} }
enqueueCovers(items);
publishSections(); publishSections();
syncSelectedCounts(); syncSelectedCounts();
if (!isExpanded(key)) expanded.value = [...expanded.value, key]; if (!isExpanded(key)) expanded.value = [...expanded.value, key];
enqueueSectionCovers(key);
void nextTick(() => measure()); void nextTick(() => measure());
} catch { } catch {
if (generation === revealGeneration) searchHint.value = "搜索失败"; if (generation === revealGeneration) searchHint.value = "搜索失败";
@@ -714,7 +760,12 @@ async function startDownload() {
const response = await fetch(`${apiBase.value}/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,
download_points: props.showPointDownload ? downloadPoints.value : false,
}),
}); });
const payload = await response.json(); const payload = await response.json();
if (!response.ok) { if (!response.ok) {
@@ -738,7 +789,7 @@ async function startDownload() {
type="line" type="line"
:percentage="progress" :percentage="progress"
:show-indicator="false" :show-indicator="false"
:processing="busy || coverPending" :processing="busy"
:height="8" :height="8"
/> />
</div> </div>
@@ -746,7 +797,7 @@ async function startDownload() {
<template #trigger> <template #trigger>
<n-button size="small" secondary @click="stopLoad">停止</n-button> <n-button size="small" secondary @click="stopLoad">停止</n-button>
</template> </template>
停止后不再获取新剧目,已拿到的封面会继续加载 停止后不再获取新剧目
</n-tooltip> </n-tooltip>
</div> </div>
<div class="download-body"> <div class="download-body">
@@ -845,6 +896,7 @@ async function startDownload() {
<div class="foot-selected"> <div class="foot-selected">
<n-text>已选 {{ selected.size }} 部</n-text> <n-text>已选 {{ selected.size }} 部</n-text>
<n-button secondary size="small" :disabled="selected.size === 0" @click="clearSelection">取消选择</n-button> <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>
<div class="foot-actions"> <div class="foot-actions">
<n-text class="foot-dir" depth="3" :title="directory">{{ directory || "未设置下载目录" }}</n-text> <n-text class="foot-dir" depth="3" :title="directory">{{ directory || "未设置下载目录" }}</n-text>
@@ -890,7 +942,9 @@ async function startDownload() {
padding: 12px 20px; padding: 12px 20px;
border-top: 1px solid rgba(255, 255, 255, 0.12); border-top: 1px solid rgba(255, 255, 255, 0.12);
background: #18181c; background: #18181c;
flex-wrap: wrap;
} }
.foot-selected { flex-wrap: wrap; }
.foot-actions { display: flex; align-items: center; gap: 8px; min-width: 0; } .foot-actions { display: flex; align-items: center; gap: 8px; min-width: 0; }
.foot-selected { display: flex; align-items: center; gap: 8px; flex: none; } .foot-selected { display: flex; align-items: center; gap: 8px; flex: none; }
.foot-dir { max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .foot-dir { max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }