desktop:加登录页、托盘图标、防多开(单实例 + 参数转发)
- LoginWindow:服务器地址 / 账号 / 密码 / 记住账号 → POST /api/web/auth/login 拿 user JWT; 本地已有令牌时先用 GET /api/web/me 验证,有效就跳过登录(窗口一闪而过),无效清掉令牌留下重登。 - TrayIconService(WinForms NotifyIcon,csproj 开 UseWindowsForms): 关窗口 = 隐藏到托盘(本机服务继续跑),双击托盘恢复,右键菜单「打开主界面 / 服务地址 / 版本 / 退出」; 第一次缩到托盘冒一次气泡提示。退出只走托盘「退出」(App 改 ShutdownMode=OnExplicitShutdown)。 - 防多开:SingleInstance(Local\ 命名互斥体 + 命名管道)。第二个实例不抢 17311 端口, 把 yuncang://open?code=… 转给已运行实例(在托盘里也会被弹出来并按 code 查询)后自己退出; 还在登录界面时先把 URL 存起来,登录完成后再查。 - 生命周期调整:本机 HTTP 服务与托盘在 App 里创建(登录前就可用),主窗口只管展示与操作; 日志改成全局 AppLog(窗口没开时的日志也会在窗口打开后补上)。 - 新增 AppSettings / SessionStore:%LOCALAPPDATA%\YuncangTrace\settings.json、session.json (服务器地址默认 http://127.0.0.1:7300;换服务器不会复用旧令牌)。 - 新增 ApiClient(登录 / 校验令牌)、MainWindow「退出登录」(清令牌回登录页)。 - 程序/托盘图标:Assets/app.ico + tools/make-icon.ps1(品牌蓝 + 白色播放三角)。 - csproj 关闭 ImplicitUsings:WPF 与 WinForms 同时开启时隐式命名空间会让 MessageBox / Application / Clipboard 等产生歧义。 ⚠️ 本机没有 .NET SDK,无法编译验证;已做 XAML/XML 良构与括号平衡检查。
This commit is contained in:
parent
680fff84df
commit
51abccbaaf
@ -1,8 +1,9 @@
|
||||
<Application x:Class="YuncangTrace.LocalService.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
ShutdownMode="OnMainWindowClose">
|
||||
<!-- 没有 StartupUri:窗口在 App.xaml.cs 里创建(要先判断单实例 / 协议参数) -->
|
||||
ShutdownMode="OnExplicitShutdown">
|
||||
<!-- 没有 StartupUri:窗口在 App.xaml.cs 里创建(先判断单实例,再走登录) -->
|
||||
<!-- OnExplicitShutdown:关窗口 = 缩到托盘,退出只能从托盘菜单(本机服务不能因关窗断掉) -->
|
||||
<Application.Resources>
|
||||
<SolidColorBrush x:Key="BrandBrush" Color="#2563EB" />
|
||||
<SolidColorBrush x:Key="MutedBrush" Color="#6B7280" />
|
||||
|
||||
@ -1,26 +1,41 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Windows;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
|
||||
namespace YuncangTrace.LocalService;
|
||||
|
||||
/// <summary>
|
||||
/// 应用入口
|
||||
/// 应用入口,负责四件事:
|
||||
///
|
||||
/// 两件事:**单实例**(协议被点开时系统会再启动一次本程序,要把参数转给已运行的实例)
|
||||
/// 和**把窗口拉起来**。
|
||||
/// 1. **防多开**:全局互斥体;第二个实例把参数(可能是 `yuncang://open?code=xxx`)送给第一个实例后自己退出;
|
||||
/// 2. **本机 HTTP 服务**(127.0.0.1:17311):登录前就起来,关窗口也不停(托盘里继续跑);
|
||||
/// 3. **托盘图标**:关窗口 = 缩到托盘;只有从托盘菜单「退出」才真正退出;
|
||||
/// 4. **登录**:有本地令牌先验证(`/api/web/me`),失效就弹登录窗;登录成功再开主窗口。
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
private const string AppName = "YuncangTrace.LocalService";
|
||||
|
||||
private SingleInstance? _single;
|
||||
private MainWindow? _window;
|
||||
private AppSettings _settings = new();
|
||||
private LocalHttpServer? _server;
|
||||
private TrayIconService? _tray;
|
||||
private MainWindow? _main;
|
||||
private Session? _session;
|
||||
private string? _pendingLaunchUrl;
|
||||
private bool _exiting;
|
||||
private bool _trayHintShown;
|
||||
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
base.OnStartup(e);
|
||||
|
||||
_single = new SingleInstance("YuncangTrace.LocalService", OnSecondInstanceArgs);
|
||||
// WinForms 控件的视觉样式(否则托盘右键菜单是 Win95 风格)
|
||||
System.Windows.Forms.Application.EnableVisualStyles();
|
||||
|
||||
// 已经有一个实例在跑:把自己的参数(可能是 yuncang://open?code=xxx)转过去,然后退出
|
||||
// ① 防多开
|
||||
_single = new SingleInstance(AppName, OnSecondInstanceArgs);
|
||||
if (!_single.IsFirstInstance)
|
||||
{
|
||||
_single.SendArgs(e.Args);
|
||||
@ -28,36 +43,226 @@ public partial class App : Application
|
||||
return;
|
||||
}
|
||||
|
||||
_window = new MainWindow();
|
||||
MainWindow = _window;
|
||||
_window.Show();
|
||||
_settings = AppSettings.Load();
|
||||
_pendingLaunchUrl = ProtocolHelper.FirstLaunchUrl(e.Args);
|
||||
|
||||
// 起命名管道监听(接收后续「再次启动」带来的参数)
|
||||
// ② 本机服务先起来(和登录状态无关)
|
||||
_server = new LocalHttpServer(new OrderQueryService());
|
||||
_server.Log += AppLog.Write;
|
||||
StartLocalServer();
|
||||
|
||||
// ③ 托盘
|
||||
var version = GetType().Assembly.GetName().Version?.ToString() ?? "1.0.0";
|
||||
_tray = new TrayIconService(_server.BaseUrl, version);
|
||||
_tray.ShowRequested += ShowAppWindow;
|
||||
_tray.ExitRequested += ExitApplication;
|
||||
UpdateTrayStatus();
|
||||
|
||||
AppLog.Write($"本机服务:{_server.BaseUrl}({(_server.IsRunning ? "运行中" : "未启动")})");
|
||||
|
||||
// ④ 登录 → 主窗口
|
||||
if (!ShowLogin())
|
||||
{
|
||||
ExitApplication();
|
||||
return;
|
||||
}
|
||||
|
||||
ShowMainWindow();
|
||||
_single.StartListening();
|
||||
|
||||
// 本次就是被协议拉起来的:直接进入「按 code 查信息」
|
||||
var launchUrl = ProtocolHelper.FirstLaunchUrl(e.Args);
|
||||
if (launchUrl is not null) _window.HandleLaunchUrl(launchUrl);
|
||||
}
|
||||
|
||||
// ---------------- 登录 ----------------
|
||||
|
||||
/// <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);
|
||||
if (login.ShowDialog() == true && login.Session is not null)
|
||||
{
|
||||
_session = login.Session;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <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;
|
||||
_main.ServiceStateChanged += UpdateTrayStatus;
|
||||
}
|
||||
|
||||
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} 继续提供,双击托盘图标可重新打开窗口。");
|
||||
}
|
||||
|
||||
// ---------------- 本机服务 ----------------
|
||||
|
||||
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:17311/ user=%USERNAME%",
|
||||
32 => "端口 17311 已被占用(可能还有一个本程序实例在跑)。",
|
||||
_ => $"启动本机服务失败:{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(() =>
|
||||
{
|
||||
if (MainWindow is MainWindow window)
|
||||
var url = ProtocolHelper.FirstLaunchUrl(args);
|
||||
if (url is not null)
|
||||
{
|
||||
if (window.WindowState == WindowState.Minimized) window.WindowState = WindowState.Normal;
|
||||
window.Activate();
|
||||
AppLog.Write($"另一个实例请求打开:{url}");
|
||||
|
||||
var url = ProtocolHelper.FirstLaunchUrl(args);
|
||||
if (url is not null) window.HandleLaunchUrl(url);
|
||||
if (_main is null)
|
||||
{
|
||||
// 还在登录界面:等登录完再查
|
||||
_pendingLaunchUrl = url;
|
||||
return;
|
||||
}
|
||||
|
||||
ShowAppWindow();
|
||||
_main.HandleLaunchUrl(url);
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
BIN
desktop/Assets/app.ico
Normal file
BIN
desktop/Assets/app.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.9 KiB |
42
desktop/LoginWindow.xaml
Normal file
42
desktop/LoginWindow.xaml
Normal file
@ -0,0 +1,42 @@
|
||||
<Window x:Class="YuncangTrace.LocalService.LoginWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="登录 · 云仓视频溯源软件"
|
||||
Height="500" Width="430"
|
||||
ResizeMode="NoResize"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Background="{StaticResource BgBrush}"
|
||||
FontFamily="Microsoft YaHei UI, Segoe UI"
|
||||
FontSize="13">
|
||||
<Border Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="10" Margin="26" Padding="22">
|
||||
<StackPanel>
|
||||
<TextBlock Text="云仓视频溯源软件" FontSize="18" FontWeight="SemiBold" HorizontalAlignment="Center" />
|
||||
<TextBlock Text="登录后使用本机打印与溯源服务"
|
||||
FontSize="12" Foreground="{StaticResource MutedBrush}"
|
||||
HorizontalAlignment="Center" Margin="0,6,0,18" />
|
||||
|
||||
<TextBlock Text="服务器地址" FontSize="12" Foreground="{StaticResource MutedBrush}" Margin="0,0,0,4" />
|
||||
<TextBox x:Name="ServerBox" Padding="6,5" ToolTip="后端地址,例如 http://127.0.0.1:7300" />
|
||||
|
||||
<TextBlock Text="账号(用户名 / 手机号 / 邮箱)" FontSize="12" Foreground="{StaticResource MutedBrush}" Margin="0,12,0,4" />
|
||||
<TextBox x:Name="AccountBox" Padding="6,5" />
|
||||
|
||||
<TextBlock Text="密码" FontSize="12" Foreground="{StaticResource MutedBrush}" Margin="0,12,0,4" />
|
||||
<PasswordBox x:Name="PasswordBox" Padding="6,5" KeyDown="PasswordBox_KeyDown" />
|
||||
|
||||
<CheckBox x:Name="RememberBox" Content="记住账号" Margin="0,12,0,0" />
|
||||
|
||||
<TextBlock x:Name="ErrorText" Foreground="{StaticResource BadBrush}" TextWrapping="Wrap"
|
||||
Margin="0,10,0,0" Visibility="Collapsed" />
|
||||
|
||||
<Button x:Name="LoginButton" Content="登录" Margin="0,16,0,0" Padding="0,9" FontSize="14"
|
||||
Background="{StaticResource BrandBrush}" Foreground="White" BorderThickness="0"
|
||||
Cursor="Hand" Click="Login_Click" />
|
||||
|
||||
<Button x:Name="ExitButton" Content="退出" Margin="0,8,0,0" Padding="0,6"
|
||||
Background="Transparent" BorderThickness="0" Foreground="{StaticResource MutedBrush}"
|
||||
Cursor="Hand" Click="Exit_Click" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Window>
|
||||
176
desktop/LoginWindow.xaml.cs
Normal file
176
desktop/LoginWindow.xaml.cs
Normal file
@ -0,0 +1,176 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
|
||||
namespace YuncangTrace.LocalService;
|
||||
|
||||
/// <summary>
|
||||
/// 登录窗
|
||||
///
|
||||
/// - 服务器地址 / 账号 / 密码 → `POST /api/web/auth/login` 拿 user JWT;
|
||||
/// - 本地已有令牌时,先调 `GET /api/web/me` 验证,还有效就直接跳过登录(窗口一闪而过);
|
||||
/// - 成功后把令牌存到 `%LOCALAPPDATA%\YuncangTrace\session.json`。
|
||||
/// </summary>
|
||||
public partial class LoginWindow : Window
|
||||
{
|
||||
private readonly AppSettings _settings;
|
||||
private readonly Session? _saved;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>登录成功后的会话(ShowDialog 返回 true 时可用)</summary>
|
||||
public Session? Session { get; private set; }
|
||||
|
||||
/// <summary>登录用户</summary>
|
||||
public ApiUser? User { get; private set; }
|
||||
|
||||
public LoginWindow(AppSettings settings, Session? saved)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_settings = settings;
|
||||
_saved = saved;
|
||||
|
||||
ServerBox.Text = settings.ServerBaseUrl;
|
||||
AccountBox.Text = settings.LastAccount;
|
||||
RememberBox.IsChecked = settings.RememberAccount;
|
||||
|
||||
Loaded += OnLoaded;
|
||||
}
|
||||
|
||||
private async void OnLoaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_saved is null)
|
||||
{
|
||||
AccountBox.Focus();
|
||||
return;
|
||||
}
|
||||
|
||||
await ResumeAsync();
|
||||
}
|
||||
|
||||
/// <summary>本地有令牌:问一下服务端还在不在,有效就直接进主界面</summary>
|
||||
private async Task ResumeAsync()
|
||||
{
|
||||
SetBusy(true, "正在恢复登录…");
|
||||
|
||||
try
|
||||
{
|
||||
var api = new ApiClient(_saved!.ServerBaseUrl);
|
||||
var me = await api.MeAsync(_saved.Token);
|
||||
|
||||
if (me is null)
|
||||
{
|
||||
AppLog.Write("本地登录态已失效,请重新登录");
|
||||
SessionStore.Clear();
|
||||
SetBusy(false);
|
||||
AccountBox.Focus();
|
||||
return;
|
||||
}
|
||||
|
||||
Session = _saved;
|
||||
User = me;
|
||||
AppLog.Write($"已恢复登录:{me.DisplayName}");
|
||||
DialogResult = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"恢复登录失败:{ex.Message}");
|
||||
SetBusy(false);
|
||||
ShowError($"恢复登录失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void Login_Click(object sender, RoutedEventArgs e) => _ = DoLoginAsync();
|
||||
|
||||
private void PasswordBox_KeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.Enter) _ = DoLoginAsync();
|
||||
}
|
||||
|
||||
private async Task DoLoginAsync()
|
||||
{
|
||||
if (_busy) return;
|
||||
|
||||
var server = AppSettings.Normalize(ServerBox.Text);
|
||||
var account = AccountBox.Text.Trim();
|
||||
var password = PasswordBox.Password;
|
||||
|
||||
if (account.Length == 0)
|
||||
{
|
||||
ShowError("请填写账号");
|
||||
AccountBox.Focus();
|
||||
return;
|
||||
}
|
||||
if (password.Length == 0)
|
||||
{
|
||||
ShowError("请填写密码");
|
||||
PasswordBox.Focus();
|
||||
return;
|
||||
}
|
||||
|
||||
ClearError();
|
||||
SetBusy(true, "正在登录…");
|
||||
|
||||
try
|
||||
{
|
||||
var api = new ApiClient(server);
|
||||
var (session, user) = await api.LoginAsync(account, password);
|
||||
|
||||
session.DisplayName = user.DisplayName;
|
||||
SessionStore.Save(session);
|
||||
|
||||
_settings.ServerBaseUrl = server;
|
||||
_settings.RememberAccount = RememberBox.IsChecked == true;
|
||||
_settings.LastAccount = _settings.RememberAccount ? account : string.Empty;
|
||||
_settings.Save();
|
||||
|
||||
Session = session;
|
||||
User = user;
|
||||
|
||||
AppLog.Write($"登录成功:{user.DisplayName}({server})");
|
||||
DialogResult = true;
|
||||
}
|
||||
catch (ApiException ex)
|
||||
{
|
||||
ShowError(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ShowError($"登录失败:{ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetBusy(bool busy, string? text = null)
|
||||
{
|
||||
_busy = busy;
|
||||
|
||||
LoginButton.IsEnabled = !busy;
|
||||
ExitButton.IsEnabled = !busy;
|
||||
ServerBox.IsEnabled = !busy;
|
||||
AccountBox.IsEnabled = !busy;
|
||||
PasswordBox.IsEnabled = !busy;
|
||||
RememberBox.IsEnabled = !busy;
|
||||
|
||||
LoginButton.Content = busy ? (text ?? "请稍候…") : "登录";
|
||||
}
|
||||
|
||||
private void ShowError(string message)
|
||||
{
|
||||
ErrorText.Text = message;
|
||||
ErrorText.Visibility = Visibility.Visible;
|
||||
}
|
||||
|
||||
private void ClearError()
|
||||
{
|
||||
ErrorText.Text = string.Empty;
|
||||
ErrorText.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
|
||||
private void Exit_Click(object sender, RoutedEventArgs e) => DialogResult = false;
|
||||
}
|
||||
@ -18,12 +18,13 @@
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- ① 标题 + 运行状态 -->
|
||||
<!-- ① 标题 + 运行状态 + 当前登录用户 -->
|
||||
<DockPanel Grid.Row="0" Margin="0,0,0,14">
|
||||
<TextBlock DockPanel.Dock="Right"
|
||||
Text="云仓视频溯源系统"
|
||||
Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" />
|
||||
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="UserText" Text="未登录" Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<Button Content="退出登录" Padding="10,4" Click="Logout_Click" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Ellipse x:Name="StatusDot" Width="10" Height="10" Margin="0,0,8,0"
|
||||
VerticalAlignment="Center" Fill="{StaticResource BadBrush}" />
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
@ -9,32 +10,52 @@ using YuncangTrace.LocalService.Services;
|
||||
namespace YuncangTrace.LocalService;
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口:起/停本机 HTTP 服务、注册启动协议、手工测一条查询、看日志
|
||||
/// 主窗口:本机服务状态、启动协议、测试查询、日志、当前登录用户
|
||||
///
|
||||
/// 服务地址固定 <c>http://localhost:17311</c>(前端公共页 /local 与 Chrome 插件都按这个地址写死)。
|
||||
/// 关窗口**不是退出**:只是隐藏到托盘(本机服务得继续跑)。
|
||||
/// 真正退出:托盘菜单「退出」,或点「退出登录」后再取消登录。
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
private readonly ObservableCollection<string> _logs = new();
|
||||
private readonly OrderQueryService _queryService = new();
|
||||
private readonly LocalHttpServer _server;
|
||||
private readonly OrderQueryService _queryService = new();
|
||||
|
||||
public MainWindow()
|
||||
/// <summary>允许真正关闭窗口(退出登录 / 退出程序时由 App 置 true)</summary>
|
||||
public bool AllowClose { get; set; }
|
||||
|
||||
/// <summary>用户点了「退出登录」</summary>
|
||||
public event Action? LogoutRequested;
|
||||
|
||||
/// <summary>窗口被隐藏到托盘(用来弹一次气泡提示)</summary>
|
||||
public event Action? HiddenToTray;
|
||||
|
||||
/// <summary>本机服务的启/停状态变了(App 用它同步托盘上的文案)</summary>
|
||||
public event Action? ServiceStateChanged;
|
||||
|
||||
public MainWindow(LocalHttpServer server, AppSettings settings, Session session)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
_server = new LocalHttpServer(_queryService);
|
||||
_server.Log += AppendLog;
|
||||
_server = server;
|
||||
|
||||
UserText.Text = $"已登录:{session.DisplayName}";
|
||||
UserText.ToolTip = $"服务器:{settings.ServerBaseUrl}";
|
||||
AddressBox.Text = _server.BaseUrl;
|
||||
|
||||
// 日志:先灌历史(服务在登录前就起来了),再订阅新的
|
||||
foreach (var line in AppLog.History) _logs.Add(line);
|
||||
|
||||
LogList.ItemsSource = _logs;
|
||||
AddressBox.Text = _server.BaseUrl;
|
||||
AppLog.Written += OnLogWritten;
|
||||
|
||||
Loaded += (_, _) =>
|
||||
{
|
||||
StartServer();
|
||||
UpdateServerState();
|
||||
UpdateProtocolState();
|
||||
};
|
||||
Closed += (_, _) => _server.Dispose();
|
||||
Closing += OnClosing;
|
||||
Closed += (_, _) => AppLog.Written -= OnLogWritten;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -42,12 +63,12 @@ public partial class MainWindow : Window
|
||||
/// </summary>
|
||||
public void HandleLaunchUrl(string url)
|
||||
{
|
||||
AppendLog($"收到启动协议:{url}");
|
||||
AppLog.Write($"收到启动协议:{url}");
|
||||
|
||||
var code = ProtocolHelper.ParseCode(url);
|
||||
if (code is null)
|
||||
{
|
||||
AppendLog("协议里没带 code,忽略");
|
||||
AppLog.Write("协议里没带 code,忽略");
|
||||
return;
|
||||
}
|
||||
|
||||
@ -57,32 +78,6 @@ public partial class MainWindow : Window
|
||||
|
||||
// ---------------- 服务启停 ----------------
|
||||
|
||||
private void StartServer()
|
||||
{
|
||||
try
|
||||
{
|
||||
_server.Start();
|
||||
}
|
||||
catch (HttpListenerException ex)
|
||||
{
|
||||
var hint = ex.ErrorCode switch
|
||||
{
|
||||
5 => "没有绑定端口的权限。用管理员执行一次:netsh http add urlacl url=http://localhost:17311/ user=%USERNAME%",
|
||||
32 => "端口 17311 已被占用(可能已经开了一个本程序的实例)。",
|
||||
_ => "启动失败:" + ex.Message,
|
||||
};
|
||||
AppendLog(hint);
|
||||
MessageBox.Show(this, hint, "本机服务启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppendLog($"启动失败:{ex.Message}");
|
||||
MessageBox.Show(this, ex.Message, "本机服务启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
|
||||
UpdateServerState();
|
||||
}
|
||||
|
||||
private void StartStop_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_server.IsRunning)
|
||||
@ -91,7 +86,15 @@ public partial class MainWindow : Window
|
||||
}
|
||||
else
|
||||
{
|
||||
StartServer();
|
||||
try
|
||||
{
|
||||
_server.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"启动本机服务失败:{ex.Message}");
|
||||
MessageBox.Show(this, ex.Message, "启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
UpdateServerState();
|
||||
@ -104,6 +107,8 @@ public partial class MainWindow : Window
|
||||
StatusText.Text = running ? $"运行中 · {_server.BaseUrl}" : "未启动";
|
||||
StatusDot.Fill = (Brush)FindResource(running ? "OkBrush" : "BadBrush");
|
||||
StartStopButton.Content = running ? "停止服务" : "启动服务";
|
||||
|
||||
ServiceStateChanged?.Invoke();
|
||||
}
|
||||
|
||||
// ---------------- 启动协议 ----------------
|
||||
@ -120,17 +125,17 @@ public partial class MainWindow : Window
|
||||
if (answer != MessageBoxResult.Yes) return;
|
||||
|
||||
ProtocolHelper.Unregister();
|
||||
AppendLog("已取消注册启动协议");
|
||||
AppLog.Write("已取消注册启动协议");
|
||||
}
|
||||
else
|
||||
{
|
||||
ProtocolHelper.Register();
|
||||
AppendLog($"已注册启动协议:{ProtocolHelper.Scheme}:// → {ProtocolHelper.RegisteredCommand()}");
|
||||
AppLog.Write($"已注册启动协议:{ProtocolHelper.Scheme}:// → {ProtocolHelper.RegisteredCommand()}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppendLog($"操作启动协议失败:{ex.Message}");
|
||||
AppLog.Write($"操作启动协议失败:{ex.Message}");
|
||||
MessageBox.Show(this, ex.Message, "启动协议", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
|
||||
@ -159,7 +164,7 @@ public partial class MainWindow : Window
|
||||
private void RunQuery()
|
||||
{
|
||||
var code = QueryBox.Text.Trim();
|
||||
AppendLog($"查询:{code}");
|
||||
AppLog.Write($"查询:{code}");
|
||||
|
||||
var result = _queryService.Query(code);
|
||||
ResultBox.Text = result.Ok
|
||||
@ -169,6 +174,28 @@ public partial class MainWindow : Window
|
||||
ResultBox.ScrollToHome();
|
||||
}
|
||||
|
||||
// ---------------- 退出登录 / 关闭 ----------------
|
||||
|
||||
private void Logout_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var answer = MessageBox.Show(this,
|
||||
$"要退出登录吗?(本机服务会继续运行,重新登录后可继续使用)",
|
||||
"退出登录", MessageBoxButton.YesNo, MessageBoxImage.Question);
|
||||
if (answer != MessageBoxResult.Yes) return;
|
||||
|
||||
LogoutRequested?.Invoke();
|
||||
}
|
||||
|
||||
private void OnClosing(object? sender, CancelEventArgs e)
|
||||
{
|
||||
if (AllowClose) return;
|
||||
|
||||
// 关窗口 = 缩到托盘,别把本机服务带走
|
||||
e.Cancel = true;
|
||||
Hide();
|
||||
HiddenToTray?.Invoke();
|
||||
}
|
||||
|
||||
// ---------------- 小工具 ----------------
|
||||
|
||||
private void CopyAddress_Click(object sender, RoutedEventArgs e) => CopyText(_server.BaseUrl);
|
||||
@ -184,7 +211,7 @@ public partial class MainWindow : Window
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppendLog($"打开浏览器失败:{ex.Message}");
|
||||
AppLog.Write($"打开浏览器失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -193,19 +220,17 @@ public partial class MainWindow : Window
|
||||
try
|
||||
{
|
||||
Clipboard.SetText(text);
|
||||
AppendLog($"已复制:{text}");
|
||||
AppLog.Write($"已复制:{text}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppendLog($"复制失败:{ex.Message}");
|
||||
AppLog.Write($"复制失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>日志(服务线程也会调,切回 UI 线程再改集合)</summary>
|
||||
private void AppendLog(string message)
|
||||
/// <summary>日志(HTTP 服务线程也会触发,切回 UI 线程再改集合)</summary>
|
||||
private void OnLogWritten(string line)
|
||||
{
|
||||
var line = $"[{DateTime.Now:HH:mm:ss}] {message}";
|
||||
|
||||
if (!Dispatcher.CheckAccess())
|
||||
{
|
||||
Dispatcher.BeginInvoke(new Action(() => Append(line)));
|
||||
@ -219,7 +244,7 @@ public partial class MainWindow : Window
|
||||
{
|
||||
_logs.Add(line);
|
||||
|
||||
// 只留最近 300 行,免得越跑越占内存
|
||||
// 只留最近 300 行
|
||||
while (_logs.Count > 300) _logs.RemoveAt(0);
|
||||
|
||||
if (_logs.Count > 0) LogList.ScrollIntoView(_logs[^1]);
|
||||
|
||||
@ -2,24 +2,51 @@
|
||||
|
||||
Windows 桌面端,用**前端 `/local` 公共页**和 **Chrome 插件**做对接:
|
||||
|
||||
- **登录页**:账号密码登录后端(`POST /api/web/auth/login`)拿 user JWT,令牌存本机;
|
||||
下次启动先用 `/api/web/me` 验证,还有效就直接进主界面;
|
||||
- 在 `127.0.0.1:17311` 起一个本机 HTTP 服务,浏览器里的页面直接查询本机数据;
|
||||
- 注册 `yuncang://` 启动协议,网页可以「叫醒」本软件(前提是已安装);
|
||||
- 单实例:被协议再次拉起时,只把 `code` 转给已运行的窗口,不会抢端口。
|
||||
- **托盘图标**:关窗口只是缩到托盘(本机服务不能因关窗断掉),双击托盘恢复窗口,
|
||||
右键菜单有「打开主界面 / 服务地址 / 退出」;
|
||||
- **防多开**:全局互斥体 + 命名管道 —— 第二个实例不会抢 17311 端口,而是把
|
||||
`yuncang://open?code=xxx` 转给已运行的实例(在托盘里也会被叫出来并直接查询),然后自己退出。
|
||||
|
||||
```
|
||||
desktop/
|
||||
├── YuncangTrace.LocalService.csproj # net8.0-windows + UseWPF
|
||||
├── YuncangTrace.LocalService.csproj # net8.0-windows + UseWPF + UseWindowsForms(托盘)
|
||||
├── app.manifest # 高 DPI / 兼容性声明
|
||||
├── App.xaml / App.xaml.cs # 单实例 + 协议参数处理
|
||||
├── MainWindow.xaml / .xaml.cs # 状态、地址、协议注册、测试查询、日志
|
||||
├── Assets/app.ico # 程序/托盘图标(tools/make-icon.ps1 生成)
|
||||
├── App.xaml / App.xaml.cs # 防多开 + 托盘 + 登录流程 + 本机服务生命周期
|
||||
├── LoginWindow.xaml / .xaml.cs # 服务器地址 / 账号 / 密码 / 记住账号 / 自动恢复登录
|
||||
├── MainWindow.xaml / .xaml.cs # 服务状态、地址、协议注册、测试查询、日志、退出登录
|
||||
└── Services/
|
||||
├── LocalHttpServer.cs # HttpListener + CORS + PNA
|
||||
├── OrderQueryService.cs # ★ 按运单号查数据(接真实数据源的地方)
|
||||
├── ApiClient.cs # 登录 / 校验令牌(用到的全部后端接口)
|
||||
├── SessionStore.cs # 登录态(%LOCALAPPDATA%\YuncangTrace\session.json)
|
||||
├── AppSettings.cs # 服务器地址 / 记住账号(%LOCALAPPDATA%\YuncangTrace\settings.json)
|
||||
├── ProtocolHelper.cs # yuncang:// 注册/反注册、解析 code
|
||||
├── SingleInstance.cs # 互斥体 + 命名管道转发参数
|
||||
├── SingleInstance.cs # 互斥体 + 命名管道转发参数(防多开)
|
||||
├── TrayIconService.cs # 托盘图标与菜单
|
||||
├── AppLog.cs # 全局日志缓冲(窗口没开时的日志也不丢)
|
||||
└── JsonUtil.cs # JSON 序列化(中文不转义)
|
||||
```
|
||||
|
||||
## 登录 / 托盘 / 防多开的行为
|
||||
|
||||
| 场景 | 行为 |
|
||||
| --- | --- |
|
||||
| 首次启动 | 先起本机服务(17311)与托盘,再弹登录页 → 登录成功才出主窗口 |
|
||||
| 已有令牌 | 登录窗一闪而过:`/api/web/me` 通过就直接进主窗口;失效则清掉令牌留在登录页 |
|
||||
| 关窗口(X) | 隐藏到托盘,本机服务继续跑(第一次会冒一个气泡提示) |
|
||||
| 再次双击 exe / 点网页「启动本机软件」 | 不会开第二个:把 `yuncang://open?code=…` 通过命名管道转给已运行实例 |
|
||||
| 托盘双击 / 右键「打开主界面」 | 恢复窗口 |
|
||||
| 「退出登录」 | 清令牌 → 关闭主窗口 → 回到登录页(取消登录则退出程序) |
|
||||
| 托盘右键「退出」 | 真正退出(dispose 托盘与本机服务) |
|
||||
|
||||
服务器地址默认 `http://127.0.0.1:7300`(后端 dev 默认端口),登录页上可以改,改完会存进 `settings.json`。
|
||||
换服务器后不会复用旧令牌(会要求重新登录)。
|
||||
|
||||
## 环境要求
|
||||
|
||||
- 编译:**.NET 8 SDK**(`dotnet --list-sdks` 能看到 `8.x`)
|
||||
|
||||
181
desktop/Services/ApiClient.cs
Normal file
181
desktop/Services/ApiClient.cs
Normal file
@ -0,0 +1,181 @@
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>接口调用失败(能拿到后端的 message 就透出去)</summary>
|
||||
public sealed class ApiException : Exception
|
||||
{
|
||||
public ApiException(string message, int statusCode = 0) : base(message)
|
||||
{
|
||||
StatusCode = statusCode;
|
||||
}
|
||||
|
||||
/// <summary>HTTP 状态码(网络层失败为 0)</summary>
|
||||
public int StatusCode { get; }
|
||||
}
|
||||
|
||||
/// <summary>登录用户(后端 `/api/web/auth/login` 返回的 user 子集)</summary>
|
||||
public sealed record ApiUser(int Id, string? Username, string? Nickname)
|
||||
{
|
||||
/// <summary>界面显示名</summary>
|
||||
public string DisplayName =>
|
||||
!string.IsNullOrWhiteSpace(Nickname) ? Nickname!
|
||||
: !string.IsNullOrWhiteSpace(Username) ? Username!
|
||||
: $"#{Id}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 后端接口客户端(只用到登录 + 校验令牌,够桌面端跑起来)
|
||||
///
|
||||
/// 契约见 frontend/README:成功 `{ ok:true, data }`,失败 `{ ok:false, message }`。
|
||||
/// </summary>
|
||||
public sealed class ApiClient
|
||||
{
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(15) };
|
||||
|
||||
private static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
|
||||
public ApiClient(string serverBaseUrl)
|
||||
{
|
||||
BaseUrl = AppSettings.Normalize(serverBaseUrl);
|
||||
}
|
||||
|
||||
/// <summary>后端根地址(已去掉末尾斜杠)</summary>
|
||||
public string BaseUrl { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 账号密码登录(`POST /api/web/auth/login`)
|
||||
/// </summary>
|
||||
/// <exception cref="ApiException">账号密码错 / 网络不通 / 返回格式不对</exception>
|
||||
public async Task<(Session Session, ApiUser User)> LoginAsync(
|
||||
string account, string password, CancellationToken ct = default)
|
||||
{
|
||||
var body = JsonSerializer.Serialize(new { account, password }, Json);
|
||||
|
||||
using var content = new StringContent(body, Encoding.UTF8, "application/json");
|
||||
using var response = await SendAsync(
|
||||
() => new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/api/web/auth/login") { Content = content },
|
||||
"登录", ct).ConfigureAwait(false);
|
||||
|
||||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var (data, message) = ReadEnvelope(response, text);
|
||||
if (data is null)
|
||||
{
|
||||
throw new ApiException(message, (int)response.StatusCode);
|
||||
}
|
||||
|
||||
var token = GetString(data.Value, "token")
|
||||
?? throw new ApiException("登录返回里没有令牌");
|
||||
var user = ReadUser(data.Value);
|
||||
|
||||
var session = new Session
|
||||
{
|
||||
Token = token,
|
||||
UserId = user.Id,
|
||||
DisplayName = user.DisplayName,
|
||||
ServerBaseUrl = BaseUrl,
|
||||
};
|
||||
return (session, user);
|
||||
}
|
||||
|
||||
/// <summary>校验令牌是否还有效(`GET /api/web/me`),无效返回 null</summary>
|
||||
public async Task<ApiUser?> MeAsync(string token, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var response = await SendAsync(() =>
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/api/web/me");
|
||||
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}");
|
||||
return request;
|
||||
}, "校验登录态", ct).ConfigureAwait(false);
|
||||
|
||||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var (data, _) = ReadEnvelope(response, text);
|
||||
return data is null ? null : ReadUser(data.Value);
|
||||
}
|
||||
catch (ApiException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>发请求:连不上时翻成「无法连接服务器」这种能看懂的提示</summary>
|
||||
private async Task<HttpResponseMessage> SendAsync(
|
||||
Func<HttpRequestMessage> createRequest, string action, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var request = createRequest();
|
||||
return await Http.SendAsync(request, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
throw new ApiException("连接服务器超时,请检查服务器地址或网络");
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
throw new ApiException($"无法连接服务器({BaseUrl}):{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析 `{ ok, data, message }`:成功返回 data(JSON 片段),失败返回 message
|
||||
/// </summary>
|
||||
private static (JsonElement? Data, string Message) ReadEnvelope(HttpResponseMessage response, string text)
|
||||
{
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(string.IsNullOrWhiteSpace(text) ? "{}" : text);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return (null, $"服务器返回了非 JSON 内容(HTTP {(int)response.StatusCode})");
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
var root = document.RootElement;
|
||||
|
||||
var ok = root.TryGetProperty("ok", out var okElement)
|
||||
&& okElement.ValueKind == JsonValueKind.True;
|
||||
|
||||
if (ok && root.TryGetProperty("data", out var dataElement))
|
||||
{
|
||||
// 复制一份出来(document 释放后就失效了)
|
||||
return (dataElement.Clone(), "ok");
|
||||
}
|
||||
|
||||
var message = GetString(root, "message")
|
||||
?? $"请求失败(HTTP {(int)response.StatusCode})";
|
||||
return (null, message);
|
||||
}
|
||||
}
|
||||
|
||||
private static ApiUser ReadUser(JsonElement data)
|
||||
{
|
||||
// 登录接口是 { token, user },/api/web/me 是直接一个 user
|
||||
var userElement = data.TryGetProperty("user", out var nested) ? nested : data;
|
||||
|
||||
var id = userElement.TryGetProperty("id", out var idElement) && idElement.TryGetInt32(out var value) ? value : 0;
|
||||
var username = GetString(userElement, "username");
|
||||
var nickname = GetString(userElement, "nickname");
|
||||
return new ApiUser(id, username, nickname);
|
||||
}
|
||||
|
||||
private static string? GetString(JsonElement element, string property)
|
||||
{
|
||||
return element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String
|
||||
? value.GetString()
|
||||
: null;
|
||||
}
|
||||
}
|
||||
47
desktop/Services/AppLog.cs
Normal file
47
desktop/Services/AppLog.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 进程级日志(托盘 / 登录窗 / 主窗 / HTTP 服务都往这里写)
|
||||
///
|
||||
/// 服务在登录之前就起来了,那时主窗口还不存在 —— 所以日志要有个全局缓冲,
|
||||
/// 主窗口打开时用 <see cref="History"/> 把历史补上。
|
||||
/// </summary>
|
||||
public static class AppLog
|
||||
{
|
||||
private const int MaxLines = 300;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static readonly Queue<string> Buffer = new();
|
||||
|
||||
/// <summary>新日志(订阅方负责切回 UI 线程)</summary>
|
||||
public static event Action<string>? Written;
|
||||
|
||||
/// <summary>写入一行日志</summary>
|
||||
public static void Write(string message)
|
||||
{
|
||||
var line = $"[{DateTime.Now:HH:mm:ss}] {message}";
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
Buffer.Enqueue(line);
|
||||
while (Buffer.Count > MaxLines) Buffer.Dequeue();
|
||||
}
|
||||
|
||||
Written?.Invoke(line);
|
||||
}
|
||||
|
||||
/// <summary>最近的历史日志(窗口初始化时灌进去)</summary>
|
||||
public static IReadOnlyList<string> History
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
return Buffer.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
84
desktop/Services/AppSettings.cs
Normal file
84
desktop/Services/AppSettings.cs
Normal file
@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本机设置:`%LOCALAPPDATA%\YuncangTrace\settings.json`
|
||||
///
|
||||
/// 目前只有「服务器地址」(登录用的后端)和「记住账号」。
|
||||
/// </summary>
|
||||
public sealed class AppSettings
|
||||
{
|
||||
/// <summary>默认后端地址(本地开发)</summary>
|
||||
public const string DefaultServer = "http://127.0.0.1:7300";
|
||||
|
||||
/// <summary>后端 API 根地址(登录、校验令牌都走它)</summary>
|
||||
public string ServerBaseUrl { get; set; } = DefaultServer;
|
||||
|
||||
/// <summary>上次登录的账号(只在「记住账号」勾选时保存)</summary>
|
||||
public string LastAccount { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>是否记住账号</summary>
|
||||
public bool RememberAccount { get; set; } = true;
|
||||
|
||||
private static string Dir => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YuncangTrace");
|
||||
|
||||
private static string FilePath => Path.Combine(Dir, "settings.json");
|
||||
|
||||
private static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
|
||||
/// <summary>读设置(读不到就用默认值,绝不抛)</summary>
|
||||
public static AppSettings Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath)) return new AppSettings();
|
||||
|
||||
var settings = JsonSerializer.Deserialize<AppSettings>(File.ReadAllText(FilePath));
|
||||
if (settings is null) return new AppSettings();
|
||||
|
||||
settings.ServerBaseUrl = Normalize(settings.ServerBaseUrl);
|
||||
return settings;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"读取设置失败(用默认值):{ex.Message}");
|
||||
return new AppSettings();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>存设置(失败只记日志)</summary>
|
||||
public void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
ServerBaseUrl = Normalize(ServerBaseUrl);
|
||||
if (!RememberAccount) LastAccount = string.Empty;
|
||||
|
||||
Directory.CreateDirectory(Dir);
|
||||
File.WriteAllText(FilePath, JsonSerializer.Serialize(this, Options));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"保存设置失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>统一成 `http://host:port` 形式(去掉末尾斜杠,没写协议就补 http://)</summary>
|
||||
public static string Normalize(string? url)
|
||||
{
|
||||
var value = (url ?? string.Empty).Trim();
|
||||
if (value.Length == 0) return DefaultServer;
|
||||
|
||||
if (!value.Contains("://", StringComparison.Ordinal)) value = "http://" + value;
|
||||
return value.TrimEnd('/');
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,5 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>JSON 序列化(中文不转义,方便人看;输出紧凑,省得前端表格里一堆空格)</summary>
|
||||
|
||||
@ -1,5 +1,8 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
|
||||
@ -1,3 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>一次查询的结果(HTTP 层和界面都复用)</summary>
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
86
desktop/Services/SessionStore.cs
Normal file
86
desktop/Services/SessionStore.cs
Normal file
@ -0,0 +1,86 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 登录态(`%LOCALAPPDATA%\YuncangTrace\session.json`)
|
||||
///
|
||||
/// 只是把后端下发的 user JWT 存在本机,启动时用它调 `GET /api/web/me` 验证一下还在不在;
|
||||
/// 验证不过就直接丢掉重新登录(**不**自己解析 JWT 过期时间,以服务端为准)。
|
||||
/// </summary>
|
||||
public sealed class Session
|
||||
{
|
||||
/// <summary>后端签发的用户令牌(请求时放 Authorization: Bearer)</summary>
|
||||
public string Token { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>用户 id</summary>
|
||||
public int UserId { get; set; }
|
||||
|
||||
/// <summary>界面显示名(昵称优先)</summary>
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>登录时用的服务器地址(换了服务器就要重新登录)</summary>
|
||||
public string ServerBaseUrl { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>登录态的读写</summary>
|
||||
public static class SessionStore
|
||||
{
|
||||
private static string Dir => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YuncangTrace");
|
||||
|
||||
private static string FilePath => Path.Combine(Dir, "session.json");
|
||||
|
||||
private static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
|
||||
/// <summary>读登录态(没有/坏了返回 null)</summary>
|
||||
public static Session? Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath)) return null;
|
||||
|
||||
var session = JsonSerializer.Deserialize<Session>(File.ReadAllText(FilePath));
|
||||
return string.IsNullOrWhiteSpace(session?.Token) ? null : session;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"读取登录态失败:{ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>保存登录态</summary>
|
||||
public static void Save(Session session)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Dir);
|
||||
File.WriteAllText(FilePath, JsonSerializer.Serialize(session, Options));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"保存登录态失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>清掉登录态(退出登录 / 令牌失效时调)</summary>
|
||||
public static void Clear()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(FilePath)) File.Delete(FilePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"清除登录态失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
|
||||
115
desktop/Services/TrayIconService.cs
Normal file
115
desktop/Services/TrayIconService.cs
Normal file
@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using WinForms = System.Windows.Forms;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 托盘图标(WPF 没有内置托盘,用 WinForms 的 <see cref="WinForms.NotifyIcon"/>)
|
||||
///
|
||||
/// 关窗口 = 缩到托盘,程序继续跑(本机服务不能因为关窗就断)。
|
||||
/// 退出只能从托盘菜单「退出」。
|
||||
/// </summary>
|
||||
public sealed class TrayIconService : IDisposable
|
||||
{
|
||||
private readonly WinForms.NotifyIcon _icon;
|
||||
private readonly WinForms.ToolStripMenuItem _statusItem;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>要显示主界面(双击托盘 / 菜单「打开主界面」)</summary>
|
||||
public event Action? ShowRequested;
|
||||
|
||||
/// <summary>要退出程序</summary>
|
||||
public event Action? ExitRequested;
|
||||
|
||||
public TrayIconService(string serverUrl, string version)
|
||||
{
|
||||
_statusItem = new WinForms.ToolStripMenuItem($"服务:{serverUrl}") { Enabled = false };
|
||||
|
||||
var menu = new WinForms.ContextMenuStrip();
|
||||
menu.Items.Add(new WinForms.ToolStripMenuItem("打开主界面", null, (_, _) => ShowRequested?.Invoke()));
|
||||
menu.Items.Add(_statusItem);
|
||||
menu.Items.Add(new WinForms.ToolStripMenuItem($"版本 {version}") { Enabled = false });
|
||||
menu.Items.Add(new WinForms.ToolStripSeparator());
|
||||
menu.Items.Add(new WinForms.ToolStripMenuItem("退出", null, (_, _) => ExitRequested?.Invoke()));
|
||||
|
||||
_icon = new WinForms.NotifyIcon
|
||||
{
|
||||
Icon = LoadIcon(),
|
||||
Text = "云仓视频溯源软件(本机服务)",
|
||||
Visible = true,
|
||||
ContextMenuStrip = menu,
|
||||
};
|
||||
|
||||
// 双击托盘 → 打开主界面
|
||||
_icon.DoubleClick += (_, _) => ShowRequested?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>更新托盘提示(服务地址 / 运行状态)</summary>
|
||||
public void UpdateStatus(string text)
|
||||
{
|
||||
if (_disposed) return;
|
||||
|
||||
_statusItem.Text = text;
|
||||
|
||||
// NotifyIcon.Text 最多 63 个字符,超了会抛异常
|
||||
var tip = $"云仓视频溯源软件\n{text}";
|
||||
_icon.Text = tip.Length <= 63 ? tip : tip[..63];
|
||||
}
|
||||
|
||||
/// <summary>冒一个气泡提示(第一次缩到托盘时用)</summary>
|
||||
public void ShowBalloon(string title, string text)
|
||||
{
|
||||
if (_disposed) return;
|
||||
|
||||
try
|
||||
{
|
||||
_icon.BalloonTipTitle = title;
|
||||
_icon.BalloonTipText = text;
|
||||
_icon.ShowBalloonTip(3000);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"托盘气泡提示失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取 exe 自带的图标(csproj 里 ApplicationIcon),取不到就用系统默认
|
||||
/// </summary>
|
||||
private static Icon LoadIcon()
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = Environment.ProcessPath;
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
{
|
||||
var icon = Icon.ExtractAssociatedIcon(path);
|
||||
if (icon is not null) return icon;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"读取程序图标失败:{ex.Message}");
|
||||
}
|
||||
|
||||
return SystemIcons.Application;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
|
||||
_disposed = true;
|
||||
try
|
||||
{
|
||||
_icon.Visible = false;
|
||||
_icon.ContextMenuStrip?.Dispose();
|
||||
_icon.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 退出路径上忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -5,10 +5,20 @@
|
||||
<!-- WPF 只能跑在 Windows 上;net8.0-windows 是当前 LTS -->
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<!-- 托盘图标用 WinForms 的 NotifyIcon(WPF 没有内置托盘) -->
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
|
||||
<!--
|
||||
⚠️ 必须关掉隐式 using:WPF 与 WinForms 同时开启时,两边的隐式命名空间会让
|
||||
MessageBox / Application / Clipboard / Point 等类型产生歧义(编译不过)。
|
||||
各文件里显式 using 自己需要的命名空间。
|
||||
-->
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
|
||||
<ApplicationIcon>Assets\app.ico</ApplicationIcon>
|
||||
|
||||
<!-- 产物名/程序集名(安装包里 exe 就叫这个) -->
|
||||
<AssemblyName>YuncangTrace.LocalService</AssemblyName>
|
||||
<RootNamespace>YuncangTrace.LocalService</RootNamespace>
|
||||
|
||||
56
desktop/tools/make-icon.ps1
Normal file
56
desktop/tools/make-icon.ps1
Normal file
@ -0,0 +1,56 @@
|
||||
# 生成 desktop/Assets/app.ico(256×256,PNG 压缩的 ICO)
|
||||
# 用法:powershell -ExecutionPolicy Bypass -File desktop/tools/make-icon.ps1
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$out = Join-Path $PSScriptRoot '..\Assets\app.ico'
|
||||
$out = [System.IO.Path]::GetFullPath($out)
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path $out) | Out-Null
|
||||
|
||||
$size = 256
|
||||
$bmp = New-Object System.Drawing.Bitmap $size, $size
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$g.Clear([System.Drawing.Color]::Transparent)
|
||||
|
||||
# 品牌蓝底 + 白色播放三角("视频溯源")
|
||||
$bg = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(255, 37, 99, 235))
|
||||
$g.FillRectangle($bg, 12, 12, 232, 232)
|
||||
|
||||
$play = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::White)
|
||||
$points = @(
|
||||
(New-Object System.Drawing.Point 100, 74),
|
||||
(New-Object System.Drawing.Point 100, 182),
|
||||
(New-Object System.Drawing.Point 186, 128)
|
||||
)
|
||||
$g.FillPolygon($play, $points)
|
||||
|
||||
$bg.Dispose()
|
||||
$play.Dispose()
|
||||
$g.Dispose()
|
||||
|
||||
$stream = New-Object System.IO.MemoryStream
|
||||
$bmp.Save($stream, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$png = $stream.ToArray()
|
||||
$stream.Dispose()
|
||||
$bmp.Dispose()
|
||||
|
||||
# ICO 头(22 字节)+ PNG 数据(Vista 起支持 PNG 压缩的 ICO)
|
||||
$file = [System.IO.File]::Create($out)
|
||||
$writer = New-Object System.IO.BinaryWriter($file)
|
||||
$writer.Write([UInt16]0) # reserved
|
||||
$writer.Write([UInt16]1) # type: icon
|
||||
$writer.Write([UInt16]1) # count
|
||||
$writer.Write([Byte]0) # width 256 -> 0
|
||||
$writer.Write([Byte]0) # height 256 -> 0
|
||||
$writer.Write([Byte]0) # palette
|
||||
$writer.Write([Byte]1) # reserved
|
||||
$writer.Write([UInt16]1) # color planes
|
||||
$writer.Write([UInt16]32) # bpp
|
||||
$writer.Write([UInt32]$png.Length) # size
|
||||
$writer.Write([UInt32]22) # offset
|
||||
$writer.Write($png)
|
||||
$writer.Flush()
|
||||
$writer.Dispose()
|
||||
$file.Dispose()
|
||||
|
||||
Write-Host "已生成: $out ($([System.IO.File]::ReadAllBytes($out).Length) 字节)"
|
||||
Loading…
x
Reference in New Issue
Block a user