- 后端:sys_config 存插件配置(识别前缀/生效站点/模板),平台管理员 GET/PUT /api/web/admin/extension; 插件读取 GET /api/web/extension/config(Redis 缓存 1 小时,保存即失效) - 前端:平台管理 → 插件配置页(只维护前缀,单号正则由服务端生成) - 插件:改为只拉取执行(每 5 分钟 + 手动同步),移除规则编辑/试跑/导入导出;安装包地址自动取最新发布 - 桌面端:工具 → 安装/卸载谷歌插件(生成 .reg + reg import 写 HKLM 策略,读注册表验证); 跨网下载改走云端中转;局域网探测补排障日志;自动更新按包类型取 md5Exe/sizeExe - 发布:npm run extension:publish(crx + updates.xml)、extension:zip(商店上传包), nginx 对 /download/extension/updates.xml 关缓存 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
243 lines
9.4 KiB
C#
243 lines
9.4 KiB
C#
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 → 自动静默安装并退出。
|
||
///
|
||
/// 为什么不在浏览器里打开下载链接:
|
||
/// 用户还要自己找文件、自己双击、自己处理"文件被占用";
|
||
/// 这里直接下到临时目录、校验,再静默安装(EXE 走 `/VERYSILENT`,MSI 走 `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 = "下载完成,正在校验安装包…";
|
||
|
||
// 先比大小:下载被截断时这里就能看出来,比 MD5 的报错更直白
|
||
var length = new FileInfo(file).Length;
|
||
if (_info.Size > 0 && length != _info.Size)
|
||
{
|
||
TryDelete(file);
|
||
AppLog.Write($"安装包大小不符:实际 {length},期望 {_info.Size}({file})");
|
||
StatusText.Text = "安装包不完整(大小不符),请稍后重试。";
|
||
ResetButtons();
|
||
return;
|
||
}
|
||
|
||
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.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)))
|
||
{
|
||
fileName = $"YuncangTraceSetup-{_info.Version}.exe";
|
||
}
|
||
|
||
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 被占用时换不掉),再静默安装,装完自动把新版拉起来。
|
||
/// perUser 安装,不需要管理员权限。
|
||
///
|
||
/// - `.exe`(Inno Setup):`/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-`;
|
||
/// - `.msi`(老安装包 / 老版本更新):`msiexec /i ... /passive /norestart`。
|
||
/// </summary>
|
||
private static void LaunchInstaller(string packagePath)
|
||
{
|
||
var exe = Path.Combine(
|
||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||
"Programs", "YuncangTrace", "YuncangTrace.LocalService.exe");
|
||
|
||
var isMsi = packagePath.EndsWith(".msi", StringComparison.OrdinalIgnoreCase);
|
||
var install = isMsi
|
||
? $"msiexec /i \"{packagePath}\" /passive /norestart"
|
||
: $"\"{packagePath}\" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-";
|
||
|
||
// 安装程序(setup loader)会等真正的安装进程结束才退出,所以这里能顺序等到装完再拉起软件
|
||
var command = $"/c timeout /t 3 /nobreak >nul & {install}";
|
||
if (File.Exists(exe))
|
||
{
|
||
// ⚠️ 用 explorer 拉起:从提权 cmd “start” 子进程会继续以管理员身份运行,
|
||
// 而普通权限的协议唤起无法把参数送进管理员实例(表现为“唤起没反应”)。
|
||
command += $" & timeout /t 2 /nobreak >nul & explorer.exe \"{exe}\"";
|
||
}
|
||
|
||
AppLog.Write($"启动安装程序(软件退出后执行):{packagePath}");
|
||
|
||
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";
|
||
}
|
||
}
|