liufumingren 21e8c6a5ec 更新改为软件内下载(进度条)+ 下载完成自动安装;修复 version.json 与包版本不一致导致的无限提示
一、需求:更新不要跳浏览器
- 新增 UpdateWindow(弹窗):显示新版本 / 当前版本 / 包大小 / 更新说明;
- 点「立即更新」→ 软件内流式下载(ProgressBar + 百分比 + 已下载/总大小)→ MD5 校验
  → 启动安装(等 3 秒让本进程退出,再 msiexec /passive)→ 装完自动重新打开;
- 下载目录 %TEMP%\YuncangTraceUpdate\,文件名取 downloadUrl 里的真实文件名
  (原来用 version.json 的 version 命名,配错时会误导)。

二、修复「更新不了一直提示 1.0.2」
- 原因:测试数据里 version.json 写 1.0.3,但 downloadUrl 指向 1.0.2 的包;
  装完仍是 1.0.2 → 下次启动又提示,永远循环。
- 修复(防御):解析 downloadUrl 里的包版本(YuncangTraceSetup-x.y.z.msi),
  若包版本 <= 当前版本则直接忽略更新 —— 以后 version.json 配错/漏传包也不会无限弹窗。
- 同时把环境打成一致:真实打包 1.0.3(version.json 与包都是 1.0.3)并安装。

三、build.ps1
- 自动设置 DOTNET_ROOT(wix 是 dotnet 全局工具,apphost 不认 PATH,只认 DOTNET_ROOT):
  之前在无该环境变量的终端里打包会报「You must install .NET to run this application」。

四、验证
- 安装 1.0.3 + version.json 1.0.3 → 启动无更新窗口、日志无「发现新版本」✅
- 伪造 version.json=1.0.4 但包仍是 1.0.3 → 启动**不弹窗**(防御生效)✅
- 恢复 version.json 为 1.0.3。
- 更新窗口 UI 已通过截图确认(新版本/当前版本/包大小/说明/稍后/立即更新)。
- 新增 YUNCANG_AUTO_UPDATE=1 测试开关:弹窗后自动开始下载,便于无 UI 自动化环境回归。

五、README
- 「自动更新怎么工作」改为软件内下载+自动安装,补充下载位置、安装时机、版本一致性防护与测试开关。
2026-10-17 12:27:05 +08:00

