3 Commits
9 changed files with 185 additions and 60 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "videosdowntools",
"private": true,
"version": "0.1.2",
"version": "0.1.4",
"scripts": {
"tauri": "tauri"
},
+13 -6
View File
@@ -15,7 +15,7 @@ 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 登录凭据可以导出成一个 JSON 文件,在另一台电脑导入后继续使用。"
NOTES = "导入 DramaBox 凭据后会先读取个人信息,确认登录成功后才进入。"
PART_SIZE = 40 * 1024 * 1024
@@ -81,16 +81,23 @@ def main() -> None:
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}")
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}"
uploaded = _post_asset(http, release_id, name, part)
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}")
+5
View File
@@ -104,6 +104,11 @@ class CredentialBody(BaseModel):
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))
+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
+103 -43
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,43 +23,7 @@ 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)
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}
return _install_app_login(read_app_login(serial), language)
_CREDENTIAL_KIND = "dramabox-login"
@@ -107,20 +74,117 @@ def export_credential() -> dict:
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)
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,
@@ -141,10 +205,6 @@ def import_credential(payload: dict, 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:
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "VideosDownTools",
"version": "0.1.2",
"version": "0.1.4",
"identifier": "com.videosdowntools.desktop",
"build": {
"beforeDevCommand": {
+22
View File
@@ -1,3 +1,4 @@
from server.services.dramabox.app_api import account_from_bootstrap
from server.services.dramabox.login import _credential_record
@@ -35,6 +36,27 @@ def test_credential_file_is_one_json_document() -> None:
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")
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "videosdowntools-ui",
"private": true,
"version": "0.1.2",
"version": "0.1.4",
"type": "module",
"scripts": {
"dev": "vite",
+7 -8
View File
@@ -153,6 +153,7 @@ 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);
@@ -1098,21 +1099,17 @@ 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")
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 blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "dramabox-login.json";
link.click();
URL.revokeObjectURL(url);
const path = typeof payload.path === "string" ? payload.path : "";
credentialNote.value = path ? `已保存到 ${path}` : "已取消";
})
.catch((exc) => {
target.value = exc instanceof Error ? exc.message : "导出失败";
@@ -1644,6 +1641,7 @@ onUnmounted(stopLive);
<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>
@@ -1751,6 +1749,7 @@ 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>