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;
///
/// 更新窗口:软件内下载(进度条)→ 校验 MD5 → 自动静默安装并退出。
///
/// 为什么不在浏览器里打开下载链接:
/// 用户还要自己找文件、自己双击、自己处理"文件被占用";
/// 这里直接下到临时目录、校验、`msiexec /passive` 安装,装完自动把新版拉起来。
///
public partial class UpdateWindow : Window
{
private readonly UpdateInfo _info;
private bool _busy;
///
/// 打开后自动开始下载(无 UI 自动化时用):由环境变量 YUNCANG_AUTO_UPDATE=1 开启,
/// 仅用于回归测试,正常使用不会走到。
///
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;
}
/// 下载到临时目录(流式,边下边报进度)
private async Task 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 { /* 忽略 */ }
}
///
/// 启动安装:先等本进程退出(exe 被占用时 MSI 换不掉),再 /passive 安装,
/// 装完自动把新版拉起来。perUser 安装,不需要管理员权限。
///
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";
}
}