packServer/desktop/UpdateWindow.xaml.cs
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

218 lines
7.9 KiB
C#
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.

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";
}
}