feat: 打开时提示新版本并自动更新
This commit is contained in:
@@ -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
|
||||
"""
|
||||
Reference in New Issue
Block a user