fix: 更新包过大时分段上传并自动拼回

This commit is contained in:
Nixevol
2026-10-29 07:40:41 +08:00
parent 623c7c28e9
commit 7ffbf48efd
3 changed files with 161 additions and 25 deletions
+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 = "打开程序时会检查新版本,确认后自动下载并重新打开。\n应用内播放会带上单独的音轨。\n黄豆账号登录后会自动签到。"
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()
+32 -18
View File
@@ -23,7 +23,7 @@ _state = {
"message": "", "message": "",
"latest": "", "latest": "",
"notes": "", "notes": "",
"url": "", "urls": [],
} }
_worker: threading.Thread | None = None _worker: threading.Thread | None = None
@@ -80,21 +80,32 @@ def public_notes(value: str) -> str:
return text.strip() 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: def describe_release(payload: dict, current: str) -> dict | None:
if not isinstance(payload, dict) or payload.get("draft") or payload.get("prerelease"): if not isinstance(payload, dict) or payload.get("draft") or payload.get("prerelease"):
return None return None
latest = normalize_version(str(payload.get("tag_name") or payload.get("name") or "")) latest = normalize_version(str(payload.get("tag_name") or payload.get("name") or ""))
if not is_newer(latest, current): if not is_newer(latest, current):
return None return None
url = "" urls = release_urls(payload)
assets = payload.get("assets") if isinstance(payload.get("assets"), list) else [] if not urls:
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 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: def check() -> dict:
@@ -112,9 +123,9 @@ def check() -> dict:
if found: if found:
_state["latest"] = found["latest"] _state["latest"] = found["latest"]
_state["notes"] = found["notes"] _state["notes"] = found["notes"]
_state["url"] = found["url"] _state["urls"] = list(found["urls"])
else: else:
_state["url"] = "" _state["urls"] = []
return { return {
"available": bool(found), "available": bool(found),
"current": current, "current": current,
@@ -138,7 +149,7 @@ def start() -> dict:
if not is_packaged(): if not is_packaged():
raise RuntimeError("请使用发布的程序更新") raise RuntimeError("请使用发布的程序更新")
with _lock: with _lock:
if not _state["url"]: if not _state["urls"]:
raise RuntimeError("没有可安装的更新") raise RuntimeError("没有可安装的更新")
if _worker is not None and _worker.is_alive(): if _worker is not None and _worker.is_alive():
return status() return status()
@@ -157,11 +168,13 @@ def _set(**values) -> None:
def _install() -> None: def _install() -> None:
with _lock: with _lock:
url = _state["url"] urls = list(_state["urls"])
temp_root = Path(tempfile.mkdtemp(prefix="VideosDownTools-update-")) temp_root = Path(tempfile.mkdtemp(prefix="VideosDownTools-update-"))
archive = temp_root / ASSET_NAME archive = temp_root / ASSET_NAME
try: 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") source = _extract(archive, temp_root / "package")
_launch_updater(source) _launch_updater(source)
except Exception: except Exception:
@@ -171,20 +184,21 @@ def _install() -> None:
_set(state="restarting", percent=100, message="正在重新打开") _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 done = 0
with httpx.stream("GET", url, timeout=600.0, follow_redirects=True, trust_env=True) as response: with httpx.stream("GET", url, timeout=600.0, follow_redirects=True, trust_env=True) as response:
response.raise_for_status() response.raise_for_status()
total = int(response.headers.get("content-length") or 0) total = int(response.headers.get("content-length") or 0)
with dest.open("wb") as handle:
for chunk in response.iter_bytes(256 * 1024): for chunk in response.iter_bytes(256 * 1024):
if not chunk: if not chunk:
continue continue
handle.write(chunk) handle.write(chunk)
done += len(chunk) done += len(chunk)
if total: if total:
_set(percent=min(99, done * 100 // total), message="正在下载更新") part = min(99, done * 100 // total)
if dest.stat().st_size <= 0: overall = int(((index - 1) + part / 100) / count * 99)
_set(percent=overall, message="正在下载更新")
if done <= 0:
raise RuntimeError("更新包是空的") raise RuntimeError("更新包是空的")
+14 -1
View File
@@ -24,7 +24,20 @@ def test_release_needs_the_package_asset() -> None:
assert found is not None assert found is not None
assert found["latest"] == "0.1.1" assert found["latest"] == "0.1.1"
assert "http" not in found["notes"] 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 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