packServer/desktop/App.xaml.cs
liufumingren 2ab3ad35e5 主界面移除协议状态文字;修复「未登录/网络异常时不会自动更新」与「误清登录令牌」
一、UI
- 主界面删除「已注册 yuncang://(网页可叫醒本软件)」整行(`ProtocolText`),
  行定义 4→3(标题 / 查询 / 日志);删除 `UpdateProtocolState()` 及其调用。
  协议对用户是内部实现,不展示;注册由 MSI 完成、卸载自动删除、启动自动校正。

二、修复(本次测试暴露的真实缺陷)
1. **更新检查提前到登录之前**(`App.OnStartup`):
   原来放在 `ShowMainWindow()` 之后,一旦本地令牌失效/未登录,软件停在登录窗,
   **永远不会检查更新**(实测 1.0.7 → 1.0.8 卡在登录窗 180s 未更新)。
2. **`ApiClient.MeAsync` 不再把网络错误当成"令牌失效"**:
   原来 catch(ApiException) → return null,调用方据此 `SessionStore.Clear()`,
   后端启动中/一时连不上就会**误删 session.json**(本次就丢了登录态)。
   现在只有 401/403 返回 null;超时/连不上/5xx 抛异常 → 登录窗保留令牌并提示,
   下次启动仍可自动登录。

三、验证(标准流程:打包 → 启动旧版 → 自动更新)
- 打包 1.0.9(含修复)并安装(旧版 1.0.7 因缺陷无法自更新,只能手工升级一次);
- 打包 1.0.10 → `test-update.ps1`:
    当前安装 1.0.9(**处于登录窗,未登录**)→ 后端目标 1.0.10
    [4s] 1.0.9 → [10s] 1.0.10
    ✔ 自动更新完成:1.0.9 → 1.0.10(耗时 10.1s)
    ✔ 本机服务 17300 有响应(HTTP 401)
    ✔ 软件进程已恢复
  证明「未登录也能检测并完成更新」。

四、待用户操作:本次测试中 session.json 被旧逻辑误删,需要**重新登录一次**;
   之后的版本不会因为网络抖动再丢登录态。
2026-10-17 16:59:23 +08:00

