feat: 打开时提示新版本并自动更新
This commit is contained in:
@@ -7,6 +7,7 @@ Windows 桌面程序,用来登录 RaptDrama、黄豆短剧和 DramaBox,浏
|
||||
1. 解压 `dist/VideosDownTools-windows-x64.zip`。
|
||||
2. 进入 `VideosDownTools`,运行 `VideosDownTools.exe`。
|
||||
3. 压缩包里已经带有 Python、adb、ffmpeg 和大约 2 MB 的 WebView2 在线安装器。本机如果还没有 WebView2,程序启动时会用它联网静默安装。
|
||||
4. 打开程序时如果有新版本,会提示是否更新。选择更新后会自动下载并重新打开,已下载的视频和登录状态会保留。
|
||||
|
||||
程序会在自己的目录里写入:
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "videosdowntools",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"scripts": {
|
||||
"tauri": "tauri"
|
||||
},
|
||||
|
||||
@@ -216,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"
|
||||
@@ -251,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"
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,262 @@
|
||||
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": "",
|
||||
"url": "",
|
||||
}
|
||||
_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 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:
|
||||
return None
|
||||
return {"latest": latest, "notes": public_notes(str(payload.get("body") or "")), "url": url}
|
||||
|
||||
|
||||
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["url"] = found["url"]
|
||||
else:
|
||||
_state["url"] = ""
|
||||
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["url"]:
|
||||
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:
|
||||
url = _state["url"]
|
||||
temp_root = Path(tempfile.mkdtemp(prefix="VideosDownTools-update-"))
|
||||
archive = temp_root / ASSET_NAME
|
||||
try:
|
||||
_download(url, archive)
|
||||
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, dest: Path) -> 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:
|
||||
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
|
||||
"""
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "VideosDownTools",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"identifier": "com.videosdowntools.desktop",
|
||||
"build": {
|
||||
"beforeDevCommand": {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
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["url"].endswith(".zip")
|
||||
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
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "videosdowntools-ui",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -1262,6 +1262,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;
|
||||
@@ -1304,9 +1309,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 {
|
||||
@@ -1653,6 +1717,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"
|
||||
@@ -1918,6 +1996,8 @@ html { color-scheme: dark; }
|
||||
.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; }
|
||||
|
||||
Reference in New Issue
Block a user