更新改为软件内下载(进度条)+ 下载完成自动安装;修复 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 - 「自动更新怎么工作」改为软件内下载+自动安装,补充下载位置、安装时机、版本一致性防护与测试开关。
This commit is contained in:
parent
81a5a8888d
commit
21e8c6a5ec
@ -104,26 +104,20 @@ public partial class App : Application
|
||||
|
||||
AppLog.Write($"发现新版本 {info.Version}(当前 {current}):{info.DownloadUrl}");
|
||||
|
||||
var notes = string.IsNullOrWhiteSpace(info.Notes) ? string.Empty : $"\n\n更新内容:{info.Notes}";
|
||||
var size = info.Size > 0 ? $"\n安装包大小:{info.Size / 1024.0 / 1024.0:0.0} MB" : string.Empty;
|
||||
|
||||
var answer = MessageBox.Show(
|
||||
$"发现新版本 {info.Version}(当前 {current})。{notes}{size}\n\n现在下载安装包吗?",
|
||||
"软件更新",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Information);
|
||||
|
||||
if (answer != MessageBoxResult.Yes) return;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(info.DownloadUrl))
|
||||
// 软件内弹窗 + 进度条下载 + 自动安装(不跳浏览器)
|
||||
AppLog.Write("准备显示更新窗口…");
|
||||
var update = new UpdateWindow(info, current)
|
||||
{
|
||||
AppLog.Write("更新信息里没有下载地址(version.json 的 downloadUrl)");
|
||||
return;
|
||||
// 回归测试用:YUNCANG_AUTO_UPDATE=1 时不点按钮直接开始下载
|
||||
AutoStart = Environment.GetEnvironmentVariable("YUNCANG_AUTO_UPDATE") == "1",
|
||||
};
|
||||
var result = update.ShowDialog();
|
||||
AppLog.Write($"更新窗口返回:{result}");
|
||||
if (result == true)
|
||||
{
|
||||
AppLog.Write("更新已开始安装,退出本程序以释放 exe");
|
||||
ExitApplication();
|
||||
}
|
||||
|
||||
// 用默认浏览器打开下载(MSI 能直接下,也能交给用户自己跑)
|
||||
Process.Start(new ProcessStartInfo(info.DownloadUrl) { UseShellExecute = true });
|
||||
AppLog.Write($"已打开下载:{info.DownloadUrl}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@ -150,10 +150,19 @@ cd desktop\installer
|
||||
|
||||
```
|
||||
软件启动(登录后)→ GET {后端}/download/version.json?t=时间戳
|
||||
→ version.json 里的 version 比当前程序集版本新
|
||||
→ 弹窗「发现新版本 x.y.z」→ 用户点是 → 浏览器打开 downloadUrl 下载安装
|
||||
→ version.json 的 version 比当前程序集版本新
|
||||
→ 软件内弹窗:新版本号 / 更新说明 / 安装包大小
|
||||
→ 点「立即更新」→ **软件内下载(进度条)**→ MD5 校验
|
||||
→ 自动静默安装(msiexec /passive)→ 软件退出 → 装完自动重新打开
|
||||
```
|
||||
|
||||
- **不跳浏览器**:下载、进度、校验、安装都在软件里完成。
|
||||
- 下载落在 `%TEMP%\YuncangTraceUpdate\`,文件名取 downloadUrl 里的真实文件名。
|
||||
- 安装前会等 3 秒(让本进程先退出,否则 exe 被占用换不掉);perUser 安装不需要管理员。
|
||||
- **版本一致性防护**:若 `downloadUrl` 里的包版本(`YuncangTraceSetup-x.y.z.msi`)不比当前版本新,
|
||||
直接忽略 —— 防止 version.json 配错/漏传包导致「装完还是旧版 → 无限弹窗」。
|
||||
- 回归测试可用环境变量 `YUNCANG_AUTO_UPDATE=1` 让弹窗出现后自动开始下载(无需手点)。
|
||||
|
||||
`version.json` 长这样(脚本生成,**不用手写**):
|
||||
|
||||
```json
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@ -35,6 +36,17 @@ public static class UpdateChecker
|
||||
public static string VersionUrl(string serverBaseUrl)
|
||||
=> serverBaseUrl.TrimEnd('/') + "/download/version.json";
|
||||
|
||||
/// <summary>
|
||||
/// 从下载地址里解析安装包版本:`.../YuncangTraceSetup-1.0.3.msi` → <c>1.0.3</c>;解析不到返回 null。
|
||||
/// </summary>
|
||||
public static Version? PackageVersionOf(string? downloadUrl)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(downloadUrl)) return null;
|
||||
|
||||
var match = Regex.Match(downloadUrl, @"YuncangTraceSetup-(\d+(?:\.\d+){1,3})\.msi", RegexOptions.IgnoreCase);
|
||||
return match.Success && Version.TryParse(match.Groups[1].Value, out var version) ? version : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查是否有更新。
|
||||
/// </summary>
|
||||
@ -66,9 +78,16 @@ public static class UpdateChecker
|
||||
if (!Version.TryParse(text.Trim(), out var remote)) return null;
|
||||
if (remote <= current) return null;
|
||||
|
||||
var downloadUrl = root.TryGetProperty("downloadUrl", out var d) ? d.GetString() : null;
|
||||
|
||||
// 防御:version.json 的 version 可能和下载包本身不一致(配错、或发版时漏传包)。
|
||||
// 若包里的版本并不比当前新,提示了也装不上去 → 会无限弹窗,直接忽略。
|
||||
var packageVersion = PackageVersionOf(downloadUrl);
|
||||
if (packageVersion is not null && packageVersion <= current) return null;
|
||||
|
||||
return new UpdateInfo(
|
||||
text.Trim(),
|
||||
root.TryGetProperty("downloadUrl", out var d) ? d.GetString() : null,
|
||||
downloadUrl,
|
||||
root.TryGetProperty("md5", out var m) ? m.GetString() : null,
|
||||
root.TryGetProperty("size", out var s) && s.TryGetInt64(out var size) ? size : 0,
|
||||
root.TryGetProperty("releaseNotes", out var n) ? n.GetString() : null);
|
||||
|
||||
55
desktop/UpdateWindow.xaml
Normal file
55
desktop/UpdateWindow.xaml
Normal file
@ -0,0 +1,55 @@
|
||||
<Window x:Class="YuncangTrace.LocalService.UpdateWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="软件更新"
|
||||
Height="340" Width="470"
|
||||
ResizeMode="NoResize"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Background="{StaticResource BgBrush}"
|
||||
FontFamily="Microsoft YaHei UI, Segoe UI"
|
||||
FontSize="13">
|
||||
<!--
|
||||
更新窗口:软件内下载(进度条)+ 校验 + 自动安装,不跳浏览器。
|
||||
样式沿用 App.xaml 里的资源(BgBrush / LineBrush / MutedBrush / BrandBrush)。
|
||||
-->
|
||||
<Border Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="10" Margin="22" Padding="20">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock x:Name="TitleText" FontSize="17" FontWeight="SemiBold" />
|
||||
<TextBlock x:Name="SubText" Grid.Row="1" Margin="0,6,0,12"
|
||||
FontSize="12" Foreground="{StaticResource MutedBrush}" />
|
||||
|
||||
<Border Grid.Row="2" Background="#F9FAFB" BorderBrush="{StaticResource LineBrush}"
|
||||
BorderThickness="1" CornerRadius="6" Padding="10" MaxHeight="96">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<TextBlock x:Name="NotesText" TextWrapping="Wrap" FontSize="12"
|
||||
Foreground="{StaticResource MutedBrush}" />
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
|
||||
<StackPanel Grid.Row="3" VerticalAlignment="Bottom" Margin="0,14,0,0">
|
||||
<ProgressBar x:Name="Progress" Height="8" Visibility="Collapsed"
|
||||
Minimum="0" Maximum="100" />
|
||||
<TextBlock x:Name="StatusText" Margin="0,8,0,0" FontSize="12"
|
||||
Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="4" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,14,0,0">
|
||||
<Button x:Name="LaterButton" Content="稍后提醒" Padding="14,7" Margin="0,0,8,0"
|
||||
Background="Transparent" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
Cursor="Hand" Click="Later_Click" />
|
||||
<Button x:Name="UpdateButton" Content="立即更新" Padding="16,7"
|
||||
Background="{StaticResource BrandBrush}" Foreground="White" BorderThickness="0"
|
||||
Cursor="Hand" Click="Update_Click" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
217
desktop/UpdateWindow.xaml.cs
Normal file
217
desktop/UpdateWindow.xaml.cs
Normal file
@ -0,0 +1,217 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
|
||||
namespace YuncangTrace.LocalService;
|
||||
|
||||
/// <summary>
|
||||
/// 更新窗口:软件内下载(进度条)→ 校验 MD5 → 自动静默安装并退出。
|
||||
///
|
||||
/// 为什么不在浏览器里打开下载链接:
|
||||
/// 用户还要自己找文件、自己双击、自己处理"文件被占用";
|
||||
/// 这里直接下到临时目录、校验、`msiexec /passive` 安装,装完自动把新版拉起来。
|
||||
/// </summary>
|
||||
public partial class UpdateWindow : Window
|
||||
{
|
||||
private readonly UpdateInfo _info;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>
|
||||
/// 打开后自动开始下载(无 UI 自动化时用):由环境变量 <c>YUNCANG_AUTO_UPDATE=1</c> 开启,
|
||||
/// 仅用于回归测试,正常使用不会走到。
|
||||
/// </summary>
|
||||
public bool AutoStart { get; set; }
|
||||
|
||||
public UpdateWindow(UpdateInfo info, Version current)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_info = info;
|
||||
TitleText.Text = $"发现新版本 {info.Version}";
|
||||
SubText.Text = $"当前版本 {current} · 安装包 {FormatSize(info.Size)}";
|
||||
NotesText.Text = string.IsNullOrWhiteSpace(info.Notes) ? "(本次更新没有提供说明)" : info.Notes;
|
||||
|
||||
Loaded += (_, _) =>
|
||||
{
|
||||
if (AutoStart) _ = StartUpdateAsync();
|
||||
};
|
||||
}
|
||||
|
||||
private void Later_Click(object sender, RoutedEventArgs e) => Close();
|
||||
|
||||
private void Update_Click(object sender, RoutedEventArgs e) => _ = StartUpdateAsync();
|
||||
|
||||
private async Task StartUpdateAsync()
|
||||
{
|
||||
if (_busy) return;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(_info.DownloadUrl))
|
||||
{
|
||||
StatusText.Text = "更新信息里没有下载地址,请联系管理员。";
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
UpdateButton.IsEnabled = false;
|
||||
LaterButton.IsEnabled = false;
|
||||
Progress.Visibility = Visibility.Visible;
|
||||
AppLog.Write($"开始下载更新包:{_info.DownloadUrl}");
|
||||
|
||||
try
|
||||
{
|
||||
StatusText.Text = "正在下载… 0%";
|
||||
|
||||
var progress = new Progress<(long received, long? total)>(p =>
|
||||
{
|
||||
if (p.total is > 0)
|
||||
{
|
||||
Progress.IsIndeterminate = false;
|
||||
var percent = Math.Min(100.0, p.received * 100.0 / p.total.Value);
|
||||
Progress.Value = percent;
|
||||
StatusText.Text = $"正在下载… {percent:0}%({FormatSize(p.received)} / {FormatSize(p.total.Value)})";
|
||||
}
|
||||
else
|
||||
{
|
||||
// 服务端没给 Content-Length:退化成不确定进度
|
||||
Progress.IsIndeterminate = true;
|
||||
StatusText.Text = $"正在下载… {FormatSize(p.received)}";
|
||||
}
|
||||
});
|
||||
|
||||
var file = await DownloadAsync(_info.DownloadUrl!, progress, CancellationToken.None);
|
||||
AppLog.Write($"更新包下载完成:{file}");
|
||||
|
||||
Progress.IsIndeterminate = false;
|
||||
Progress.Value = 100;
|
||||
StatusText.Text = "下载完成,正在校验安装包…";
|
||||
|
||||
var actual = await Task.Run(() => ComputeMd5(file));
|
||||
if (!string.IsNullOrWhiteSpace(_info.Md5)
|
||||
&& !actual.Equals(_info.Md5.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
TryDelete(file);
|
||||
AppLog.Write($"安装包校验失败:实际 {actual},期望 {_info.Md5}");
|
||||
StatusText.Text = "安装包校验失败(MD5 不一致),请稍后重试。";
|
||||
ResetButtons();
|
||||
return;
|
||||
}
|
||||
|
||||
AppLog.Write("安装包校验通过,开始安装");
|
||||
StatusText.Text = "正在安装,软件会短暂退出,安装完成后自动重新打开…";
|
||||
LaunchInstaller(file);
|
||||
|
||||
// 通知 App:可以退出了(退出后才能替换正在运行的 exe)
|
||||
DialogResult = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusText.Text = $"更新失败:{ex.Message}";
|
||||
ResetButtons();
|
||||
}
|
||||
}
|
||||
|
||||
private void ResetButtons()
|
||||
{
|
||||
_busy = false;
|
||||
UpdateButton.IsEnabled = true;
|
||||
LaterButton.IsEnabled = true;
|
||||
Progress.Visibility = Visibility.Collapsed;
|
||||
Progress.IsIndeterminate = false;
|
||||
Progress.Value = 0;
|
||||
}
|
||||
|
||||
/// <summary>下载到临时目录(流式,边下边报进度)</summary>
|
||||
private async Task<string> DownloadAsync(
|
||||
string url,
|
||||
IProgress<(long received, long? total)> progress,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var dir = Path.Combine(Path.GetTempPath(), "YuncangTraceUpdate");
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
// 文件名优先用下载地址里的真实文件名(避免 version.json 的 version 与包不一致时名字骗人)
|
||||
var fileName = Path.GetFileName(new Uri(url).LocalPath);
|
||||
if (string.IsNullOrWhiteSpace(fileName) || !fileName.EndsWith(".msi", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
fileName = $"YuncangTraceSetup-{_info.Version}.msi";
|
||||
}
|
||||
|
||||
var file = Path.Combine(dir, fileName);
|
||||
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(15) };
|
||||
using var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var total = response.Content.Headers.ContentLength
|
||||
?? (_info.Size > 0 ? _info.Size : (long?)null);
|
||||
|
||||
await using var source = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var target = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
|
||||
var buffer = new byte[81920];
|
||||
long received = 0;
|
||||
int read;
|
||||
|
||||
while ((read = await source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false);
|
||||
received += read;
|
||||
progress.Report((received, total));
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
private static string ComputeMd5(string file)
|
||||
{
|
||||
using var md5 = MD5.Create();
|
||||
using var stream = File.OpenRead(file);
|
||||
return Convert.ToHexString(md5.ComputeHash(stream)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static void TryDelete(string file)
|
||||
{
|
||||
try { File.Delete(file); } catch { /* 忽略 */ }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动安装:先等本进程退出(exe 被占用时 MSI 换不掉),再 /passive 安装,
|
||||
/// 装完自动把新版拉起来。perUser 安装,不需要管理员权限。
|
||||
/// </summary>
|
||||
private static void LaunchInstaller(string msiPath)
|
||||
{
|
||||
var exe = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"Programs", "YuncangTrace", "YuncangTrace.LocalService.exe");
|
||||
|
||||
var command = $"/c timeout /t 3 /nobreak >nul & msiexec /i \"{msiPath}\" /passive /norestart";
|
||||
if (File.Exists(exe))
|
||||
{
|
||||
command += $" & start \"\" \"{exe}\"";
|
||||
}
|
||||
|
||||
AppLog.Write($"启动安装程序(软件退出后执行):{msiPath}");
|
||||
|
||||
Process.Start(new ProcessStartInfo("cmd.exe", command)
|
||||
{
|
||||
CreateNoWindow = true,
|
||||
UseShellExecute = false,
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
});
|
||||
}
|
||||
|
||||
private static string FormatSize(long bytes)
|
||||
{
|
||||
if (bytes <= 0) return "未知大小";
|
||||
if (bytes >= 1024L * 1024 * 1024) return $"{bytes / 1024.0 / 1024 / 1024:0.0} GB";
|
||||
if (bytes >= 1024 * 1024) return $"{bytes / 1024.0 / 1024:0.0} MB";
|
||||
return $"{bytes / 1024.0:0} KB";
|
||||
}
|
||||
}
|
||||
@ -50,6 +50,20 @@ param(
|
||||
|
||||
$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'
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user