3 Commits
10 changed files with 461 additions and 28 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "videosdowntools",
"private": true,
"version": "0.1.1",
"version": "0.1.3",
"scripts": {
"tauri": "tauri"
},
+109
View File
@@ -0,0 +1,109 @@
"""把当前版本的 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 = _post_asset(http, release_id, path.name, data)
if uploaded.status_code != 413:
if uploaded.status_code >= 300:
raise SystemExit(f"上传压缩包失败 {uploaded.status_code}")
return
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}"
uploaded = _post_asset(http, release_id, name, part)
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()
+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)
+159
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
@@ -59,6 +62,162 @@ def import_adb(serial: str, language: str = "") -> dict:
return {"token": client.token, "profile": client.profile}
_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:
record = _credential_record(payload)
try:
locale = resolve(language or record.get("language") or client.language or DEFAULT_LANGUAGE)
except RuntimeError:
locale = resolve(DEFAULT_LANGUAGE)
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"]
nickname = str(record.get("name") or record.get("user_id") or "DramaBox")
client.profile = {
"id": record.get("user_id") or "",
"username": nickname,
"nickname": nickname,
"email": "",
"phone": "",
"badge": "VIP" if record.get("vip") else "",
"vipday": 1 if record.get("vip") else 0,
"score": 0,
"watched": 0,
"rewards": 0,
"login_day": 0,
"country": locale.get("country") or "",
"language": locale.get("language") or "",
"native": locale.get("native") or "",
"locale": locale.get("id") or "",
"loginType": "app",
"has_login": "1",
"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:
if not client.token or not client.profile:
raise RuntimeError("还没有登录")
+38 -24
View File
@@ -23,7 +23,7 @@ _state = {
"message": "",
"latest": "",
"notes": "",
"url": "",
"urls": [],
}
_worker: threading.Thread | None = None
@@ -80,21 +80,32 @@ def public_notes(value: str) -> str:
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
url = ""
assets = payload.get("assets") if isinstance(payload.get("assets"), list) else []
for item in assets:
if isinstance(item, dict) and item.get("name") == ASSET_NAME:
url = str(item.get("browser_download_url") or "").strip()
break
if not url:
urls = release_urls(payload)
if not urls:
return None
return {"latest": latest, "notes": public_notes(str(payload.get("body") or "")), "url": url}
return {"latest": latest, "notes": public_notes(str(payload.get("body") or "")), "urls": urls}
def check() -> dict:
@@ -112,9 +123,9 @@ def check() -> dict:
if found:
_state["latest"] = found["latest"]
_state["notes"] = found["notes"]
_state["url"] = found["url"]
_state["urls"] = list(found["urls"])
else:
_state["url"] = ""
_state["urls"] = []
return {
"available": bool(found),
"current": current,
@@ -138,7 +149,7 @@ def start() -> dict:
if not is_packaged():
raise RuntimeError("请使用发布的程序更新")
with _lock:
if not _state["url"]:
if not _state["urls"]:
raise RuntimeError("没有可安装的更新")
if _worker is not None and _worker.is_alive():
return status()
@@ -157,11 +168,13 @@ def _set(**values) -> None:
def _install() -> None:
with _lock:
url = _state["url"]
urls = list(_state["urls"])
temp_root = Path(tempfile.mkdtemp(prefix="VideosDownTools-update-"))
archive = temp_root / ASSET_NAME
try:
_download(url, archive)
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:
@@ -171,20 +184,21 @@ def _install() -> None:
_set(state="restarting", percent=100, message="正在重新打开")
def _download(url: str, dest: Path) -> None:
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)
with dest.open("wb") as handle:
for chunk in response.iter_bytes(256 * 1024):
if not chunk:
continue
handle.write(chunk)
done += len(chunk)
if total:
_set(percent=min(99, done * 100 // total), message="正在下载更新")
if dest.stat().st_size <= 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("更新包是空的")
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "VideosDownTools",
"version": "0.1.1",
"version": "0.1.3",
"identifier": "com.videosdowntools.desktop",
"build": {
"beforeDevCommand": {
+40
View File
@@ -0,0 +1,40 @@
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("不完整的凭据文件应被拒绝")
if __name__ == "__main__":
test_credential_file_is_one_json_document()
print("ok")
+14 -1
View File
@@ -24,7 +24,20 @@ def test_release_needs_the_package_asset() -> None:
assert found is not None
assert found["latest"] == "0.1.1"
assert "http" not in found["notes"]
assert found["url"].endswith(".zip")
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
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "videosdowntools-ui",
"private": true,
"version": "0.1.1",
"version": "0.1.3",
"type": "module",
"scripts": {
"dev": "vite",
+76
View File
@@ -153,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);
@@ -1094,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;
@@ -1568,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>
@@ -1677,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>
@@ -1688,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">
@@ -1992,6 +2067,7 @@ 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; }