249 lines
9.2 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#requires -Version 5.1
<#
.SYNOPSIS
打「云仓视频溯源软件」的 MSI 安装包,并生成本机自动更新用的 version.json。
.DESCRIPTION
1. 按 -Environment 从 package.config.json 取该环境的域名(开发 / 生产);
2. dotnet publish(自包含单文件,不依赖 .NET 运行时);
3. wix build 生成 MSI;
4. 计算 MD5 → 写 version.json(version / downloadUrl / md5 / size / publishedAt / buildId);
5. 把 version.json + MSI 复制到后端静态目录(默认 backend/app/public/download/),
供软件启动时 GET /download/version.json 检测更新;
6. 本地 out/ 与后端目录各只保留最近 keepVersions(默认 5)个安装包。
.PARAMETER Environment
Development(默认,连本机 7300)/ Production(用正式域名)。
.PARAMETER Version
覆盖版本号(默认取 csproj 的 <Version>)。例:-Version 1.0.1
.PARAMETER ServerBaseUrl
覆盖该环境配置里的域名(临时打测试包用)。
.PARAMETER Keep
保留多少个历史安装包(默认读 package.config.json 的 keepVersions = 5)。
.PARAMETER ReleaseNotes
写进 version.json 的更新说明(软件弹更新提示时展示)。
.EXAMPLE
.\build.ps1 -Environment Production -Version 1.0.1 -ReleaseNotes "修复若干问题"
.EXAMPLE
.\build.ps1 # 开发环境、版本取 csproj
.NOTES
前置:dotnet tool install --global wix --version 5.0.2
(WiX v6+ 需要 OSMF 付费协议,v5 不需要)
本文件必须保存为 UTF-8 with BOM —— PowerShell 5.1 读无 BOM 脚本会按 GBK 解析,中文注释直接语法报错。
#>
param(
[ValidateSet('Development', 'Production')]
[string]$Environment = 'Development',
[string]$Version,
[string]$ServerBaseUrl,
[int]$Keep = 0,
[string]$ReleaseNotes = ''
)
$ErrorActionPreference = 'Stop'
# dotnet 可能装在用户目录(免管理员安装):wix 是 dotnet 全局工具(apphost),
# **只认 DOTNET_ROOT / 默认安装路径,不认 PATH** —— 不设置会报「You must install .NET」。
$dotnetRoot = Join-Path $env:LOCALAPPDATA 'Microsoft\dotnet'
if (Test-Path (Join-Path $dotnetRoot 'dotnet.exe')) {
$env:DOTNET_ROOT = $dotnetRoot
if (($env:Path -split ';') -notcontains $dotnetRoot) {
$env:Path = "$dotnetRoot;$env:Path"
}
Write-Host "DOTNET_ROOT=$dotnetRoot"
}
if (-not (Get-Command dotnet -ErrorAction SilentlyContinue)) {
throw "找不到 dotnet。请先安装 .NET 8 SDK,或设置 DOTNET_ROOT。"
}
$desktop = Split-Path -Parent $PSScriptRoot # desktop\
$project = Join-Path $desktop 'YuncangTrace.LocalService.csproj'
$publishDir = Join-Path $desktop 'publish'
$outDir = Join-Path $PSScriptRoot 'out'
function Read-Utf8([string]$p) {
return [System.IO.File]::ReadAllText($p, (New-Object System.Text.UTF8Encoding($false)))
}
function Write-Utf8NoBom([string]$p, [string]$text) {
[System.IO.File]::WriteAllText($p, $text, (New-Object System.Text.UTF8Encoding($false)))
}
# ---------------- 1. 配置 ----------------
$configPath = Join-Path $PSScriptRoot 'package.config.json'
$cfg = Read-Utf8 $configPath | ConvertFrom-Json
$envProp = $cfg.environments.PSObject.Properties[$Environment]
if (-not $envProp) { throw "package.config.json 里没有环境:$Environment" }
$envCfg = $envProp.Value
if (-not $ServerBaseUrl) { $ServerBaseUrl = $envCfg.serverBaseUrl }
if (-not $ServerBaseUrl) { throw "环境 $Environment 没配 serverBaseUrl" }
$ServerBaseUrl = $ServerBaseUrl.TrimEnd('/')
if ($Keep -le 0) { $Keep = [int]$cfg.keepVersions }
if ($Keep -le 0) { $Keep = 5 }
# ---------------- 2. 版本 ----------------
$projXml = [xml](Read-Utf8 $project)
$projVersion = ($projXml.Project.PropertyGroup.Version | Where-Object { $_ } | Select-Object -First 1)
if (-not $Version) { $Version = $projVersion }
if (-not $Version) { throw "csproj 里没找到 <Version>,也没传 -Version" }
$Version = $Version.Trim().TrimStart('v', 'V')
$null = [version]$Version # 提前校验格式(不合法直接报错)
Write-Host "环境:$Environment"
Write-Host "版本:$Version"
Write-Host "后端:$ServerBaseUrl"
# ---------------- 3. 发布 ----------------
Push-Location $desktop
try {
dotnet publish $project -c Release -r win-x64 `
--self-contained true `
-p:PublishSingleFile=true `
-p:IncludeNativeLibrariesForSelfExtract=true `
-p:Version=$Version `
-p:ServerBaseUrl=$ServerBaseUrl `
-o $publishDir
if ($LASTEXITCODE -ne 0) { throw "dotnet publish 失败($LASTEXITCODE)" }
}
finally {
Pop-Location
}
$exe = Join-Path $publishDir 'YuncangTrace.LocalService.exe'
if (-not (Test-Path $exe)) { throw "发布产物不存在:$exe" }
# ---------------- 4. 打 MSI ----------------
$wix = (Get-Command wix.exe -ErrorAction SilentlyContinue).Source
if (-not $wix) { $wix = Join-Path $env:USERPROFILE '.dotnet\tools\wix.exe' }
if (-not (Test-Path $wix)) {
throw "找不到 wix.exe。先执行:dotnet tool install --global wix --version 5.0.2"
}
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
$msiName = "YuncangTraceSetup-$Version.msi"
$msi = Join-Path $outDir $msiName
Push-Location $PSScriptRoot
try {
& $wix build Product.wxs -arch x64 -d "Version=$Version" -o $msi
if ($LASTEXITCODE -ne 0) { throw "wix build 失败($LASTEXITCODE)" }
}
finally {
Pop-Location
}
# ---------------- 5. version.json ----------------
$hash = (Get-FileHash -Algorithm MD5 -Path $msi).Hash.ToLowerInvariant()
$size = (Get-Item $msi).Length
$downloadUrl = "$ServerBaseUrl/download/$msiName"
$now = Get-Date
$versionJson = [ordered]@{
version = $Version
downloadUrl = $downloadUrl
md5 = $hash
size = $size
publishedAt = $now.ToString('yyyy-MM-ddTHH:mm:sszzz')
buildId = $now.ToString('yyyyMMddHHmmss')
environment = $Environment
releaseNotes = $ReleaseNotes
} | ConvertTo-Json
$versionFile = Join-Path $outDir 'version.json'
Write-Utf8NoBom $versionFile $versionJson
Write-Host "MD5:$hash($([math]::Round($size / 1MB, 1)) MB)"
# ---------------- 6. 复制到后端 ----------------
# MSI → 静态目录(/download/xxx.msi,长缓存)
# version.json → 非静态目录(/download/version.json 由路由提供,绝不能缓存)
$skipVersionJson = $false
$downloadDir = $null
$versionDir = $null
$existingVj = $null
if ($envCfg.copyToServer -ne $false) {
$downloadDir = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $envCfg.downloadFolder))
$versionDir = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $envCfg.versionFolder))
New-Item -ItemType Directory -Force -Path $downloadDir | Out-Null
New-Item -ItemType Directory -Force -Path $versionDir | Out-Null
# 后端已经有更新版本:说明这次是在补打旧版本,不能把 version.json 降回去
$existingVj = Join-Path $versionDir 'version.json'
if (Test-Path $existingVj) {
try {
$old = (Read-Utf8 $existingVj) | ConvertFrom-Json
if ($old.version -and ([version]$old.version -gt [version]$Version)) {
$skipVersionJson = $true
Write-Warning "后端 version.json 已是更新版本($($old.version)),本次不覆盖它"
}
}
catch { /* 旧文件坏了就当没有 */ }
}
$dstMsi = Join-Path $downloadDir $msiName
Copy-Item -Path $msi -Destination $dstMsi -Force
# 刷新 mtime:即使上游还有一层协商缓存,也能认出文件变了
(Get-Item $dstMsi).LastWriteTime = $now
if (-not $skipVersionJson) {
Write-Utf8NoBom $existingVj $versionJson
(Get-Item $existingVj).LastWriteTime = $now
}
# 旧版本打包时把 version.json 放在静态目录里,顺手清掉(避免两份不一致)
$staleVj = Join-Path $downloadDir 'version.json'
if (Test-Path $staleVj) { Remove-Item $staleVj -Force }
Write-Host "已复制到:$downloadDir(MSI)、$versionDir(version.json)"
}
else {
Write-Host "(该环境 copyToServer=false,跳过复制到后端)"
}
# ---------------- 7. 只保留最近 N 个安装包 ----------------
function Remove-OldPackages([string]$dir, [int]$keep) {
if (-not (Test-Path $dir)) { return }
$items = @(
Get-ChildItem -Path $dir -Filter 'YuncangTraceSetup-*.msi' -File | ForEach-Object {
if ($_.BaseName -match 'YuncangTraceSetup-(\d+(\.\d+){1,3})$') {
[pscustomobject]@{ File = $_; Ver = [version]$Matches[1] }
}
} | Sort-Object Ver -Descending
)
$removed = 0
$items | Select-Object -Skip $keep | ForEach-Object {
Remove-Item $_.File.FullName -Force
$removed++
Write-Host " 清理旧包:$($_.File.Name)"
}
if ($removed -eq 0) { Write-Host " $dir:共 $($items.Count) 个,未超过 $keep 个" }
}
Write-Host "保留最近 $Keep 个安装包:"
Remove-OldPackages $outDir $Keep
if ($downloadDir) { Remove-OldPackages $downloadDir $Keep }
# ---------------- 8. 摘要 ----------------
Write-Host ""
Write-Host "完成:$msi" -ForegroundColor Green
Write-Host "版本文件:$versionFile"
Write-Host "下载地址:$downloadUrl"
Write-Host "安装:msiexec /i `"$msi`""
Write-Host "卸载:msiexec /x `"$msi`""