452 lines
15 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.Net;
using System.Threading.Tasks;
using System.Windows;
using YuncangTrace.LocalService.Services;
namespace YuncangTrace.LocalService;
/// <summary>
/// 应用入口,负责五件事:
///
/// 1. **防多开**:全局互斥体;第二个实例把参数(可能是 `yuncang://open?code=xxx`)送给第一个实例后自己退出;
/// 2. **本机 HTTP 服务**(127.0.0.1:17300):登录前就起来,关窗口也不停(托盘里继续跑);
/// 3. **托盘图标**:关窗口 = 缩到托盘;只有从托盘菜单「退出」才真正退出;
/// 4. **登录**:有本地令牌先验证(`/api/web/me`),失效就弹登录窗;登录成功再开主窗口。
/// </summary>
public partial class App : Application
{
private const string AppName = "YuncangTrace.LocalService";
private SingleInstance? _single;
private AppSettings _settings = new();
private LocalHttpServer? _server;
private TrayIconService? _tray;
private MainWindow? _main;
private LoginWindow? _loginWindow;
private Session? _session;
private string? _pendingLaunchUrl;
private bool _exiting;
private bool _trayHintShown;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// WinForms 控件的视觉样式(否则托盘右键菜单是 Win95 风格)
System.Windows.Forms.Application.EnableVisualStyles();
// ① 防多开
_single = new SingleInstance(AppName, OnSecondInstanceArgs);
if (!_single.IsFirstInstance)
{
_single.SendArgs(e.Args);
Shutdown();
return;
}
_settings = AppSettings.Load();
ApplyServerOverride(e.Args);
_pendingLaunchUrl = ProtocolHelper.FirstLaunchUrl(e.Args);
// ② 本机服务先起来(和登录状态无关)
_server = new LocalHttpServer(new OrderQueryService());
_server.Log += AppLog.Write;
// 网页靠 /api/health 里的 loggedIn 判断要不要唤起登录,靠 /api/activate-login 把登录窗叫到前台
_server.IsLoggedInProvider = () => _session is not null;
_server.UserNameProvider = () => _session?.DisplayName;
_server.ServerBaseUrlProvider = () => _settings.ServerBaseUrl;
_server.LoginRequested += OnLoginRequested;
StartLocalServer();
// 启动协议永远指向「当前这个 exe」:换目录/从 Debug 换成发布版/重新安装后,
// 旧注册表项会指向一个不存在的或依赖开发环境的 exe(网页“启动本机软件”会直接报错)。
EnsureProtocolRegistered();
// 单实例监听要**在登录之前**起来:用户卡在登录窗时被协议唤起,参数也要能进来。
_single.StartListening();
// ③ 托盘
var version = GetType().Assembly.GetName().Version?.ToString() ?? "1.0.0";
_tray = new TrayIconService(_server.BaseUrl, version);
_tray.ShowRequested += ShowAppWindow;
_tray.RestartRequested += RestartApplication;
_tray.ExitRequested += ExitApplication;
UpdateTrayStatus();
AppLog.Write($"本机服务:{_server.BaseUrl}({(_server.IsRunning ? "运行中" : "未启动")})");
AppLog.Write($"环境:{BuildInfo.EnvironmentLabel},后端:{_settings.ServerBaseUrl}");
// ④ 检查更新(**不依赖登录**:令牌失效/未登录时也要能更新;放登录之前)
_ = CheckUpdatesAsync();
// ⑤ 登录 → 主窗口
if (!ShowLogin())
{
ExitApplication();
return;
}
ShowMainWindow();
}
/// <summary>
/// 检查更新:后端静态 <c>GET /download/version.json</c>,比当前程序集版本新就弹窗问要不要下载。
/// 网络失败 / 后端没放 version.json 都静默(这不该打扰用户)。
/// </summary>
private async Task CheckUpdatesAsync()
{
try
{
var current = GetType().Assembly.GetName().Version ?? new Version(1, 0, 0, 0);
var info = await UpdateChecker.CheckAsync(_settings.ServerBaseUrl, current);
if (info is null) return;
AppLog.Write($"发现新版本 {info.Version}(当前 {current}):{info.DownloadUrl}");
// 软件内弹窗 + 进度条下载 + 自动安装(不跳浏览器)
AppLog.Write("准备显示更新窗口…");
var update = new UpdateWindow(info, current)
{
// 回归测试用: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();
}
}
catch (Exception ex)
{
AppLog.Write($"检查更新失败:{ex.Message}");
}
}
/// <summary>
/// 把 <c>yuncang://open?code=xxx</c> 的注册表项校正到当前 exe。
/// 已经指向当前 exe 时什么都不做(幂等,每次启动都能安全调用)。
/// </summary>
private void EnsureProtocolRegistered()
{
try
{
var exe = Environment.ProcessPath;
if (string.IsNullOrEmpty(exe)) return;
var want = $"\"{exe}\" \"%1\"";
var current = ProtocolHelper.RegisteredCommand();
if (string.Equals(current, want, StringComparison.OrdinalIgnoreCase)) return;
ProtocolHelper.Register();
AppLog.Write(current is null
? $"已注册启动协议 {ProtocolHelper.Scheme}:// → {exe}"
: $"启动协议已改指向当前程序:{exe}(原来是 {current})");
}
catch (Exception ex)
{
AppLog.Write($"注册启动协议失败:{ex.Message}");
}
}
// ---------------- 登录 ----------------
/// <summary>
/// 后端地址的运行时覆盖(优先级:<c>--server=xxx</c> 参数 &gt; <c>YUNCANG_SERVER</c> 环境变量 &gt; 构建默认值)
///
/// 打包/联调时用:<c>YuncangTrace.LocalService.exe --server=http://192.168.1.10:7300</c>
/// </summary>
private void ApplyServerOverride(string[] args)
{
string? url = null;
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
const string prefix = "--server=";
if (arg.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
url = arg[prefix.Length..];
}
else if ((arg == "--server" || arg == "-s") && i + 1 < args.Length)
{
url = args[i + 1];
}
}
if (string.IsNullOrWhiteSpace(url))
{
url = Environment.GetEnvironmentVariable("YUNCANG_SERVER");
}
_settings.UseServer(url);
}
/// <summary>显示登录窗;返回 false = 用户取消(应退出程序)</summary>
private bool ShowLogin()
{
var saved = SessionStore.Load();
// 换了服务器地址就别复用旧令牌了
if (saved is not null
&& !string.Equals(saved.ServerBaseUrl, _settings.ServerBaseUrl, StringComparison.OrdinalIgnoreCase))
{
AppLog.Write("服务器地址已变更,需要重新登录");
saved = null;
}
var login = new LoginWindow(_settings, saved);
_loginWindow = login;
var accepted = login.ShowDialog() == true && login.Session is not null;
_loginWindow = null;
if (accepted)
{
_session = login.Session;
return true;
}
return false;
}
/// <summary>
/// 网页请求唤起登录(`POST /api/activate-login`):来自 HTTP 线程,切回 UI 线程处理
/// </summary>
private void OnLoginRequested()
{
Dispatcher.Invoke(() =>
{
// 已登录:把主界面叫到前台就够了
if (_session is not null)
{
ShowAppWindow();
return;
}
BringLoginWindowToFront();
});
}
/// <summary>把登录窗弹到最前(没登录时网页/协议/第二次双击都走这里)</summary>
private void BringLoginWindowToFront()
{
if (_loginWindow is null) return;
if (_loginWindow.WindowState == WindowState.Minimized) _loginWindow.WindowState = WindowState.Normal;
_loginWindow.Activate();
_loginWindow.Topmost = true;
_loginWindow.Topmost = false;
_loginWindow.Focus();
}
/// <summary>退出登录:清令牌 → 关主窗口 → 重新登录(取消则退出程序)</summary>
private void OnLogoutRequested()
{
AppLog.Write("已退出登录");
SessionStore.Clear();
_session = null;
if (_main is not null)
{
_main.AllowClose = true;
_main.Close();
_main = null;
}
if (!ShowLogin())
{
ExitApplication();
return;
}
ShowMainWindow();
}
// ---------------- 窗口 ----------------
private void ShowMainWindow()
{
var server = _server;
var session = _session;
if (server is null || session is null) return;
if (_main is null)
{
_main = new MainWindow(server, _settings, session);
_main.LogoutRequested += OnLogoutRequested;
_main.HiddenToTray += OnHiddenToTray;
}
ShowAppWindow();
// 被协议带过来的 code:登录完再查
if (_pendingLaunchUrl is not null)
{
var url = _pendingLaunchUrl;
_pendingLaunchUrl = null;
_main.HandleLaunchUrl(url);
}
}
/// <summary>把窗口显示出来(托盘双击 / 第二个实例启动时也走这里)</summary>
private void ShowAppWindow()
{
if (_main is null) return;
if (!_main.IsVisible) _main.Show();
if (_main.WindowState == WindowState.Minimized) _main.WindowState = WindowState.Normal;
_main.Activate();
_main.Topmost = true;
_main.Topmost = false;
_main.Focus();
}
private void OnHiddenToTray()
{
if (_trayHintShown) return;
_trayHintShown = true;
_tray?.ShowBalloon("云仓视频溯源软件仍在运行",
$"本机服务在 {_server?.BaseUrl} 继续提供,双击托盘图标可重新打开窗口。");
}
/// <summary>
/// 托盘菜单「重启软件」:先让本进程退出(释放单实例互斥体与 17300 端口),2 秒后再拉起自己。
/// 直接用 Process.Start 会撞上单实例检测(新进程把参数转发给正在退出的旧进程后就没了)。
/// </summary>
private void RestartApplication()
{
if (_exiting) return;
var exe = Environment.ProcessPath;
AppLog.Write($"重启软件:{exe}");
if (!string.IsNullOrEmpty(exe))
{
try
{
Process.Start(new ProcessStartInfo("cmd.exe", $"/c timeout /t 2 /nobreak >nul & start \"\" \"{exe}\"")
{
CreateNoWindow = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
});
}
catch (Exception ex)
{
AppLog.Write($"启动新进程失败:{ex.Message}");
}
}
ExitApplication();
}
// ---------------- 本机服务 ----------------
private void StartLocalServer()
{
if (_server is null) return;
try
{
_server.Start();
}
catch (HttpListenerException ex)
{
var hint = ex.ErrorCode switch
{
5 => "没有绑定端口的权限。用管理员执行一次:netsh http add urlacl url=http://localhost:17300/ user=%USERNAME%",
32 => "端口 17300 已被占用(可能还有一个本程序实例在跑)。",
_ => $"启动本机服务失败:{ex.Message}",
};
AppLog.Write(hint);
MessageBox.Show(hint, "本机服务启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
}
catch (Exception ex)
{
AppLog.Write($"启动本机服务失败:{ex.Message}");
MessageBox.Show(ex.Message, "本机服务启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
}
UpdateTrayStatus();
}
private void UpdateTrayStatus()
{
_tray?.UpdateStatus(_server?.IsRunning == true ? $"运行中 · {_server.BaseUrl}" : "本机服务未启动");
}
// ---------------- 单实例 / 退出 ----------------
/// <summary>另一个实例把参数送过来了(工作线程回调,切回 UI 线程)</summary>
private void OnSecondInstanceArgs(string[] args)
{
Dispatcher.Invoke(() =>
{
var url = ProtocolHelper.FirstLaunchUrl(args);
if (url is not null)
{
AppLog.Write($"另一个实例请求打开:{url}");
if (_main is null)
{
// 还在登录界面:先把登录窗叫到前面,参数留着登录完再查
if (url is not null) _pendingLaunchUrl = url;
BringLoginWindowToFront();
return;
}
ShowAppWindow();
_main.HandleLaunchUrl(url);
return;
}
// 第二次双击 exe(没带 URL):有主窗口就显示,还在登录就把登录窗叫到前面
if (_main is null) BringLoginWindowToFront();
else ShowAppWindow();
});
}
/// <summary>真正退出(托盘菜单 / 登录取消 / 退出登录后取消登录)</summary>
private void ExitApplication()
{
if (_exiting) return;
_exiting = true;
try
{
_tray?.Dispose();
}
catch
{
// 退出路径忽略
}
try
{
_server?.Dispose();
}
catch
{
// 退出路径忽略
}
Shutdown();
}
protected override void OnExit(ExitEventArgs e)
{
_tray?.Dispose();
_server?.Dispose();
_single?.Dispose();
base.OnExit(e);
}
}