11 Commits
31 changed files with 1549 additions and 86 deletions
+13
View File
@@ -0,0 +1,13 @@
* text=auto eol=lf
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.webp binary
*.ico binary
*.icns binary
*.zip binary
*.exe binary
*.dll binary
*.pyd binary
*.pyc binary
+4 -3
View File
@@ -6,7 +6,8 @@ Windows 桌面程序,用来登录 RaptDrama、黄豆短剧和 DramaBox,浏
1. 解压 `dist/VideosDownTools-windows-x64.zip`。
2. 进入 `VideosDownTools`,运行 `VideosDownTools.exe`。
3. 压缩包里已经带有 Python、adb、ffmpeg 和 WebView2 离线安装包。本机如果还没有 WebView2,程序启动时会静默安装。
3. 压缩包里已经带有 Python、adb、ffmpeg 和大约 2 MB 的 WebView2 在线安装器。本机如果还没有 WebView2,程序启动时会用它联网静默安装。
4. 打开程序时如果有新版本,会提示是否更新。选择更新后会自动下载并重新打开,已下载的视频和登录状态会保留。
程序会在自己的目录里写入:
@@ -44,8 +45,8 @@ python scripts\package.py
- `dist/cache` 里的 Windows 嵌入式 Python,以及 `server/requirements.txt` 里的依赖
- `vendor/platform-tools` 里的 adb,拷到压缩包的 `tools/platform-tools`
- `tools/ffmpeg/ffmpeg.exe`
- `vendor/webview2/MicrosoftEdgeWebView2RuntimeInstallerX64.exe`
- `vendor/webview2/MicrosoftEdgeWebview2Setup.exe`。本机还没有这个文件时,打包会从微软下载这份在线安装器。同目录里的离线安装包不会打进压缩包。
adb 和 WebView2 打包时不再下载。完成后得到 `dist/VideosDownTools-windows-x64.zip`。
adb 打包时不再下载。完成后得到 `dist/VideosDownTools-windows-x64.zip`。
打包脚本是 Python,公共步骤和平台相关的运行时是分开的。目前只接好了 Windows。macOS 和 Linux 以后把对应文件放进 `vendor` 即可。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "videosdowntools",
"private": true,
"version": "0.1.0",
"version": "0.1.4",
"scripts": {
"tauri": "tauri"
},
+17 -3
View File
@@ -4,7 +4,7 @@
python scripts/package.py
Windows 会编译界面和桌面程序,并拷贝本地已有的 Python 缓存、adb、ffmpeg 和 WebView2 离线安装包。
Windows 会编译界面和桌面程序,并拷贝本地已有的 Python 缓存、adb、ffmpeg 和 WebView2 在线安装器。
macOS、Linux 以后可以在对应函数里补上自己的运行时,其余步骤可以复用。
"""
@@ -31,7 +31,8 @@ PYTHON_EMBED_URL = (
)
GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
FFMPEG_URL = "https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1/ffmpeg-win32-x64.gz"
WEBVIEW_INSTALLER = "MicrosoftEdgeWebView2RuntimeInstallerX64.exe"
WEBVIEW_INSTALLER = "MicrosoftEdgeWebview2Setup.exe"
WEBVIEW_BOOTSTRAP_URL = "https://go.microsoft.com/fwlink/p/?LinkId=2124703"
def log(message: str) -> None:
@@ -166,7 +167,11 @@ def bundle_webview(stage: Path) -> None:
return
source = ROOT / "vendor" / "webview2" / WEBVIEW_INSTALLER
if not source.is_file():
raise SystemExit(f"vendor/webview2 里没有 {WEBVIEW_INSTALLER}")
download(WEBVIEW_BOOTSTRAP_URL, source)
data = source.read_bytes()[:2]
size = source.stat().st_size
if data != b"MZ" or not 200_000 <= size <= 20_000_000:
raise SystemExit(f"{WEBVIEW_INSTALLER} 不是 WebView2 在线安装器")
dest = stage / "vendor" / "webview2"
dest.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, dest / source.name)
@@ -211,6 +216,14 @@ def hide_server_source(stage: Path) -> None:
raise SystemExit("服务端没有编译出字节码")
def write_version(stage: Path) -> None:
conf = json.loads((ROOT / "src-tauri" / "tauri.conf.json").read_text(encoding="utf-8"))
version = str(conf.get("version") or "").strip()
if not version:
raise SystemExit("没有版本号")
(stage / "version.json").write_text(json.dumps({"version": version}, ensure_ascii=False), encoding="utf-8")
def make_zip(stage: Path) -> Path:
suffix = "windows-x64" if sys.platform == "win32" else platform.system().lower()
archive = DIST / f"{STAGE_NAME}-{suffix}.zip"
@@ -246,6 +259,7 @@ def main() -> None:
if stage.exists():
shutil.rmtree(stage)
stage.mkdir(parents=True)
write_version(stage)
shutil.copy2(exe, stage / exe.name)
copy_server(stage)
ui_dest = stage / "dist" / "ui"
+116
View File
@@ -0,0 +1,116 @@
"""把当前版本的 Windows 压缩包发到公开仓库的 Release。
优先使用环境变量 GITEA_TOKEN。没有令牌时使用本机已经保存的 Git 登录。
"""
from __future__ import annotations
import json
import os
import subprocess
from pathlib import Path
import httpx
ROOT = Path(__file__).resolve().parents[1]
API = "https://git.asio.asia/api/v1/repos/nixevol/RaptDramaDump"
ASSET = ROOT / "dist" / "VideosDownTools-windows-x64.zip"
NOTES = "导入 DramaBox 凭据后会先读取个人信息,确认登录成功后才进入。"
PART_SIZE = 40 * 1024 * 1024
def client() -> httpx.Client:
token = os.environ.get("GITEA_TOKEN", "").strip()
headers = {"Authorization": f"token {token}"} if token else {}
auth = None
if not token:
env = os.environ.copy()
env["GIT_TERMINAL_PROMPT"] = "0"
proc = subprocess.run(
["git", "credential", "fill"],
input="protocol=https\nhost=git.asio.asia\n\n",
text=True,
capture_output=True,
env=env,
check=False,
)
username = ""
password = ""
for line in proc.stdout.splitlines():
if line.startswith("username="):
username = line.split("=", 1)[1]
elif line.startswith("password="):
password = line.split("=", 1)[1]
if not username or not password:
raise SystemExit("没有可用的发布登录")
auth = (username, password)
return httpx.Client(headers=headers, auth=auth, timeout=60.0)
def main() -> None:
if not ASSET.is_file():
raise SystemExit("还没有压缩包")
version = str(json.loads((ROOT / "src-tauri" / "tauri.conf.json").read_text(encoding="utf-8")).get("version") or "").strip()
if not version:
raise SystemExit("没有版本号")
with client() as http:
created = http.post(
API + "/releases",
json={
"tag_name": f"v{version}",
"name": version,
"target_commitish": "master",
"body": NOTES,
"draft": False,
"prerelease": False,
},
)
if created.status_code == 409:
created = http.get(API + f"/releases/tags/v{version}")
if created.status_code >= 300:
raise SystemExit(f"创建版本失败 {created.status_code}")
release = created.json()
assets = release.get("assets") if isinstance(release.get("assets"), list) else []
names = {item.get("name") for item in assets if isinstance(item, dict)}
if ASSET.name in names or any(str(name).startswith(ASSET.name + ".part") for name in names):
print(f"已有附件 {version}")
return
_upload(http, release.get("id"), ASSET)
print(f"已发布 {version}")
def _upload(http: httpx.Client, release_id, path: Path) -> None:
data = path.read_bytes()
uploaded = None
try:
uploaded = _post_asset(http, release_id, path.name, data)
except httpx.TransportError:
uploaded = None
if uploaded is not None and uploaded.status_code < 300:
return
if uploaded is not None and uploaded.status_code != 413:
raise SystemExit(f"上传压缩包失败 {uploaded.status_code}")
count = (len(data) + PART_SIZE - 1) // PART_SIZE
for index in range(count):
part = data[index * PART_SIZE : (index + 1) * PART_SIZE]
name = f"{path.name}.part{index + 1:03d}"
try:
uploaded = _post_asset(http, release_id, name, part)
except httpx.TransportError as exc:
raise SystemExit("上传压缩包时连接中断") from exc
if uploaded.status_code >= 300:
raise SystemExit(f"上传压缩包失败 {uploaded.status_code}")
def _post_asset(http: httpx.Client, release_id, name: str, data: bytes) -> httpx.Response:
return http.post(
f"{API}/releases/{release_id}/assets",
params={"name": name},
headers={"Content-Type": "application/octet-stream"},
content=data,
timeout=600.0,
)
if __name__ == "__main__":
main()
+2
View File
@@ -17,6 +17,7 @@ from server.routes.live import router as live_router
from server.routes.play import router as play_router
from server.routes.proxy import router as proxy_router
from server.routes.session import router as session_router
from server.routes.update import router as update_router
from server.services.downloads import downloads
from server.services.huangdou.downloads import downloads as huangdou_downloads
from server.services.dramabox.downloads import downloads as dramabox_downloads
@@ -40,6 +41,7 @@ def create_app() -> FastAPI:
app.include_router(play_router)
app.include_router(live_router)
app.include_router(proxy_router)
app.include_router(update_router)
app.include_router(huangdou_router)
app.include_router(dramabox_router)
+22
View File
@@ -92,6 +92,28 @@ def login_adb(body: AdbLoginBody):
return call(lambda: db_login.import_adb(body.serial, body.language))
@router.get("/login/credential")
def export_credential():
return call(db_login.export_credential)
class CredentialBody(BaseModel):
kind: str = ""
version: int = 0
app: dict = {}
language: str = ""
@router.post("/login/credential/save")
def save_credential():
return call(db_login.save_credential_file)
@router.post("/login/credential")
def import_credential(body: CredentialBody):
return call(lambda: db_login.import_credential(body.model_dump(), body.language))
@router.post("/resume")
def resume():
return call(db_login.resume)
+7 -3
View File
@@ -213,6 +213,7 @@ def list_episodes(body: PlayBody):
"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")),
"lines": len(ep.get("line_urls") or []),
"preview_seconds": ep.get("preview_seconds") or 0,
"locked_reason": ep.get("locked_reason") or "",
}
@@ -283,11 +284,14 @@ def play_key(vid: str, cid: int):
@router.get("/play/{vid}/{cid}/index.m3u8")
def episode_playlist(vid: str, cid: int):
def episode_playlist(vid: str, cid: int, line: int = 0):
row = hd_playlist.episode_src(vid, cid)
src = str(row.get("src") or "").strip()
src = hd_playlist.pick_line(row, line)
if not src:
raise HTTPException(status_code=404, detail=row.get("locked_reason") or "这一集还没有可播放的地址")
detail = row.get("locked_reason") or "这一集还没有可播放的地址"
if line > 0:
detail = "没有下一条线路"
raise HTTPException(status_code=404, detail=detail)
try:
text = hd_playlist.playback_playlist(src)
key = str(row.get("hls_key") or "").strip()
+10
View File
@@ -75,6 +75,16 @@ def play_segment(url: str):
return StreamingResponse(chunks(), media_type=media)
@router.get("/media")
def play_media(url: str):
target = _public_url(url)
try:
text = playlists.media_playlist(target)
except RuntimeError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
return Response(text, media_type="application/vnd.apple.mpegurl", headers={"Cache-Control": "no-store"})
@router.get("/{vid}/{cid}/index.m3u8")
def episode_playlist(vid: int, cid: int):
token = sessions.active_token()
+23
View File
@@ -0,0 +1,23 @@
from fastapi import APIRouter, HTTPException
from server.services import updater
router = APIRouter(prefix="/api/update")
@router.get("")
def check_update():
return updater.check()
@router.get("/status")
def update_status():
return updater.status()
@router.post("/apply")
def apply_update():
try:
return updater.start()
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+37
View File
@@ -669,6 +669,23 @@ class DownloadManager:
live.touch()
def _download_episode(self, drama_id: str, folder: Path, row: dict) -> None:
sources = _source_candidates(row)
if not sources:
self._set_phase(drama_id, row["cid"], "skipped")
return
source_dir, _mp4_path = self._episode_paths(folder, row)
for index, src in enumerate(sources):
attempt = dict(row)
attempt["src"] = src
try:
self._download_one_source(drama_id, folder, attempt)
return
except RuntimeError as exc:
if str(exc) == "已停止" or index + 1 == len(sources):
raise
_clear_source_files(source_dir)
def _download_one_source(self, drama_id: str, folder: Path, row: dict) -> None:
if not row.get("src"):
self._set_phase(drama_id, row["cid"], "skipped")
return
@@ -869,6 +886,26 @@ class DownloadManager:
)
def _source_candidates(row: dict) -> list[str]:
urls = []
src = str(row.get("src") or "").strip()
if src:
urls.append(src)
for item in row.get("line_urls") or []:
text = str(item or "").strip()
if text and text not in urls:
urls.append(text)
return urls
def _clear_source_files(source_dir: Path) -> None:
if not source_dir.is_dir():
return
for child in source_dir.iterdir():
if child.is_file():
child.unlink(missing_ok=True)
def _keep_finished_episode(phase: str, mp4_path: Path) -> bool:
return phase == "done" and mp4_path.is_file() and mp4_path.stat().st_size > 0
+32
View File
@@ -72,6 +72,38 @@ def create_guest(template: dict | None = None) -> dict:
return _guest_from_bootstrap(device, data)
def refresh_account(app: dict) -> dict:
if not isinstance(app, dict):
raise RuntimeError("登录凭据已失效")
data = _post("drama-box/ap001/bootstrap", {
"distinctId": str(app.get("instance_id") or uuid.uuid4()),
"installTime": str(app.get("install_time") or int(time.time() * 1000)),
}, app)
return account_from_bootstrap(app, data)
def account_from_bootstrap(app: dict, data: dict) -> dict:
user = data.get("user") if isinstance(data, dict) else None
if not isinstance(user, dict):
raise RuntimeError("登录凭据已失效")
uid = str(user.get("uid") or user.get("userId") or "").strip()
token = str(user.get("token") or "").strip()
if not uid or uid == "0" or not token:
raise RuntimeError("登录凭据已失效")
expected = str((app or {}).get("user_id") or "").strip()
if expected and uid != expected:
raise RuntimeError("登录凭据已失效")
if not token.startswith("Bearer "):
token = f"Bearer {token}"
nickname = ""
for key in ("nickname", "nickName", "name", "userName"):
nickname = str(user.get(key) or "").strip()
if nickname:
break
vip = user.get("isVip") in (1, True) or str(user.get("isVip") or "").lower() in {"1", "true", "y"}
return {"user_id": uid, "token": token, "name": nickname, "vip": vip}
def ensure_guest() -> dict:
if client.has_guest():
return client.guest
+174 -6
View File
@@ -1,4 +1,7 @@
import json
import secrets
import subprocess
from pathlib import Path
from server.services.dramabox.client import client
from server.services.dramabox.locales import DEFAULT_LANGUAGE, public_list, resolve
@@ -20,19 +23,168 @@ def enter(language: str = "") -> dict:
def import_adb(serial: str, language: str = "") -> dict:
from server.services.dramabox.app_device import read_app_login
record = read_app_login(serial)
return _install_app_login(read_app_login(serial), language)
_CREDENTIAL_KIND = "dramabox-login"
_CREDENTIAL_VERSION = 1
_CREDENTIAL_FIELDS = (
"token",
"device_id",
"android_id",
"user_id",
"name",
"vip",
"cid",
"nchid",
"mchid",
"mbid",
"language",
"current_language",
"country_code",
"install_time",
"instance_id",
"device_score",
"lat",
"afid",
"brand",
"model",
"manufacturer",
"os_version",
"build",
"locale",
"resolution",
)
def export_credential() -> dict:
if not client.has_app():
raise RuntimeError("还没有可导出的登录凭据")
profile = client.profile if isinstance(client.profile, dict) else {}
app = {}
for key in _CREDENTIAL_FIELDS:
if key == "name":
value = str(profile.get("nickname") or profile.get("username") or client.app.get("name") or "")
elif key == "vip":
value = bool(profile.get("badge")) or client.app.get("vip") is True
else:
value = client.app.get(key)
if value not in (None, ""):
app[key] = value
return {"kind": _CREDENTIAL_KIND, "version": _CREDENTIAL_VERSION, "app": app}
def save_credential_file() -> dict:
document = export_credential()
chosen = _pick_credential_path()
if not chosen:
return {"path": ""}
path = Path(chosen)
if path.suffix.lower() != ".json":
path = path.with_suffix(".json")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(document, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return {"path": str(path)}
def _pick_credential_path() -> str:
script = """
Add-Type -AssemblyName System.Windows.Forms
$owner = New-Object System.Windows.Forms.Form
$owner.TopMost = $true
$owner.ShowInTaskbar = $false
$owner.Opacity = 0
$owner.Show()
$owner.Activate()
$dialog = New-Object System.Windows.Forms.SaveFileDialog
$dialog.Title = '导出登录凭据'
$dialog.Filter = 'JSON 文件 (*.json)|*.json'
$dialog.FileName = 'dramabox-login.json'
$dialog.DefaultExt = 'json'
$dialog.AddExtension = $true
$dialog.OverwritePrompt = $true
$downloads = Join-Path $env:USERPROFILE 'Downloads'
if (Test-Path $downloads) { $dialog.InitialDirectory = $downloads }
$result = $dialog.ShowDialog($owner)
$owner.Close()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
[Console]::Out.WriteLine($dialog.FileName)
}
"""
completed = subprocess.run(
["powershell", "-NoProfile", "-STA", "-Command", script],
capture_output=True,
text=True,
encoding="utf-8",
check=False,
)
return (completed.stdout or "").strip()
def import_credential(payload: dict, language: str = "") -> dict:
return _install_app_login(_credential_record(payload), language)
def _install_app_login(record: dict, language: str = "") -> dict:
try:
locale = resolve(language or record.get("language") or client.language or DEFAULT_LANGUAGE)
except RuntimeError:
locale = resolve(DEFAULT_LANGUAGE)
previous = {
"token": client.token,
"language": client.language,
"app": dict(client.app),
"profile": dict(client.profile) if isinstance(client.profile, dict) else {},
}
if not client.token:
client.token = secrets.token_hex(16)
client.language = locale["id"]
client.app = {key: value for key, value in record.items() if key not in {"name", "vip"}}
client.app["language"] = locale["id"]
client.app["current_language"] = locale["id"]
client.profile = _profile_from_record(record, locale)
client.save()
try:
_confirm_account(locale)
except RuntimeError:
client.token = previous["token"]
client.language = previous["language"]
client.app = previous["app"]
client.profile = previous["profile"]
client.save()
raise
from server.services.dramabox.app_api import ensure_guest
ensure_guest()
return {"token": client.token, "profile": client.profile}
def _confirm_account(locale: dict) -> None:
from server.services.dramabox.app_api import refresh_account
try:
fresh = refresh_account(client.app)
except RuntimeError as exc:
text = str(exc).strip()
if "失效" in text:
raise
if any(word in text for word in ("拦截", "没有响应", "没有返回", "网络")):
raise RuntimeError("暂时读不到个人信息,请检查网络后再导入") from exc
raise RuntimeError("登录凭据已失效") from exc
if fresh.get("token"):
client.app["token"] = fresh["token"]
if fresh.get("user_id"):
client.app["user_id"] = fresh["user_id"]
record = dict(client.app)
record["name"] = fresh.get("name") or ""
record["vip"] = fresh.get("vip") is True
client.profile = _profile_from_record(record, locale)
client.save()
def _profile_from_record(record: dict, locale: dict) -> dict:
nickname = str(record.get("name") or record.get("user_id") or "DramaBox")
client.profile = {
return {
"id": record.get("user_id") or "",
"username": nickname,
"nickname": nickname,
@@ -53,10 +205,26 @@ def import_adb(serial: str, language: str = "") -> dict:
"app_login": "1",
"avatarNumUrl": "",
}
client.save()
from server.services.dramabox.app_api import ensure_guest
ensure_guest()
return {"token": client.token, "profile": client.profile}
def _credential_record(payload: dict) -> dict:
if not isinstance(payload, dict) or payload.get("kind") != _CREDENTIAL_KIND:
raise RuntimeError("这不是 DramaBox 登录凭据文件")
if int(payload.get("version") or 0) != _CREDENTIAL_VERSION:
raise RuntimeError("这份凭据文件无法识别")
app = payload.get("app")
if not isinstance(app, dict):
raise RuntimeError("凭据文件里没有登录信息")
token = str(app.get("token") or "").strip()
if token and not token.startswith("Bearer "):
token = f"Bearer {token}"
record = {key: app.get(key) for key in _CREDENTIAL_FIELDS}
record["token"] = token
record["vip"] = app.get("vip") is True or str(app.get("vip") or "").lower() in {"1", "true", "y", "yes"}
missing = [name for name in ("token", "device_id", "android_id", "user_id") if not str(record.get(name) or "").strip()]
if missing:
raise RuntimeError("凭据文件不完整")
return record
def resume() -> dict:
+11 -1
View File
@@ -127,7 +127,17 @@ class HttpClient:
options["content"] = content
if timeout is not None:
options["timeout"] = timeout
return self._client_locked().request(method, url, **options)
last_error: Exception | None = None
for attempt in range(3):
try:
return self._client_locked().request(method, url, **options)
except (httpx.HTTPError, TimeoutError, OSError) as exc:
last_error = exc
with self._lock:
self._close_locked()
if attempt < 2:
time.sleep(0.4 * (attempt + 1))
raise RuntimeError(f"请求失败: {last_error}")
def get_bytes(self, url: str, headers: dict | None = None) -> tuple[bytes, str]:
hdrs = {"User-Agent": "RaptDrama"}
+75 -5
View File
@@ -39,6 +39,9 @@ def login_device(*, force_new: bool = False) -> dict:
if not token:
raise RuntimeError("设备登录没有返回 token")
client.token = token
remember_login_user(data, account=False)
client._renew_blocked.discard("guest")
client.save()
return data
@@ -64,16 +67,54 @@ def login_username(username: str, password: str, channel_code: str = "") -> dict
raise RuntimeError("账号登录没有返回 token")
client.account_token = token
client.account_username = username.strip()
remember_login_user(data, account=True)
client._renew_blocked.discard("account")
client.save()
return data
def user_info(*, identity: str = "guest") -> dict:
data = client.request("/user/info", {}, auth=True, identity=identity)
def user_sign() -> dict:
data = client.request("/user/sign", {}, auth=True, identity="account")
return data if isinstance(data, dict) else {}
def system_info() -> dict:
def user_do_sign() -> dict:
data = client.request("/user/doSign", {}, auth=True, identity="account")
return data if isinstance(data, dict) else {}
def user_info(*, identity: str = "guest") -> dict:
data = client.request("/user/info", {}, auth=True, identity=identity)
if not isinstance(data, dict):
return {}
uid = str(data.get("user_id") or data.get("id") or "").strip()
if uid:
if identity == "account":
client.account_user_id = uid
else:
client.user_id = uid
client.save()
return data
def remember_login_user(data: dict, *, account: bool) -> None:
uid = ""
if isinstance(data, dict):
uid = str(data.get("user_id") or data.get("id") or "").strip()
for key in ("user", "userInfo", "user_info", "info"):
nested = data.get(key)
if isinstance(nested, dict) and not uid:
uid = str(nested.get("user_id") or nested.get("id") or "").strip()
if not uid:
return
if account:
client.account_user_id = uid
else:
client.user_id = uid
def system_info(*, identity: str = "") -> dict:
chosen = identity or ("account" if client.account_token else "guest")
data = client.request(
"/system/info",
{
@@ -81,14 +122,43 @@ def system_info() -> dict:
"channel_code": "",
"share_code": "",
"clipboard_text": "",
"device_info": device_info(),
"package_name": "",
"device_info": device_info(chosen),
"package_name": "dfa03",
},
auth=True,
identity=chosen,
)
return data if isinstance(data, dict) else {}
def remember_api_lines(info: dict | None = None) -> list[str]:
if info is None:
identities = ["account", "guest"] if client.account_token else ["guest"]
info = {}
for name in identities:
try:
info = system_info(identity=name)
break
except TokenExpired:
continue
except RuntimeError:
return list(client.api_lines)
else:
return list(client.api_lines)
if not isinstance(info, dict) or "api_lines" not in info:
return list(client.api_lines)
hosts = []
for item in info.get("api_lines") or []:
if not isinstance(item, str) or not item.startswith("https://"):
continue
host = item.rstrip("/")
if host not in hosts:
hosts.append(host)
client.api_lines = hosts
client.save()
return hosts
def nav_list() -> list[dict]:
data = client.request("/drama/navList", {"with_filters": "1"}, auth=True)
rows = _list_of(data)
+114 -15
View File
@@ -34,6 +34,36 @@ class TokenExpired(RuntimeError):
pass
def _connection_error(exc: BaseException) -> bool:
text = str(exc).lower()
return any(
word in text
for word in (
"ssl",
"unexpected_eof",
"connection",
"timed out",
"timeout",
"10054",
"10060",
"连接",
"重置",
"强迫关闭",
)
)
def present_token(token: str, user_id: str) -> str:
token = (token or "").strip()
user_id = (user_id or "").strip()
if not token or not user_id:
return token
suffix = f"_{user_id}"
if token.endswith(suffix):
return token
return token + suffix
class ApiError(RuntimeError):
def __init__(self, message: str, code=None) -> None:
super().__init__(message)
@@ -50,8 +80,16 @@ class HuangdouClient:
self.guest_session_id = ""
self.guest_device_info: dict = {}
self.token = ""
self.user_id = ""
self.account_token = ""
self.account_user_id = ""
self.account_username = ""
self.renew_account = None
self.renew_guest = None
self._renewing = False
self._renew_blocked: set[str] = set()
self.play_line = ""
self.api_lines: list[str] = []
self.host = DEFAULT_HOST
self.profile: dict = {}
self._load()
@@ -78,8 +116,14 @@ class HuangdouClient:
if isinstance(guest_info, dict) and guest_info:
self.guest_device_info = dict(guest_info)
self.token = str(data.get("token") or "")
self.user_id = str(data.get("user_id") or "")
self.account_token = str(data.get("account_token") or "")
self.account_user_id = str(data.get("account_user_id") or "")
self.account_username = str(data.get("account_username") or "")
self.play_line = str(data.get("play_line") or "")
lines = data.get("api_lines")
if isinstance(lines, list):
self.api_lines = [str(item).rstrip("/") for item in lines if str(item).startswith("https://")]
host = str(data.get("host") or "")
if host.startswith("http://") or host.startswith("https://"):
self.host = host.rstrip("/")
@@ -98,8 +142,12 @@ class HuangdouClient:
"guest_session_id": self.guest_session_id,
"guest_device_info": self.guest_device_info,
"token": self.token,
"user_id": self.user_id,
"account_token": self.account_token,
"account_user_id": self.account_user_id,
"account_username": self.account_username,
"play_line": self.play_line,
"api_lines": self.api_lines,
"host": self.host,
"profile": self.profile,
}
@@ -147,6 +195,7 @@ class HuangdouClient:
self.guest_session_id = session_id_of("")
self.guest_device_info = self._new_device_info()
self.token = ""
self.user_id = ""
self.save()
def roll_account_fingerprint(self) -> None:
@@ -157,6 +206,7 @@ class HuangdouClient:
self.device_info = info
self.device_info_source = "fixed"
self.account_token = ""
self.account_user_id = ""
self.save()
def clear_token(self) -> None:
@@ -165,7 +215,9 @@ class HuangdouClient:
self.guest_session_id = ""
self.guest_device_info = {}
self.account_token = ""
self.account_user_id = ""
self.account_username = ""
self.user_id = ""
self.profile = {}
self.save()
@@ -177,26 +229,71 @@ class HuangdouClient:
return self.host
def request(self, path: str, data: dict | None = None, *, auth: bool = True, identity: str = "guest") -> dict | list | None:
try:
return self._dispatch(path, data, auth=auth, identity=identity)
except TokenExpired:
if not auth or self._renewing or identity in self._renew_blocked:
raise
self._renewing = True
try:
renew = self.renew_account if identity == "account" else self.renew_guest
renewed = bool(renew and renew())
finally:
self._renewing = False
if not renewed:
self._renew_blocked.add(identity)
raise
self._renew_blocked.discard(identity)
return self._dispatch(path, data, auth=auth, identity=identity)
def _dispatch(self, path: str, data: dict | None, *, auth: bool, identity: str) -> 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
for _ in range(2):
try:
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
hosts = [self.host] if token else self._request_hosts()
for host in hosts:
for _ in range(2):
try:
payload = self._call(
host,
path,
data or {},
token=self._presented_token(token, identity) if auth else "",
device_id=device_id,
session_id=session_id,
user_agent=user_agent,
)
if host != self.host:
self.host = host
self.save()
return payload
except (TokenExpired, ApiError):
raise
except RuntimeError as exc:
last_error = exc
if not _connection_error(exc):
raise
raise last_error or RuntimeError("网络请求异常")
def _presented_token(self, token: str, identity: str) -> str:
if identity == "account":
user_id = self.account_user_id
if not user_id and self.account_token:
profile = self.profile if isinstance(self.profile, dict) else {}
if str(profile.get("has_login") or "") == "1":
user_id = str(profile.get("id") or "")
else:
user_id = self.user_id
return present_token(token, user_id)
def _request_hosts(self) -> list[str]:
hosts = []
for host in [self.host, *self.api_lines]:
text = str(host or "").rstrip("/")
if text.startswith("https://") and text not in hosts:
hosts.append(text)
return hosts or [self.host]
def _identity(self, identity: str, auth: bool) -> tuple[str, str, str, dict]:
if identity == "account":
self._ensure_fingerprint()
@@ -248,6 +345,8 @@ class HuangdouClient:
try:
response = http.send("POST", url, headers=headers, content=encrypt_body(body, request_id), timeout=30.0)
except Exception as exc:
if _connection_error(exc):
raise RuntimeError("连接中断,请再试一次") from exc
raise RuntimeError(f"请求失败: {exc}") from exc
if response.status_code != 200:
raise RuntimeError(f"网络请求异常 ({response.status_code})")
+1 -1
View File
@@ -12,7 +12,7 @@ from cryptography.hazmat.primitives.padding import PKCS7
WEB_AES_KEY = "7961beb44246e3012ce228d6b5ced05a"
IMAGE_AES_KEY = "525202f9149e061d"
SIGN_PREFIX = "Dart"
APP_VERSION = "2.0.0"
APP_VERSION = "1.0.0"
DEVICE_TYPE = "web"
LANG = "zh-CN"
USER_AGENT = (
+86 -4
View File
@@ -6,8 +6,6 @@ from server.services.huangdou.covers import covers as huangdou_covers
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)
@@ -19,6 +17,7 @@ def enter(host: str = "") -> dict:
profile = public_profile(None)
client.profile = profile
client.save()
api.remember_api_lines()
return {"token": client.token, "profile": profile}
@@ -44,7 +43,9 @@ def login_account(username: str, password: str, rotate_fingerprint: bool = False
profile = public_profile(info if isinstance(info, dict) else {})
client.profile = profile
client.save()
return {"token": client.token, "profile": profile}
api.remember_api_lines()
sign = claim_daily_sign()
return {"token": client.token, "profile": client.profile, "sign": sign}
def resume() -> dict:
@@ -63,7 +64,54 @@ def current(token: str) -> dict:
profile = public_profile(account)
client.profile = profile
client.save()
return {"token": client.token, "profile": profile}
sign = claim_daily_sign()
return {"token": client.token, "profile": client.profile, "sign": sign}
def claim_daily_sign() -> dict | None:
if not client.account_token:
return None
try:
status = api.user_sign()
except (TokenExpired, RuntimeError):
return None
if _signed_today(status.get("today_signed") if isinstance(status, dict) else None):
return None
try:
result = api.user_do_sign()
except (TokenExpired, RuntimeError):
return None
if not isinstance(result, dict):
result = {}
balance = result.get("balance")
if balance not in (None, "") and isinstance(client.profile, dict):
client.profile["balance"] = balance
client.profile["score"] = _number(balance)
client.save()
return {"message": _sign_message(result)}
def _signed_today(value) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, (int, float)) and not isinstance(value, bool):
return value != 0
text = str(value or "").strip().lower()
return text in {"y", "1", "true", "yes"}
def _sign_message(result: dict) -> str:
name = str(result.get("prize_name") or "").strip()
try:
amount = int(float(str(result.get("prize_num") or "0")))
except (TypeError, ValueError):
amount = 0
if amount > 0 and name:
return f"签到成功,获得 {name} × {amount}"
if amount > 0:
return f"签到成功,获得 {amount} 积分"
text = str(result.get("msg") or "").strip()
return text or "签到成功"
def account_balance() -> int:
@@ -169,6 +217,40 @@ def _truthy(value) -> bool:
return text in {"1", "true", "y", "yes", "vip"}
def _renew_account() -> bool:
from server.services.huangdou.accounts import load
username = client.account_username.strip()
if not username:
return False
password = ""
for item in load():
if item.get("username") == username:
password = str(item.get("password") or "")
break
if not password:
return False
try:
api.login_username(username, password)
except Exception:
return False
return bool(client.account_token)
def _renew_guest() -> bool:
if not client.guest_device_id:
return False
try:
api.login_device(force_new=False)
except Exception:
return False
return bool(client.token)
client.renew_account = _renew_account
client.renew_guest = _renew_guest
def _number(value) -> int:
try:
return int(float(str(value or "0")))
+128 -31
View File
@@ -6,7 +6,7 @@ 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.client import TokenExpired, client
from server.services.huangdou.coins import (
PAID_TYPES,
VIP_TYPES,
@@ -53,12 +53,13 @@ def episode_src(drama_id: str, cid: int) -> dict:
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
stale = not row.get("lines_ready")
if (row.get("playable") and stale) or row.get("locked_reason") == "登录已失效":
played = _play_rows(drama_id, [dict(row)], allow_buy=False)
updated = played[0] if played else row
_store_row(drama_id, updated)
return updated
return row
def playback_playlist(src: str) -> str:
@@ -102,31 +103,97 @@ def store_fallback_key(source_dir: Path, key: str) -> None:
(source_dir / "hls.key").write_bytes(raw)
def _choose_src(played: dict) -> tuple[str, str]:
candidates: list[str] = []
for value in (played.get("m3u8"),):
text = str(value or "").strip()
if text:
candidates.append(text)
def _preview_url(url: str) -> bool:
path = (url or "").split("?", 1)[0].lower()
return path.endswith("preview.mp4") or "/preview." in path
def _line_urls(played: dict, *, allow_preview: bool) -> list[str]:
urls: list[str] = []
def add(value) -> None:
url = str(value or "").strip()
if not url or url in urls:
return
if not allow_preview and _preview_url(url):
return
urls.append(url)
lines = played.get("lines") if isinstance(played.get("lines"), list) else []
for line in lines:
if not isinstance(line, dict):
continue
url = str(line.get("url") or "").strip()
if url:
candidates.append(url)
preview = str(played.get("preview_m3u8") or "").strip()
if preview:
candidates.append(preview)
for url in candidates:
if url and not is_direct_media(url):
if isinstance(line, dict):
add(line.get("url"))
add(played.get("m3u8"))
if allow_preview:
add(played.get("preview_m3u8"))
return urls
def _open_src(url: str) -> tuple[str, str] | None:
if is_direct_media(url):
return None if _preview_url(url) else (url, "file")
try:
text = http.read_text(url, headers=_cdn_headers())
except Exception:
return None
if "#EXTM3U" not in text.upper():
return None
return url, "hls"
def _choose_src(played: dict) -> tuple[str, str]:
urls = _line_urls(played, allow_preview=False) or _line_urls(played, allow_preview=True)
for url in urls:
if not is_direct_media(url):
return url, "hls"
for url in candidates:
if is_direct_media(url):
for url in urls:
if is_direct_media(url) and not _preview_url(url):
return url, "file"
return "", ""
def _ordered_line_urls(played: dict, src: str) -> list[str]:
urls = _line_urls(played, allow_preview=False)
chosen = (src or "").strip()
if chosen and not _preview_url(chosen):
urls = [chosen, *[url for url in urls if url != chosen]]
return urls
def pick_line(row: dict, line: int) -> str:
urls: list[str] = []
for item in row.get("line_urls") or []:
text = str(item or "").strip()
if text and text not in urls and not _preview_url(text):
urls.append(text)
src = str(row.get("src") or "").strip()
if src and not _preview_url(src) and src not in urls:
urls.insert(0, src)
if line < 0:
line = 0
if not urls:
return src if line == 0 else ""
if line >= len(urls):
return ""
return urls[line]
def _resolve_src(played: dict, *, allow_preview: bool) -> tuple[str, str]:
for url in _line_urls(played, allow_preview=False):
opened = _open_src(url)
if opened:
return opened
if not allow_preview:
return "", ""
for url in _line_urls(played, allow_preview=True):
if _preview_url(url) and is_direct_media(url):
return url, "file"
opened = _open_src(url)
if opened:
return opened
return "", ""
def apply_hls_key(text: str, source_dir: Path, key: str) -> str:
secret = (key or "").strip()
if not secret:
@@ -210,6 +277,8 @@ def _skeleton_row(item: dict, *, account_vip: bool) -> dict | None:
"duration": _int(item.get("duration")),
"methods": item.get("methods") if isinstance(item.get("methods"), list) else [],
"is_preview": False,
"line_urls": [],
"lines_ready": False,
"preview_seconds": 0,
"preview_m3u8": "",
"hls_key": "",
@@ -227,6 +296,7 @@ def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[
if not allow_buy or not client.account_token:
row["src"] = ""
row["playable"] = False
row["lines_ready"] = True
row["locked_reason"] = public_lock_reason(row, row.get("locked_reason") or "")
return row
try:
@@ -234,36 +304,47 @@ def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[
except RuntimeError as exc:
row["src"] = ""
row["playable"] = False
row["lines_ready"] = True
row["locked_reason"] = public_lock_reason(row, str(exc))
return row
row["is_buy"] = True
row["needs_coin"] = False
row["points"] = 0
vip_episode = episode_kind(row) in VIP_TYPES
identity = "account" if _uses_account(row) else "guest"
try:
played = api.drama_play(drama_id, int(row["cid"]), identity=identity)
except TokenExpired:
row["src"] = ""
row["playable"] = False
row["is_preview"] = False
row["lines_ready"] = False
row["locked_reason"] = "登录已失效"
return row
except RuntimeError as exc:
row["src"] = ""
row["playable"] = False
row["lines_ready"] = True
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()
row["is_preview"] = played.get("is_preview") is True
row["preview_seconds"] = _int(played.get("preview_seconds"))
row["preview_m3u8"] = preview
src, kind = _choose_src(played)
src, kind = _resolve_src(played, allow_preview=not vip_episode)
row["src"] = src
row["src_kind"] = kind
row["line_urls"] = _ordered_line_urls(played, src)
row["lines_ready"] = True
if src:
row["playable"] = True
if kind == "file" or row["is_preview"]:
row["is_preview"] = True
row["is_preview"] = (not vip_episode) and (kind == "file" and _preview_url(src) or played.get("is_preview") is True and _preview_url(src))
row["locked_reason"] = ""
row["points"] = 0
else:
row["playable"] = False
row["locked_reason"] = _lock_reason(row)
row["is_preview"] = False
row["locked_reason"] = _vip_lock_reason(row) if vip_episode else _lock_reason(row)
return row
updated = []
@@ -278,6 +359,20 @@ def _play_rows(drama_id: str, skeleton: list[dict], *, allow_buy: bool) -> list[
return updated
def _vip_lock_reason(row: dict) -> str:
if not client.account_token:
return "需要 VIP"
try:
api.user_info(identity="account")
except TokenExpired:
client.account_token = ""
client.save()
return "登录已失效"
except RuntimeError:
return "这一集暂时不能播放"
return "这一集暂时不能播放"
def _uses_account(row: dict) -> bool:
if not client.account_token:
return False
@@ -311,12 +406,14 @@ def _keep_sources(cached: list[dict], fresh: list[dict]) -> list[dict]:
merged = []
for row in fresh:
old = previous.get(int(row["cid"]))
if old and old.get("is_preview"):
if old and old.get("is_preview") and episode_kind(row) not in VIP_TYPES:
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["line_urls"] = old.get("line_urls") or []
row["lines_ready"] = bool(old.get("lines_ready"))
row["preview_seconds"] = old.get("preview_seconds") or 0
row["preview_m3u8"] = old.get("preview_m3u8") or ""
merged.append(row)
+38
View File
@@ -509,6 +509,8 @@ def episode_src(token: str, device: DeviceProfile | None, vid: int, cid: int) ->
def playback_playlist(master_url: str) -> str:
master_text = http.read_text(master_url)
if audio_rendition_uris(master_text):
return rewrite_master_for_playback(master_text, master_url)
variant_rel = next(
(line.strip() for line in master_text.splitlines() if line.strip() and not line.startswith("#")),
"",
@@ -521,6 +523,42 @@ def playback_playlist(master_url: str) -> str:
return _rewrite_playlist(http.read_text(variant_url), variant_url)
def media_playlist(url: str) -> str:
return _rewrite_playlist(http.read_text(url), url)
def rewrite_master_for_playback(text: str, base: str) -> str:
lines = []
for line in text.splitlines():
stripped = line.strip()
if not stripped:
lines.append(line)
continue
if stripped.startswith("#"):
lines.append(_rewrite_master_tag(line, base))
continue
lines.append(_playlist_proxy_url(urljoin(base, stripped)))
return "\n".join(lines) + "\n"
def _playlist_proxy_url(url: str) -> str:
return "/api/play/media?url=" + quote(url, safe="")
def _rewrite_master_tag(line: str, base: str) -> str:
updated = line
if "TYPE=AUDIO" in line.upper() and re.search(r"DEFAULT=NO", line, re.I):
updated = re.sub(r"DEFAULT=NO", "DEFAULT=YES", updated, count=1, flags=re.I)
def replace(match: re.Match) -> str:
target = urljoin(base, match.group(1))
path = target.split("?", 1)[0].lower()
proxy = _playlist_proxy_url(target) if path.endswith(".m3u8") else _proxy_url(target)
return 'URI="' + proxy + '"'
return re.sub(r'URI="([^"]*)"', replace, updated)
def _proxy_url(url: str) -> str:
return "/api/play/segment?url=" + quote(url, safe="")
+276
View File
@@ -0,0 +1,276 @@
import json
import os
import re
import shutil
import subprocess
import tempfile
import threading
import zipfile
from pathlib import Path
import httpx
ROOT = Path(__file__).resolve().parents[2]
RELEASE_URL = "https://git.asio.asia/api/v1/repos/nixevol/RaptDramaDump/releases/latest"
ASSET_NAME = "VideosDownTools-windows-x64.zip"
EXE_NAME = "VideosDownTools.exe"
_URL_RE = re.compile(r"https?://\S+")
_lock = threading.Lock()
_state = {
"state": "idle",
"percent": 0,
"message": "",
"latest": "",
"notes": "",
"urls": [],
}
_worker: threading.Thread | None = None
def current_version() -> str:
installed = Path.cwd() / "version.json"
if installed.is_file():
try:
data = json.loads(installed.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
data = {}
version = str(data.get("version") or "").strip()
if version:
return version
config = ROOT / "src-tauri" / "tauri.conf.json"
try:
data = json.loads(config.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return "0.0.0"
return str(data.get("version") or "0.0.0").strip() or "0.0.0"
def is_packaged() -> bool:
root = Path.cwd()
return (root / "runtime" / "python" / "python.exe").is_file() and (root / EXE_NAME).is_file()
def parse_version(value: str) -> tuple[int, ...]:
parts: list[int] = []
for piece in str(value or "").strip().lstrip("vV").split("."):
digits = ""
for char in piece:
if not char.isdigit():
break
digits += char
if not digits:
break
parts.append(int(digits))
return tuple(parts) or (0,)
def is_newer(remote: str, local: str) -> bool:
return parse_version(remote) > parse_version(local)
def normalize_version(value: str) -> str:
return str(value or "").strip().lstrip("vV") or "0.0.0"
def public_notes(value: str) -> str:
text = _URL_RE.sub("", value or "")
text = re.sub(r"[ \t]+\n", "\n", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def release_urls(payload: dict) -> list[str]:
assets = payload.get("assets") if isinstance(payload.get("assets"), list) else []
named: dict[str, str] = {}
for item in assets:
if not isinstance(item, dict):
continue
name = str(item.get("name") or "")
url = str(item.get("browser_download_url") or "").strip()
if name and url:
named[name] = url
if named.get(ASSET_NAME):
return [named[ASSET_NAME]]
parts = sorted(name for name in named if name.startswith(ASSET_NAME + ".part"))
return [named[name] for name in parts]
def describe_release(payload: dict, current: str) -> dict | None:
if not isinstance(payload, dict) or payload.get("draft") or payload.get("prerelease"):
return None
latest = normalize_version(str(payload.get("tag_name") or payload.get("name") or ""))
if not is_newer(latest, current):
return None
urls = release_urls(payload)
if not urls:
return None
return {"latest": latest, "notes": public_notes(str(payload.get("body") or "")), "urls": urls}
def check() -> dict:
current = current_version()
found = None
try:
response = httpx.get(RELEASE_URL, timeout=15.0, follow_redirects=True, trust_env=True)
if response.status_code != 404:
response.raise_for_status()
body = response.json()
found = describe_release(body, current) if isinstance(body, dict) else None
except (httpx.HTTPError, OSError, ValueError):
found = None
with _lock:
if found:
_state["latest"] = found["latest"]
_state["notes"] = found["notes"]
_state["urls"] = list(found["urls"])
else:
_state["urls"] = []
return {
"available": bool(found),
"current": current,
"latest": found["latest"] if found else current,
"notes": found["notes"] if found else "",
"can_apply": bool(found) and is_packaged(),
}
def status() -> dict:
with _lock:
return {
"state": _state["state"],
"percent": _state["percent"],
"message": _state["message"],
}
def start() -> dict:
global _worker
if not is_packaged():
raise RuntimeError("请使用发布的程序更新")
with _lock:
if not _state["urls"]:
raise RuntimeError("没有可安装的更新")
if _worker is not None and _worker.is_alive():
return status()
_state["state"] = "downloading"
_state["percent"] = 0
_state["message"] = "正在下载更新"
_worker = threading.Thread(target=_install, name="videosdowntools-update", daemon=True)
_worker.start()
return status()
def _set(**values) -> None:
with _lock:
_state.update(values)
def _install() -> None:
with _lock:
urls = list(_state["urls"])
temp_root = Path(tempfile.mkdtemp(prefix="VideosDownTools-update-"))
archive = temp_root / ASSET_NAME
try:
with archive.open("wb") as handle:
for index, url in enumerate(urls, start=1):
_download(url, handle, index, len(urls))
source = _extract(archive, temp_root / "package")
_launch_updater(source)
except Exception:
shutil.rmtree(temp_root, ignore_errors=True)
_set(state="failed", message="更新没有完成,请稍后再试")
return
_set(state="restarting", percent=100, message="正在重新打开")
def _download(url: str, handle, index: int, count: int) -> None:
done = 0
with httpx.stream("GET", url, timeout=600.0, follow_redirects=True, trust_env=True) as response:
response.raise_for_status()
total = int(response.headers.get("content-length") or 0)
for chunk in response.iter_bytes(256 * 1024):
if not chunk:
continue
handle.write(chunk)
done += len(chunk)
if total:
part = min(99, done * 100 // total)
overall = int(((index - 1) + part / 100) / count * 99)
_set(percent=overall, message="正在下载更新")
if done <= 0:
raise RuntimeError("更新包是空的")
def _extract(archive: Path, dest: Path) -> Path:
dest.mkdir(parents=True, exist_ok=True)
root = dest.resolve()
with zipfile.ZipFile(archive) as packed:
for info in packed.infolist():
target = (dest / info.filename).resolve()
if target != root and root not in target.parents:
raise RuntimeError("更新包内容无效")
packed.extractall(dest)
for path in dest.rglob(EXE_NAME):
if path.is_file():
return path.parent
raise RuntimeError("更新包里没有程序")
def _launch_updater(source: Path) -> None:
script = Path(tempfile.gettempdir()) / "VideosDownTools-update.ps1"
script.write_text(_UPDATER_SCRIPT, encoding="utf-8")
flags = 0x08000000 | 0x00000200 | 0x01000000
subprocess.Popen(
[
"powershell.exe",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
str(script),
"-ParentId",
str(os.getppid()),
"-WorkerId",
str(os.getpid()),
"-Source",
str(source),
"-Dest",
str(Path.cwd()),
"-ExeName",
EXE_NAME,
],
creationflags=flags,
close_fds=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
_UPDATER_SCRIPT = r"""param(
[int]$ParentId = 0,
[int]$WorkerId = 0,
[string]$Source,
[string]$Dest,
[string]$ExeName
)
$ErrorActionPreference = "Continue"
function Wait-Gone([int]$ProcessId) {
if ($ProcessId -le 0) { return }
while (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue) {
Start-Sleep -Milliseconds 400
}
}
Wait-Gone $ParentId
Wait-Gone $WorkerId
Start-Sleep -Seconds 1
& robocopy $Source $Dest /E /XD download cache /R:2 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Null
$exe = Join-Path $Dest $ExeName
if (Test-Path -LiteralPath $exe) {
Start-Process -FilePath $exe -WorkingDirectory $Dest | Out-Null
}
Start-Sleep -Seconds 2
Remove-Item -LiteralPath $Source -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
"""
+5 -5
View File
@@ -54,11 +54,11 @@ fn prepare_webview_runtime(root: &Path) {
if webview_runtime_installed() {
return;
}
let installer = root
.join("vendor")
.join("webview2")
.join("MicrosoftEdgeWebView2RuntimeInstallerX64.exe");
if installer.is_file() {
let installer = ["MicrosoftEdgeWebview2Setup.exe", "MicrosoftEdgeWebView2RuntimeInstallerX64.exe"]
.into_iter()
.map(|name| root.join("vendor").join("webview2").join(name))
.find(|path| path.is_file());
if let Some(installer) = installer {
let _ = Command::new(installer).args(["/silent", "/install"]).status();
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "VideosDownTools",
"version": "0.1.0",
"version": "0.1.4",
"identifier": "com.videosdowntools.desktop",
"build": {
"beforeDevCommand": {
+7
View File
@@ -23,6 +23,13 @@ def test_guess_and_saved_playlist() -> None:
video.m3u8
"""
assert audio_rendition_uris(master) == ["audio/audio.m3u8"]
from server.services.playlist import rewrite_master_for_playback
played = rewrite_master_for_playback(master, "https://cdn.example/show/playlist.m3u8")
assert "DEFAULT=YES" in played
assert "/api/play/media?url=" in played
assert "audio%2Faudio.m3u8" in played or "audio/audio.m3u8" in played
assert played.strip().splitlines()[-1].startswith("/api/play/media?url=")
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp)
+62
View File
@@ -0,0 +1,62 @@
from server.services.dramabox.app_api import account_from_bootstrap
from server.services.dramabox.login import _credential_record
def test_credential_file_is_one_json_document() -> None:
document = {
"kind": "dramabox-login",
"version": 1,
"app": {
"token": "raw-token",
"device_id": "ad-1",
"android_id": "android-1",
"user_id": "88",
"vip": "y",
"name": "示例",
},
}
record = _credential_record(document)
assert record["token"] == "Bearer raw-token"
assert record["device_id"] == "ad-1"
assert record["android_id"] == "android-1"
assert record["user_id"] == "88"
assert record["vip"] is True
assert record["name"] == "示例"
for broken in (
{},
{"kind": "other", "version": 1, "app": document["app"]},
{"kind": "dramabox-login", "version": 2, "app": document["app"]},
{"kind": "dramabox-login", "version": 1, "app": {"token": "Bearer x"}},
):
try:
_credential_record(broken)
except RuntimeError:
continue
raise AssertionError("不完整的凭据文件应被拒绝")
def test_account_profile_must_match_the_credential() -> None:
app = {"user_id": "88", "token": "Bearer old"}
fresh = account_from_bootstrap(app, {"user": {"uid": "88", "token": "new", "nickname": "阿花", "isVip": 1}})
assert fresh["token"] == "Bearer new"
assert fresh["name"] == "阿花"
assert fresh["vip"] is True
try:
account_from_bootstrap(app, {"user": {"uid": "99", "token": "new", "nickname": "别人"}})
except RuntimeError as exc:
assert "失效" in str(exc)
else:
raise AssertionError("用户编号不一致应视为未登录")
try:
account_from_bootstrap(app, {})
except RuntimeError as exc:
assert "失效" in str(exc)
else:
raise AssertionError("没有个人信息应视为未登录")
if __name__ == "__main__":
test_credential_file_is_one_json_document()
test_account_profile_must_match_the_credential()
print("ok")
+14
View File
@@ -115,6 +115,19 @@ def test_saved_accounts_roundtrip() -> None:
assert accounts_module.load()[0]["password"] == "secret-one"
def test_sign_only_when_today_is_open() -> None:
from server.services.huangdou.login import _sign_message, _signed_today
assert not _signed_today(None)
assert not _signed_today("n")
assert not _signed_today("0")
assert _signed_today("y")
assert _signed_today("Y")
assert _signed_today(True)
assert _sign_message({"prize_name": "金币", "prize_num": 10}) == "签到成功,获得 金币 × 10"
assert _sign_message({"msg": "已经签过了"}) == "已经签过了"
def test_host_keeps_scheme() -> None:
assert normalize_host("pmihlvee.cc") == "https://pmihlvee.cc"
assert normalize_host("https://example.com/") == "https://example.com"
@@ -126,5 +139,6 @@ if __name__ == "__main__":
test_payment_and_episode_choice()
test_account_login_reuses_the_same_device_fingerprint()
test_saved_accounts_roundtrip()
test_sign_only_when_today_is_open()
test_host_keeps_scheme()
print("ok")
+39 -1
View File
@@ -1,5 +1,6 @@
from server.services.downloads import _local_master
from server.services.huangdou.playlist import _choose_src
from server.services.huangdou.client import present_token
from server.services.huangdou.playlist import _choose_src, _ordered_line_urls, pick_line
from server.services.playlist import expand_variant, is_direct_media, is_media_playlist
@@ -21,6 +22,16 @@ def test_direct_media_and_hls_choice() -> None:
assert kind == "hls"
assert src.endswith("play.m3u8?x=1")
src, kind = _choose_src({
"m3u8": "https://host.example/chapters/3/preview.mp4",
"lines": [
{"name": "free", "url": "https://host.example/chapters/3/preview.mp4"},
{"name": "line2", "url": "https://host.example/chapters/3/play.m3u8"},
],
})
assert kind == "hls"
assert src.endswith("play.m3u8")
src, kind = _choose_src({
"m3u8": "",
"preview_m3u8": "https://cdn.example/chapters/2/preview-r10.mp4",
@@ -29,6 +40,24 @@ def test_direct_media_and_hls_choice() -> None:
assert kind == "file"
assert src.endswith(".mp4")
played = {
"m3u8": "https://host.example/api/drama/hls/id/3/play.m3u8?line=free",
"preview_m3u8": "https://cdn.example/chapters/3/preview.mp4",
"lines": [
{"name": "free", "url": "https://host.example/api/drama/hls/id/3/play.m3u8?line=free"},
{"name": "line2", "url": "https://host.example/api/drama/hls/id/3/play.m3u8?line=line2"},
{"name": "line3", "url": "https://host.example/api/drama/hls/id/3/play.m3u8?line=line3"},
],
}
ordered = _ordered_line_urls(played, played["lines"][1]["url"])
assert [item.split("line=")[1] for item in ordered] == ["line2", "free", "line3"]
row = {"src": ordered[0], "line_urls": ordered}
assert pick_line(row, 0).endswith("line=line2")
assert pick_line(row, 1).endswith("line=free")
assert pick_line(row, 3) == ""
assert pick_line({"src": "https://cdn.example/chapters/3/preview.mp4", "line_urls": []}, 0).endswith("preview.mp4")
assert pick_line({"src": "https://cdn.example/chapters/3/preview.mp4", "line_urls": []}, 1) == ""
try:
expand_variant("https://cdn.example/preview-r10.mp4")
except RuntimeError as exc:
@@ -37,6 +66,14 @@ def test_direct_media_and_hls_choice() -> None:
raise AssertionError("mp4 不应走播放列表")
def test_request_token_includes_user_id() -> None:
assert present_token("abc", "12345678") == "abc_12345678"
assert present_token("a_bc", "12345678") == "a_bc_12345678"
assert present_token("abc_12345678", "12345678") == "abc_12345678"
assert present_token("abc", "") == "abc"
assert present_token("", "12345678") == ""
def test_catalog_follows_pages_until_the_api_stops() -> None:
from server.services.huangdou.catalog import _take_new
@@ -59,5 +96,6 @@ def test_catalog_follows_pages_until_the_api_stops() -> None:
if __name__ == "__main__":
test_direct_media_and_hls_choice()
test_request_token_includes_user_id()
test_catalog_follows_pages_until_the_api_stops()
print("ok")
+47
View File
@@ -0,0 +1,47 @@
from server.services.updater import describe_release, is_newer, public_notes
def test_version_order_and_public_notes() -> None:
assert is_newer("0.1.1", "0.1.0")
assert is_newer("v0.2.0", "0.1.9")
assert not is_newer("0.1.0", "0.1.0")
assert not is_newer("0.1.0", "0.1.1")
assert "http" not in public_notes("修复播放。\n详情 https://example.com/repo/releases/1")
def test_release_needs_the_package_asset() -> None:
current = "0.1.0"
missing = describe_release({"tag_name": "v0.1.1", "body": "更新", "assets": []}, current)
assert missing is None
found = describe_release(
{
"tag_name": "v0.1.1",
"body": "打开时提示更新。 https://example.com/hidden",
"assets": [{"name": "VideosDownTools-windows-x64.zip", "browser_download_url": "https://example.com/app.zip"}],
},
current,
)
assert found is not None
assert found["latest"] == "0.1.1"
assert "http" not in found["notes"]
assert found["urls"] == ["https://example.com/app.zip"]
parts = describe_release(
{
"tag_name": "v0.1.2",
"body": "",
"assets": [
{"name": "VideosDownTools-windows-x64.zip.part002", "browser_download_url": "https://example.com/b"},
{"name": "VideosDownTools-windows-x64.zip.part001", "browser_download_url": "https://example.com/a"},
],
},
current,
)
assert parts is not None
assert parts["urls"] == ["https://example.com/a", "https://example.com/b"]
assert describe_release({"tag_name": "v0.1.0", "assets": [{"name": "VideosDownTools-windows-x64.zip", "browser_download_url": "https://example.com/app.zip"}]}, current) is None
if __name__ == "__main__":
test_version_order_and_public_notes()
test_release_needs_the_package_asset()
print("ok")
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "videosdowntools-ui",
"private": true,
"version": "0.1.0",
"version": "0.1.4",
"type": "module",
"scripts": {
"dev": "vite",
+166
View File
@@ -140,6 +140,7 @@ const dramaboxLangs = ref<{ label: string; value: string }[]>([]);
const accountBusy = ref(false);
const activeProxyUrl = ref("");
const profileError = ref("");
const signNotice = ref("");
const method = ref<Method>("guest");
const email = ref("");
const password = ref("");
@@ -152,6 +153,8 @@ const token = ref("");
const profile = ref<Profile | null>(null);
const dramaboxLoggedIn = computed(() => profile.value?.has_login === "1");
const dramaboxDeviceReady = computed(() => devices.value.some((item) => item.state === "device"));
const credentialNote = ref("");
const credentialFile = ref<HTMLInputElement | null>(null);
const page = ref<"download" | "profile" | "progress" | "settings" | "play">("download");
const playing = ref<{ id: string | number; title: string; image: string } | null>(null);
const progressCount = ref(0);
@@ -1035,6 +1038,7 @@ async function loginHuangdou(asGuest = false) {
}
token.value = payload.token;
profile.value = payload.profile;
takeSign(payload);
writeSavedToken(payload.token);
page.value = "download";
startLive();
@@ -1092,6 +1096,73 @@ async function loginDramaboxAdb() {
}
}
function exportDramaboxCredential() {
const target = token.value ? profileError : error;
target.value = "";
credentialNote.value = "";
accountBusy.value = Boolean(token.value);
busy.value = !token.value;
fetch("/api/dramabox/login/credential/save", { method: "POST" })
.then(async (response) => {
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(typeof payload.detail === "string" ? payload.detail : "导出失败");
}
const path = typeof payload.path === "string" ? payload.path : "";
credentialNote.value = path ? `已保存到 ${path}` : "已取消";
})
.catch((exc) => {
target.value = exc instanceof Error ? exc.message : "导出失败";
})
.finally(() => {
busy.value = false;
accountBusy.value = false;
});
}
function pickDramaboxCredential() {
credentialFile.value?.click();
}
async function onDramaboxCredential(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
if (!file) return;
const inside = Boolean(token.value);
error.value = "";
profileError.value = "";
if (inside) accountBusy.value = true;
else busy.value = true;
try {
const text = await file.text();
const document = JSON.parse(text);
const response = await fetch("/api/dramabox/login/credential", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...document, language: dramaboxLang.value }),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(typeof payload.detail === "string" ? payload.detail : "导入失败");
}
token.value = payload.token;
profile.value = payload.profile;
writeSavedToken(payload.token);
if (!inside) {
page.value = "download";
startLive();
}
} catch (exc) {
const message = exc instanceof Error ? exc.message : "导入失败";
if (inside) profileError.value = message;
else error.value = message;
} finally {
busy.value = false;
accountBusy.value = false;
}
}
async function loginDramabox() {
error.value = "";
busy.value = true;
@@ -1194,6 +1265,11 @@ function applyLive(payload: { downloads?: { active: LiveJob[]; done: LiveJob[];
if (payload.profile) profile.value = payload.profile;
}
function takeSign(payload: { sign?: { message?: string } | null }) {
const message = payload.sign?.message?.trim() || "";
if (message) signNotice.value = message;
}
function startLive() {
stopLive();
const protocol = location.protocol === "https:" ? "wss" : "ws";
@@ -1255,6 +1331,11 @@ async function logout() {
const closeAsk = ref(false);
const closeCount = ref(0);
let allowClose = false;
const updateOpen = ref(false);
const updateInfo = ref({ latest: "", current: "", notes: "", can_apply: false });
const updateBusy = ref(false);
const updateMessage = ref("");
let updateTimer = 0;
function inTauri() {
return "__TAURI_INTERNALS__" in window;
@@ -1297,9 +1378,68 @@ async function confirmQuit() {
await getCurrentWindow().destroy();
}
async function checkForUpdate() {
try {
const response = await fetch("/api/update");
if (!response.ok) return;
const payload = await response.json();
if (!payload.available) return;
updateInfo.value = {
latest: String(payload.latest || ""),
current: String(payload.current || ""),
notes: String(payload.notes || ""),
can_apply: Boolean(payload.can_apply),
};
updateMessage.value = "";
updateOpen.value = true;
} catch {
// 检查失败时不打断使用
}
}
async function confirmUpdate() {
updateBusy.value = true;
updateMessage.value = "正在下载更新";
try {
const response = await fetch("/api/update/apply", { method: "POST" });
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
updateBusy.value = false;
updateMessage.value = typeof payload.detail === "string" ? payload.detail : "更新没有完成,请稍后再试";
return;
}
} catch {
updateBusy.value = false;
updateMessage.value = "更新没有完成,请稍后再试";
return;
}
updateTimer = window.setInterval(async () => {
try {
const response = await fetch("/api/update/status");
const payload = await response.json();
updateMessage.value = String(payload.message || "正在下载更新");
if (payload.state === "failed") {
window.clearInterval(updateTimer);
updateBusy.value = false;
return;
}
if (payload.state === "restarting") {
window.clearInterval(updateTimer);
allowClose = true;
if (inTauri()) await getCurrentWindow().destroy();
}
} catch {
window.clearInterval(updateTimer);
updateBusy.value = false;
updateMessage.value = "更新没有完成,请稍后再试";
}
}, 500);
}
onMounted(async () => {
document.title = "VideosDownTools";
void watchClose();
void checkForUpdate();
await loadDeviceDefaults();
loadSettings();
try {
@@ -1345,6 +1485,7 @@ onMounted(async () => {
const payload = await response.json();
token.value = payload.token;
profile.value = payload.profile;
takeSign(payload);
rememberSessionDevice(payload.device);
page.value = "download";
startLive();
@@ -1412,6 +1553,7 @@ onUnmounted(stopLive);
<div class="bar-title">
<n-button v-if="page === 'play'" quaternary size="small" @click="closePlay">返回</n-button>
<n-text strong class="bar-title-text">{{ pageTitle }}</n-text>
<n-text v-if="signNotice" class="sign-note">{{ signNotice }}</n-text>
</div>
<div v-if="page === 'download'" class="bar-search">
<n-input
@@ -1495,8 +1637,11 @@ onUnmounted(stopLive);
<span v-if="platform === 'dramabox'" class="profile-title-actions">
<n-tag size="small" :bordered="false" :type="dramaboxLoggedIn ? 'success' : 'default'">{{ dramaboxLoggedIn ? "已登录" : "访客" }}</n-tag>
<n-button size="tiny" secondary :loading="accountBusy" :disabled="!dramaboxDeviceReady" @click="loginDramaboxAdb">从设备登录</n-button>
<n-button size="tiny" secondary :loading="accountBusy" :disabled="!dramaboxLoggedIn" @click="exportDramaboxCredential">导出凭据</n-button>
<n-button size="tiny" secondary :loading="accountBusy" @click="pickDramaboxCredential">导入凭据</n-button>
</span>
</div>
<n-alert v-if="credentialNote" class="hint" type="success" :show-icon="false">{{ credentialNote }}</n-alert>
<n-alert v-if="profileError" class="hint" type="error" :show-icon="false">{{ profileError }}</n-alert>
<div v-for="item in accountFields" :key="item.key" class="profile-row">
<span class="profile-row-label">{{ item.label }}</span>
@@ -1604,9 +1749,11 @@ onUnmounted(stopLive);
<n-button :loading="devicesBusy" @click="probeMumu">探测 MuMu</n-button>
</div>
</n-form-item>
<n-alert v-if="credentialNote && platform === 'dramabox'" class="hint" type="success" :show-icon="false">{{ credentialNote }}</n-alert>
<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 v-if="platform === 'dramabox'" attr-type="button" secondary :loading="busy" @click="pickDramaboxCredential">导入凭据</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>
@@ -1615,6 +1762,7 @@ onUnmounted(stopLive);
</div>
</n-layout-content>
</n-layout>
<input ref="credentialFile" class="credential-file" type="file" accept="application/json,.json" @change="onDramaboxCredential" />
<n-tooltip v-if="!profile" placement="left">
<template #trigger>
<n-button class="settings-button" secondary circle aria-label="设置" @click="openSettings">
@@ -1644,6 +1792,20 @@ onUnmounted(stopLive);
</div>
</template>
</n-modal>
<n-modal v-model:show="updateOpen" preset="card" title="发现新版本" style="width: 440px" :mask-closable="!updateBusy" :closable="!updateBusy">
<p class="update-copy">新版本 {{ updateInfo.latest }},当前是 {{ updateInfo.current }}。</p>
<p v-if="updateInfo.notes" class="update-notes">{{ updateInfo.notes }}</p>
<p v-if="updateInfo.can_apply" class="update-copy">选择更新后会自动下载并重新打开。已下载的视频和登录状态会保留,正在进行的下载会中断。</p>
<p v-else class="update-copy">当前这份程序不能自动更新。</p>
<p v-if="updateMessage" class="update-copy">{{ updateMessage }}</p>
<template #footer>
<div class="modal-actions">
<span class="modal-spacer"></span>
<n-button :disabled="updateBusy" @click="updateOpen = false">稍后</n-button>
<n-button v-if="updateInfo.can_apply" type="primary" :loading="updateBusy" @click="confirmUpdate">立即更新</n-button>
</div>
</template>
</n-modal>
<n-modal
v-model:show="closeAsk"
preset="dialog"
@@ -1864,6 +2026,7 @@ html { color-scheme: dark; }
}
.bar-title { display: flex; align-items: center; gap: 8px; min-width: 0; }
.bar-title-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sign-note { flex: none; color: #63e2b7; font-size: 13px; white-space: nowrap; }
.bar-search {
position: absolute;
left: 50%;
@@ -1904,10 +2067,13 @@ html { color-scheme: dark; }
.card { width: 100%; max-width: 560px; }
.login-actions { display: flex; justify-content: center; gap: 8px; margin-top: 16px; }
.login-actions .n-button { min-width: 180px; }
.credential-file { display: none; }
.settings-button { position: fixed; right: 20px; bottom: 20px; z-index: 5; }
.gear-icon { width: 18px; height: 18px; display: block; }
.settings-modal-body { max-height: min(58vh, 520px); overflow: auto; padding-right: 4px; }
.modal-actions { display: flex; align-items: center; gap: 8px; }
.update-copy { margin: 0 0 8px; line-height: 1.5; }
.update-notes { margin: 0 0 8px; white-space: pre-wrap; line-height: 1.5; color: rgba(255, 255, 255, 0.72); }
.modal-spacer { flex: 1; }
.card .n-tabs { margin-bottom: 16px; }
.card .n-form-item { margin-bottom: 16px; }
+20 -5
View File
@@ -7,9 +7,11 @@ interface Episode {
title: string;
playable: boolean;
points?: number;
type?: string;
media?: string;
locked_reason?: string;
is_preview?: boolean;
lines?: number;
}
const props = defineProps<{
@@ -68,10 +70,10 @@ function select(episode: Episode) {
if (!episode.playable || episode.cid === current.value) return;
current.value = episode.cid;
error.value = "";
void nextTick(() => attach(episode.cid));
void nextTick(() => attach(episode.cid, 0));
}
function attach(cid: number) {
function attach(cid: number, line = 0) {
const video = videoRef.value;
if (!video) return;
stop();
@@ -81,17 +83,28 @@ function attach(cid: number) {
video.play().catch(() => undefined);
return;
}
const url = `${apiBase.value}/play/${props.dramaId}/${cid}/index.m3u8`;
const url = `${apiBase.value}/play/${props.dramaId}/${cid}/index.m3u8?line=${line}`;
if (Hls.isSupported()) {
const player = new Hls();
hls = player;
let advancing = false;
player.loadSource(url);
player.attachMedia(video);
player.on(Hls.Events.MANIFEST_PARSED, () => {
if (error.value === "正在切换线路") error.value = "";
video.play().catch(() => undefined);
});
player.on(Hls.Events.ERROR, (_event, data) => {
if (data.fatal) error.value = "这一集播放失败";
if (!data.fatal || advancing) return;
const status = data.response?.code;
const known = episode?.lines || 0;
if (status === 404 || line >= 5 || (known > 0 && line + 1 >= known)) {
error.value = "这一集播放失败";
return;
}
advancing = true;
error.value = "正在切换线路";
window.setTimeout(() => attach(cid, line + 1), 0);
});
return;
}
@@ -134,8 +147,10 @@ onUnmounted(stop);
@click="select(episode)"
>
<span class="play-episode-title">{{ episode.title }}</span>
<span v-if="!episode.playable" class="play-episode-lock">{{ episodeNote(episode) }}</span>
<span v-if="episode.type?.toLowerCase() === 'vip'" class="play-episode-lock">会员</span>
<span v-else-if="!episode.playable" class="play-episode-lock">{{ episodeNote(episode) }}</span>
<span v-else-if="episode.is_preview" class="play-episode-lock">试看</span>
<span v-if="episode.type?.toLowerCase() === 'vip' && !episode.playable && episode.locked_reason" class="play-episode-lock">{{ episodeNote(episode) }}</span>
</button>
<div v-if="!loading && episodes.length === 0" class="play-empty">没有分集</div>
</div>