feat(desktop): 主体切换与登录、主界面及日志留存改造
This commit is contained in:
parent
8aa1973a99
commit
c3cae69e6e
@ -1,9 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
using YuncangTrace.LocalService.Services.Hik;
|
||||
using YuncangTrace.LocalService.Services.Scan;
|
||||
|
||||
namespace YuncangTrace.LocalService;
|
||||
|
||||
@ -22,18 +26,38 @@ public partial class App : Application
|
||||
private SingleInstance? _single;
|
||||
private AppSettings _settings = new();
|
||||
private LocalHttpServer? _server;
|
||||
private HikDeviceService? _hik;
|
||||
private TrayIconService? _tray;
|
||||
private MainWindow? _main;
|
||||
private LoginWindow? _loginWindow;
|
||||
private Session? _session;
|
||||
private ApiClient? _api;
|
||||
private DeviceService? _device;
|
||||
private ScanService? _scan;
|
||||
private IReadOnlyList<ApiSubject> _subjects = Array.Empty<ApiSubject>();
|
||||
private string? _pendingLaunchUrl;
|
||||
private bool _exiting;
|
||||
private bool _trayHintShown;
|
||||
|
||||
/// <summary>NTP 定时校时(运行期间周期性把本机时钟校准到 NTP)</summary>
|
||||
private System.Threading.Timer? _ntpTimer;
|
||||
|
||||
/// <summary>防止启动校时与定时校时重叠</summary>
|
||||
private readonly System.Threading.SemaphoreSlim _ntpGate = new(1, 1);
|
||||
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
base.OnStartup(e);
|
||||
|
||||
// ⓪ 提权校时 helper:NTP 窗口用 runas 拉起的临时进程,只干一次校时后立刻退出。
|
||||
// 必须放在**防多开之前** —— 否则第二个实例会把参数转发给主实例然后自己退出,校时不会发生。
|
||||
if (ElevatedNtp.IsHelperCall(e.Args))
|
||||
{
|
||||
ElevatedNtp.RunHelper(e.Args);
|
||||
Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
// WinForms 控件的视觉样式(否则托盘右键菜单是 Win95 风格)
|
||||
System.Windows.Forms.Application.EnableVisualStyles();
|
||||
|
||||
@ -41,29 +65,69 @@ public partial class App : Application
|
||||
_single = new SingleInstance(AppName, OnSecondInstanceArgs);
|
||||
if (!_single.IsFirstInstance)
|
||||
{
|
||||
_single.SendArgs(e.Args);
|
||||
var forwarded = _single.SendArgs(e.Args);
|
||||
|
||||
// 协议唤起(yuncang://open?code=)转发失败时必须告诉用户,
|
||||
// 否则表现就是“点了没反应”(第一实例是管理员权限时必然发生)。
|
||||
if (!forwarded && e.Args.Any(arg => arg.StartsWith($"{ProtocolHelper.Scheme}://", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
MessageBox.Show(
|
||||
"软件已经在运行,但当前运行的实例是「管理员权限」的,网页无法把运单号传给它。\n\n"
|
||||
+ "请从系统托盘打开软件,或退出后重新启动本软件(新版本会自动改用普通权限运行)。",
|
||||
"云仓视频溯源软件", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
|
||||
Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
_settings = AppSettings.Load();
|
||||
|
||||
// 设备服务已改为 Windows 服务 → 通道/扫码记录跟服务共用 ProgramData 下的文件
|
||||
// (必须在任何 ChannelStore/ScanRecordStore 访问之前设置)
|
||||
AgentPaths.MachineMode = _settings.DeviceServiceEnabled && ServiceInstaller.IsInstalled;
|
||||
if (AgentPaths.MachineMode)
|
||||
{
|
||||
AppLog.Write($"[agent] 服务模式:后台服务 {ServiceInstaller.QueryState()},数据目录 {AgentPaths.MachineRoot}");
|
||||
}
|
||||
|
||||
// 服务模式(设备服务开着):NTP 校时是强制项,不能停用
|
||||
if (_settings.DeviceServiceEnabled) ForceNtpForServiceMode();
|
||||
|
||||
ApplyServerOverride(e.Args);
|
||||
_pendingLaunchUrl = ProtocolHelper.FirstLaunchUrl(e.Args);
|
||||
|
||||
// ② 本机服务先起来(和登录状态无关)
|
||||
_server = new LocalHttpServer(new OrderQueryService());
|
||||
// 海康设备服务:SDK 只在首次真正用到时初始化(找不到 native\HCNetSDK 也不影响其他接口)
|
||||
_hik = new HikDeviceService();
|
||||
// 运单查询要用户令牌 + 当前主体,登录前这两个都还没有 → 用委托现取
|
||||
var queryService = new OrderQueryService(() => _api, () => _settings.SubjectId, () => _session?.Token);
|
||||
_server = new LocalHttpServer(queryService, _hik);
|
||||
_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;
|
||||
|
||||
// 网页查件页的「下载录像」走这里:任何装了本机软件的电脑都能下,存到自己设置的目录
|
||||
_server.PlaybackDownload = new PlaybackDownloadService(
|
||||
queryService,
|
||||
new HikPlaybackService(_hik),
|
||||
() => _api,
|
||||
() => _settings.SubjectId,
|
||||
() => _session?.Token,
|
||||
() => _settings.VideoRootResolved);
|
||||
StartLocalServer();
|
||||
|
||||
// 启动协议永远指向「当前这个 exe」:换目录/从 Debug 换成发布版/重新安装后,
|
||||
// 旧注册表项会指向一个不存在的或依赖开发环境的 exe(网页“启动本机软件”会直接报错)。
|
||||
EnsureProtocolRegistered();
|
||||
|
||||
// NTP 校时:**默认不是管理员**(manifest = asInvoker),所以启动/定时校时只在
|
||||
// 以管理员身份运行时生效;普通启动时点「立即校时」会单独提权(见 ElevatedNtp)。
|
||||
StartNtpSync();
|
||||
|
||||
// 单实例监听要**在登录之前**起来:用户卡在登录窗时被协议唤起,参数也要能进来。
|
||||
_single.StartListening();
|
||||
|
||||
@ -78,10 +142,7 @@ public partial class App : Application
|
||||
AppLog.Write($"本机服务:{_server.BaseUrl}({(_server.IsRunning ? "运行中" : "未启动")})");
|
||||
AppLog.Write($"环境:{BuildInfo.EnvironmentLabel},后端:{_settings.ServerBaseUrl}");
|
||||
|
||||
// ④ 检查更新(**不依赖登录**:令牌失效/未登录时也要能更新;放登录之前)
|
||||
_ = CheckUpdatesAsync();
|
||||
|
||||
// ⑤ 登录 → 主窗口
|
||||
// ④ 登录 → 主窗口
|
||||
if (!ShowLogin())
|
||||
{
|
||||
ExitApplication();
|
||||
@ -89,6 +150,10 @@ public partial class App : Application
|
||||
}
|
||||
|
||||
ShowMainWindow();
|
||||
|
||||
// ⑤ 检查更新(**不依赖登录**状态,但仍要等主窗口起来之后):
|
||||
// 登录窗是 ShowDialog 模态,先查的话更新窗会被它挡在后面 —— 就是「没有提示更新」的典型现象。
|
||||
_ = CheckUpdatesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -112,6 +177,11 @@ public partial class App : Application
|
||||
// 回归测试用:YUNCANG_AUTO_UPDATE=1 时不点按钮直接开始下载
|
||||
AutoStart = Environment.GetEnvironmentVariable("YUNCANG_AUTO_UPDATE") == "1",
|
||||
};
|
||||
|
||||
// 主窗口在显示时才挂 Owner(托盘隐藏状态下挂 Owner,子窗口也会被一起藏掉)
|
||||
if (_main is { IsVisible: true } main) update.Owner = main;
|
||||
else update.Topmost = true;
|
||||
|
||||
var result = update.ShowDialog();
|
||||
AppLog.Write($"更新窗口返回:{result}");
|
||||
if (result == true)
|
||||
@ -208,6 +278,12 @@ public partial class App : Application
|
||||
if (accepted)
|
||||
{
|
||||
_session = login.Session;
|
||||
_subjects = login.Subjects;
|
||||
|
||||
// 登录成功后才建接口客户端与设备/扫码服务(设备服务需要用户的令牌去激活)
|
||||
_api = new ApiClient(_session!.ServerBaseUrl);
|
||||
_device = new DeviceService(_api, _settings, _session);
|
||||
_scan = new ScanService(_device);
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -245,10 +321,38 @@ public partial class App : Application
|
||||
_loginWindow.Focus();
|
||||
}
|
||||
|
||||
/// <summary>退出登录:清令牌 → 关主窗口 → 重新登录(取消则退出程序)</summary>
|
||||
private void OnLogoutRequested()
|
||||
/// <summary>
|
||||
/// 退出登录:服务模式只清登录态(后台服务继续跑);普通模式先关设备服务(令牌作废)
|
||||
/// → 清令牌 → 关主窗口 → 重新登录(取消则退出程序)
|
||||
/// </summary>
|
||||
private async void OnLogoutRequested()
|
||||
{
|
||||
AppLog.Write("已退出登录");
|
||||
|
||||
// 开着设备服务时先告知服务器(令牌立即失效),再去清登录态。
|
||||
// ⚠️ 服务模式下**不能**关设备服务:后台扫码服务要脱离桌面端继续跑,
|
||||
// 这里只清登录态,设备令牌和 agent.json 全部保留。
|
||||
if (!AgentPaths.MachineMode)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_device is not null && _device.Enabled) await _device.DisableAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"退出时关闭设备服务失败:{ex.Message}");
|
||||
}
|
||||
_device?.ResetLocalState();
|
||||
}
|
||||
else
|
||||
{
|
||||
AppLog.Write("[agent] 退出登录:保留后台扫码服务(不注销设备令牌)");
|
||||
_scan?.Stop();
|
||||
}
|
||||
_device = null;
|
||||
_scan = null;
|
||||
_api = null;
|
||||
_subjects = Array.Empty<ApiSubject>();
|
||||
SessionStore.Clear();
|
||||
_session = null;
|
||||
|
||||
@ -274,11 +378,14 @@ public partial class App : Application
|
||||
{
|
||||
var server = _server;
|
||||
var session = _session;
|
||||
if (server is null || session is null) return;
|
||||
var api = _api;
|
||||
if (server is null || session is null || api is null) return;
|
||||
|
||||
if (_main is null)
|
||||
{
|
||||
_main = new MainWindow(server, _settings, session);
|
||||
_device ??= new DeviceService(api, _settings, session);
|
||||
_scan ??= new ScanService(_device);
|
||||
_main = new MainWindow(server, _settings, session, api, _device, _scan, _hik!, _subjects);
|
||||
_main.LogoutRequested += OnLogoutRequested;
|
||||
_main.HiddenToTray += OnHiddenToTray;
|
||||
_main.RestartRequested += RestartApplication;
|
||||
@ -322,6 +429,7 @@ public partial class App : Application
|
||||
/// <summary>
|
||||
/// 托盘菜单「重启软件」:先让本进程退出(释放单实例互斥体与 17300 端口),2 秒后再拉起自己。
|
||||
/// 直接用 Process.Start 会撞上单实例检测(新进程把参数转发给正在退出的旧进程后就没了)。
|
||||
/// 用 explorer 拉起:即使当前是管理员进程,新实例也会是**普通权限**(否则协议唤起会失效)。
|
||||
/// </summary>
|
||||
private void RestartApplication()
|
||||
{
|
||||
@ -334,7 +442,7 @@ public partial class App : Application
|
||||
{
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo("cmd.exe", $"/c timeout /t 2 /nobreak >nul & start \"\" \"{exe}\"")
|
||||
Process.Start(new ProcessStartInfo("cmd.exe", $"/c timeout /t 2 /nobreak >nul & explorer.exe \"{exe}\"")
|
||||
{
|
||||
CreateNoWindow = true,
|
||||
UseShellExecute = false,
|
||||
@ -416,12 +524,142 @@ public partial class App : Application
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启用 NTP 校时:启动时校一次(可关),运行期按间隔定时校(0 = 只启动时)。
|
||||
///
|
||||
/// 为什么需要:扫码时间取本机时钟,回放按录像机时间定位;
|
||||
/// 本机 Windows Time 服务没开时时钟会漂(现场实测慢近 10 秒),面单就会被截到回放窗口外。
|
||||
/// </summary>
|
||||
private void StartNtpSync()
|
||||
{
|
||||
if (!_settings.NtpEnabled)
|
||||
{
|
||||
AppLog.Write("[ntp] NTP 校时已关闭");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ClockSyncService.IsElevated)
|
||||
{
|
||||
AppLog.Write(AgentPaths.MachineMode
|
||||
? "[ntp] 服务模式:自动校时由后台服务负责"
|
||||
: "[ntp] 当前不是管理员权限:跳过启动/定时校时"
|
||||
+ "(在 NTP 窗口点「立即校时」时会单独请求管理员权限)");
|
||||
return;
|
||||
}
|
||||
|
||||
// 服务模式:后台服务(LocalSystem)会按 agent.json 定时校时,本进程不要重复做
|
||||
if (AgentPaths.MachineMode)
|
||||
{
|
||||
AppLog.Write("[ntp] 服务模式:自动校时由后台服务负责");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_settings.NtpSyncOnStartup) _ = SyncClockAsync("启动");
|
||||
|
||||
StartNtpTimer();
|
||||
}
|
||||
|
||||
/// <summary>启动定时校时(幂等;间隔 0 时只在启动/手动校时)</summary>
|
||||
private void StartNtpTimer()
|
||||
{
|
||||
if (_ntpTimer is not null) return;
|
||||
|
||||
var minutes = _settings.NtpSyncIntervalMinutes;
|
||||
if (minutes <= 0)
|
||||
{
|
||||
AppLog.Write("[ntp] 未启用定时校时(间隔 0,只在启动时校时)");
|
||||
return;
|
||||
}
|
||||
|
||||
var interval = TimeSpan.FromMinutes(Math.Max(minutes, 5));
|
||||
_ntpTimer = new System.Threading.Timer(_ => _ = SyncClockAsync("定时"), null, interval, interval);
|
||||
AppLog.Write($"[ntp] 定时校时已启用:每 {interval.TotalMinutes:0} 分钟({_settings.NtpServer})");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务模式强制项:启用 NTP + 启动时校时 + 定时间隔 > 0(不能停用自动校时)。
|
||||
/// </summary>
|
||||
private void ForceNtpForServiceMode()
|
||||
{
|
||||
var changed = false;
|
||||
|
||||
if (!_settings.NtpEnabled) { _settings.NtpEnabled = true; changed = true; }
|
||||
if (!_settings.NtpSyncOnStartup) { _settings.NtpSyncOnStartup = true; changed = true; }
|
||||
if (_settings.NtpSyncIntervalMinutes <= 0) { _settings.NtpSyncIntervalMinutes = 30; changed = true; }
|
||||
|
||||
if (changed)
|
||||
{
|
||||
_settings.Save();
|
||||
AppLog.Write("[ntp] 服务模式:NTP 校时已强制开启(启用 + 启动校时 + 定时校时)");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 供主窗口在「开启设备服务」后调用:强制服务模式 NTP 设置并确保定时校时在跑(幂等)。
|
||||
/// </summary>
|
||||
public void EnsureNtpSync()
|
||||
{
|
||||
ForceNtpForServiceMode();
|
||||
|
||||
if (!_settings.NtpEnabled) return;
|
||||
if (!ClockSyncService.IsElevated)
|
||||
{
|
||||
if (!AgentPaths.MachineMode)
|
||||
{
|
||||
AppLog.Write("[ntp] 服务模式:当前不是管理员权限,自动校时未启动"
|
||||
+ "(在 NTP 窗口点「立即校时」可单独提权校时一次)");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
_ = SyncClockAsync("服务模式");
|
||||
StartNtpTimer();
|
||||
}
|
||||
|
||||
/// <summary>查询 NTP 并校准本机时钟(失败只记日志,不影响其他功能)。</summary>
|
||||
private async Task SyncClockAsync(string reason)
|
||||
{
|
||||
if (!_settings.NtpEnabled) return;
|
||||
if (!await _ntpGate.WaitAsync(0).ConfigureAwait(false)) return;
|
||||
|
||||
try
|
||||
{
|
||||
var result = await ClockSyncService.SyncAsync(_settings.NtpServer).ConfigureAwait(false);
|
||||
|
||||
_settings.NtpLastSyncAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
_settings.NtpLastOffsetSeconds = Math.Round(result.Offset.TotalSeconds, 2);
|
||||
_settings.Save();
|
||||
|
||||
AppLog.Write(result.Offset.Duration() < ClockSyncService.MinimumAdjust
|
||||
? $"[ntp] {reason}校时:{_settings.NtpServer} 偏差 {result.Offset.TotalSeconds:+0.00;-0.00} 秒(已在误差范围内,未调整)"
|
||||
: $"[ntp] {reason}校时完成:{_settings.NtpServer} 偏差 {result.Offset.TotalSeconds:+0.00;-0.00} 秒,往返 {result.RoundTrip.TotalMilliseconds:0} ms");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[ntp] {reason}校时失败({_settings.NtpServer}):{ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_ntpGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>真正退出(托盘菜单 / 登录取消 / 退出登录后取消登录)</summary>
|
||||
private void ExitApplication()
|
||||
{
|
||||
if (_exiting) return;
|
||||
_exiting = true;
|
||||
|
||||
try
|
||||
{
|
||||
_ntpTimer?.Dispose();
|
||||
_ntpTimer = null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 退出路径忽略
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_tray?.Dispose();
|
||||
@ -440,13 +678,24 @@ public partial class App : Application
|
||||
// 退出路径忽略
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_hik?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 退出路径忽略
|
||||
}
|
||||
|
||||
Shutdown();
|
||||
}
|
||||
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
{
|
||||
_ntpTimer?.Dispose();
|
||||
_tray?.Dispose();
|
||||
_server?.Dispose();
|
||||
_hik?.Dispose();
|
||||
_single?.Dispose();
|
||||
base.OnExit(e);
|
||||
}
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="登录 · 云仓视频溯源软件"
|
||||
Height="500" Width="430"
|
||||
Height="580" Width="440"
|
||||
ResizeMode="NoResize"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Background="{StaticResource BgBrush}"
|
||||
@ -14,32 +14,66 @@
|
||||
<TextBlock Text="云仓视频溯源软件" FontSize="18" FontWeight="SemiBold" HorizontalAlignment="Center" />
|
||||
<TextBlock Text="登录后使用本机打印与溯源服务"
|
||||
FontSize="12" Foreground="{StaticResource MutedBrush}"
|
||||
HorizontalAlignment="Center" Margin="0,6,0,18" />
|
||||
HorizontalAlignment="Center" Margin="0,6,0,16" />
|
||||
|
||||
<Grid Margin="0,0,0,4">
|
||||
<TextBlock Text="服务地址" FontSize="12" Foreground="{StaticResource MutedBrush}" />
|
||||
<!-- 开发 / 生产由构建决定(csproj 注入),这里只展示,不让用户选 -->
|
||||
<TextBlock x:Name="EnvText" FontSize="12" Foreground="{StaticResource MutedBrush}"
|
||||
HorizontalAlignment="Right" />
|
||||
<Grid>
|
||||
<!-- ① 账号密码登录 -->
|
||||
<StackPanel x:Name="AccountPanel">
|
||||
<Grid Margin="0,0,0,4">
|
||||
<TextBlock Text="服务地址" FontSize="12" Foreground="{StaticResource MutedBrush}" />
|
||||
<!-- 开发 / 生产由构建决定(csproj 注入),这里只展示,不让用户选 -->
|
||||
<TextBlock x:Name="EnvText" FontSize="12" Foreground="{StaticResource MutedBrush}"
|
||||
HorizontalAlignment="Right" />
|
||||
</Grid>
|
||||
<TextBox x:Name="ServerBox" Padding="6,5" />
|
||||
|
||||
<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" />
|
||||
|
||||
<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="WechatButton" Content="微信扫码登录" Margin="0,8,0,0" Padding="0,6"
|
||||
Background="Transparent" BorderThickness="1" BorderBrush="{StaticResource LineBrush}"
|
||||
Foreground="{StaticResource BrandBrush}" Cursor="Hand" Click="Wechat_Click" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- ② 微信扫码登录 -->
|
||||
<StackPanel x:Name="WechatPanel" Visibility="Collapsed">
|
||||
<Border Background="#F8FAFC" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="8" Padding="12" Height="232">
|
||||
<Grid>
|
||||
<Image x:Name="QrImage" Width="200" Height="200" Stretch="Uniform" />
|
||||
<TextBlock x:Name="QrPlaceholder" Text="正在生成二维码…"
|
||||
Foreground="{StaticResource MutedBrush}" FontSize="12"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<TextBlock x:Name="QrTip" Text="请用手机扫码,确认后自动登录"
|
||||
FontSize="12" Foreground="{StaticResource MutedBrush}"
|
||||
TextWrapping="Wrap" HorizontalAlignment="Center" Margin="0,12,0,0" />
|
||||
|
||||
<Button x:Name="WechatRefreshButton" Content="刷新二维码" Margin="0,12,0,0" Padding="0,6"
|
||||
Background="Transparent" BorderThickness="1" BorderBrush="{StaticResource LineBrush}"
|
||||
Cursor="Hand" Click="WechatRefresh_Click" />
|
||||
|
||||
<Button x:Name="BackButton" Content="返回账号登录" Margin="0,8,0,0" Padding="0,6"
|
||||
Background="Transparent" BorderThickness="0" Foreground="{StaticResource MutedBrush}"
|
||||
Cursor="Hand" Click="Back_Click" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<TextBox x:Name="ServerBox" Padding="6,5" />
|
||||
|
||||
<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"
|
||||
<Button x:Name="ExitButton" Content="退出" Margin="0,10,0,0" Padding="0,6"
|
||||
Background="Transparent" BorderThickness="0" Foreground="{StaticResource MutedBrush}"
|
||||
Cursor="Hand" Click="Exit_Click" />
|
||||
</StackPanel>
|
||||
|
||||
@ -1,7 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media.Imaging;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
|
||||
namespace YuncangTrace.LocalService;
|
||||
@ -9,7 +13,9 @@ namespace YuncangTrace.LocalService;
|
||||
/// <summary>
|
||||
/// 登录窗
|
||||
///
|
||||
/// - 服务器地址 / 账号 / 密码 → `POST /api/web/auth/login` 拿 user JWT;
|
||||
/// - 账号密码登录:`POST /api/web/auth/login` 拿 user JWT(顺带下发主体列表);
|
||||
/// - **微信扫码登录**:`GET /api/wechat/login` 发码 → 显示二维码(GIF,WPF 可直接显示)→ 长轮询
|
||||
/// `GET /api/wechat/login?code=&wait=25`,手机确认后直接拿到令牌;
|
||||
/// - 本地已有令牌时,先调 `GET /api/web/me` 验证,还有效就直接跳过登录(窗口一闪而过);
|
||||
/// - 成功后把令牌存到 `%LOCALAPPDATA%\YuncangTrace\session.json`。
|
||||
/// </summary>
|
||||
@ -19,12 +25,18 @@ public partial class LoginWindow : Window
|
||||
private readonly Session? _saved;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>微信扫码的长轮询取消源(离开扫码面板 / 关窗口时取消)</summary>
|
||||
private CancellationTokenSource? _wechatCts;
|
||||
|
||||
/// <summary>登录成功后的会话(ShowDialog 返回 true 时可用)</summary>
|
||||
public Session? Session { get; private set; }
|
||||
|
||||
/// <summary>登录用户</summary>
|
||||
public ApiUser? User { get; private set; }
|
||||
|
||||
/// <summary>登录时后端下发的主体列表</summary>
|
||||
public IReadOnlyList<ApiSubject> Subjects { get; private set; } = Array.Empty<ApiSubject>();
|
||||
|
||||
public LoginWindow(AppSettings settings, Session? saved)
|
||||
{
|
||||
InitializeComponent();
|
||||
@ -41,6 +53,7 @@ public partial class LoginWindow : Window
|
||||
ServerBox.ToolTip = $"留空即使用{BuildInfo.EnvironmentLabel}默认地址:{BuildInfo.DefaultServer}\n启动时可用 --server=http://x.x.x.x:7300 临时指定";
|
||||
|
||||
Loaded += OnLoaded;
|
||||
Closed += (_, _) => StopWechatPolling();
|
||||
}
|
||||
|
||||
private async void OnLoaded(object sender, RoutedEventArgs e)
|
||||
@ -75,7 +88,8 @@ public partial class LoginWindow : Window
|
||||
|
||||
Session = _saved;
|
||||
User = me;
|
||||
AppLog.Write($"已恢复登录:{me.DisplayName}");
|
||||
Subjects = await LoadSubjectsSafeAsync(api, _saved.Token);
|
||||
AppLog.Write($"已恢复登录:{me.DisplayName}(主体 {Subjects.Count} 个)");
|
||||
DialogResult = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -86,6 +100,8 @@ public partial class LoginWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 账号密码登录 ----------------
|
||||
|
||||
private void Login_Click(object sender, RoutedEventArgs e) => _ = DoLoginAsync();
|
||||
|
||||
private void PasswordBox_KeyDown(object sender, KeyEventArgs e)
|
||||
@ -120,20 +136,21 @@ public partial class LoginWindow : Window
|
||||
try
|
||||
{
|
||||
var api = new ApiClient(server);
|
||||
var (session, user) = await api.LoginAsync(account, password);
|
||||
var result = await api.LoginAsync(account, password);
|
||||
|
||||
session.DisplayName = user.DisplayName;
|
||||
SessionStore.Save(session);
|
||||
result.Session.DisplayName = result.User.DisplayName;
|
||||
SessionStore.Save(result.Session);
|
||||
|
||||
_settings.ServerBaseUrl = server;
|
||||
_settings.RememberAccount = RememberBox.IsChecked == true;
|
||||
_settings.LastAccount = _settings.RememberAccount ? account : string.Empty;
|
||||
_settings.Save();
|
||||
|
||||
Session = session;
|
||||
User = user;
|
||||
Session = result.Session;
|
||||
User = result.User;
|
||||
Subjects = result.Subjects;
|
||||
|
||||
AppLog.Write($"登录成功:{user.DisplayName}({server})");
|
||||
AppLog.Write($"登录成功:{result.User.DisplayName}({server},主体 {Subjects.Count} 个)");
|
||||
DialogResult = true;
|
||||
}
|
||||
catch (ApiException ex)
|
||||
@ -150,11 +167,182 @@ public partial class LoginWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 微信扫码登录 ----------------
|
||||
|
||||
private void Wechat_Click(object sender, RoutedEventArgs e) => _ = EnterWechatAsync();
|
||||
|
||||
private void WechatRefresh_Click(object sender, RoutedEventArgs e) => _ = StartWechatTicketAsync();
|
||||
|
||||
private void Back_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
StopWechatPolling();
|
||||
WechatPanel.Visibility = Visibility.Collapsed;
|
||||
AccountPanel.Visibility = Visibility.Visible;
|
||||
ClearError();
|
||||
AccountBox.Focus();
|
||||
}
|
||||
|
||||
private async Task EnterWechatAsync()
|
||||
{
|
||||
ClearError();
|
||||
AccountPanel.Visibility = Visibility.Collapsed;
|
||||
WechatPanel.Visibility = Visibility.Visible;
|
||||
await StartWechatTicketAsync();
|
||||
}
|
||||
|
||||
private async Task StartWechatTicketAsync()
|
||||
{
|
||||
StopWechatPolling();
|
||||
var cts = new CancellationTokenSource();
|
||||
_wechatCts = cts;
|
||||
|
||||
QrImage.Source = null;
|
||||
QrPlaceholder.Visibility = Visibility.Visible;
|
||||
QrPlaceholder.Text = "正在生成二维码…";
|
||||
QrTip.Text = "请用手机扫码,确认后自动登录";
|
||||
|
||||
try
|
||||
{
|
||||
var api = new ApiClient(AppSettings.Normalize(ServerBox.Text));
|
||||
var ticket = await api.StartWechatLoginAsync(cts.Token);
|
||||
|
||||
// WPF 不能渲染 SVG,这里拿同一张二维码的 GIF
|
||||
var bytes = await api.GetImageAsync(
|
||||
$"/api/wechat/qrcode.gif?code={Uri.EscapeDataString(ticket.Code)}", cts.Token);
|
||||
|
||||
QrImage.Source = ToBitmap(bytes);
|
||||
QrPlaceholder.Visibility = Visibility.Collapsed;
|
||||
QrTip.Text = "请用手机微信扫码,确认后自动登录";
|
||||
|
||||
AppLog.Write($"[wechat] 已生成登录二维码:{ticket.Code}");
|
||||
_ = PollWechatAsync(api, ticket.Code, cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// 切回账号登录,忽略
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
QrPlaceholder.Text = "二维码生成失败";
|
||||
ShowError($"微信登录不可用:{ex.Message}");
|
||||
AppLog.Write($"[wechat] 生成二维码失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>长轮询:确认了就登录;码过期(refreshed)就换一张继续等</summary>
|
||||
private async Task PollWechatAsync(ApiClient api, string code, CancellationToken ct)
|
||||
{
|
||||
var current = code;
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await api.PollWechatLoginAsync(current, 25, ct);
|
||||
|
||||
if (result.Status == "confirmed" && result.Session is not null)
|
||||
{
|
||||
var session = result.Session;
|
||||
session.DisplayName = result.User?.DisplayName ?? session.DisplayName;
|
||||
SessionStore.Save(session);
|
||||
|
||||
_settings.ServerBaseUrl = api.BaseUrl;
|
||||
_settings.Save();
|
||||
|
||||
Session = session;
|
||||
User = result.User;
|
||||
Subjects = await LoadSubjectsSafeAsync(api, session.Token);
|
||||
|
||||
AppLog.Write($"[wechat] 扫码登录成功:{session.DisplayName}(主体 {Subjects.Count} 个)");
|
||||
|
||||
if (!ct.IsCancellationRequested) DialogResult = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.Status == "refreshed" && !string.IsNullOrWhiteSpace(result.Code))
|
||||
{
|
||||
current = result.Code!;
|
||||
try
|
||||
{
|
||||
var bytes = await api.GetImageAsync(
|
||||
$"/api/wechat/qrcode.gif?code={Uri.EscapeDataString(current)}", ct);
|
||||
QrImage.Source = ToBitmap(bytes);
|
||||
QrTip.Text = "二维码已刷新,请重新扫码";
|
||||
}
|
||||
catch
|
||||
{
|
||||
QrTip.Text = "二维码刷新失败,可点「刷新二维码」重试";
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
QrTip.Text = $"连接中断,正在重试…({ex.Message})";
|
||||
try
|
||||
{
|
||||
await Task.Delay(1200, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void StopWechatPolling()
|
||||
{
|
||||
try
|
||||
{
|
||||
_wechatCts?.Cancel();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 忽略
|
||||
}
|
||||
_wechatCts = null;
|
||||
}
|
||||
|
||||
/// <summary>拿主体列表;失败不阻塞登录(主界面里还能再拉)</summary>
|
||||
private static async Task<IReadOnlyList<ApiSubject>> LoadSubjectsSafeAsync(ApiClient api, string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await api.SubjectsAsync(token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"读取主体列表失败:{ex.Message}");
|
||||
return Array.Empty<ApiSubject>();
|
||||
}
|
||||
}
|
||||
|
||||
private static BitmapImage? ToBitmap(byte[] bytes)
|
||||
{
|
||||
if (bytes.Length == 0) return null;
|
||||
|
||||
using var stream = new MemoryStream(bytes);
|
||||
var image = new BitmapImage();
|
||||
image.BeginInit();
|
||||
image.CacheOption = BitmapCacheOption.OnLoad;
|
||||
image.StreamSource = stream;
|
||||
image.EndInit();
|
||||
image.Freeze();
|
||||
return image;
|
||||
}
|
||||
|
||||
// ---------------- 状态 ----------------
|
||||
|
||||
private void SetBusy(bool busy, string? text = null)
|
||||
{
|
||||
_busy = busy;
|
||||
|
||||
LoginButton.IsEnabled = !busy;
|
||||
WechatButton.IsEnabled = !busy;
|
||||
ExitButton.IsEnabled = !busy;
|
||||
ServerBox.IsEnabled = !busy;
|
||||
AccountBox.IsEnabled = !busy;
|
||||
@ -176,5 +364,9 @@ public partial class LoginWindow : Window
|
||||
ErrorText.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
|
||||
private void Exit_Click(object sender, RoutedEventArgs e) => DialogResult = false;
|
||||
private void Exit_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
StopWechatPolling();
|
||||
DialogResult = false;
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="云仓视频溯源软件(本机服务)"
|
||||
Height="460" Width="780"
|
||||
MinHeight="400" MinWidth="680"
|
||||
Height="620" Width="920"
|
||||
MinHeight="520" MinWidth="760"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Background="{StaticResource BgBrush}"
|
||||
FontFamily="Microsoft YaHei UI, Segoe UI"
|
||||
@ -18,6 +18,8 @@
|
||||
<!-- 菜单 -->
|
||||
<Menu Grid.Row="0" Padding="10,3,0,3" Background="Transparent" BorderThickness="0">
|
||||
<MenuItem Header="工具(_T)">
|
||||
<MenuItem Header="打开配置页(后台)" Click="OpenConsole_Click" />
|
||||
<Separator />
|
||||
<MenuItem Header="测试查询" Click="FocusQuery_Click" />
|
||||
<Separator />
|
||||
<MenuItem Header="打开日志目录" Click="OpenLogFolder_Click" />
|
||||
@ -28,7 +30,32 @@
|
||||
<MenuItem Header="重启软件" Click="Restart_Click" />
|
||||
</MenuItem>
|
||||
|
||||
<!-- 设置:本机相关配置(录像存储路径) -->
|
||||
<MenuItem Header="设置(_O)">
|
||||
<MenuItem Header="录像存储路径…" Click="SettingsVideoPath_Click" />
|
||||
<MenuItem x:Name="MenuVideoPath" Header="录像目录" IsEnabled="False" />
|
||||
<MenuItem Header="打开录像目录" Click="OpenVideoFolder_Click" />
|
||||
</MenuItem>
|
||||
|
||||
<!-- 服务:主体切换 + 设备服务(默认关闭,只有主体管理员可见「开启设备服务」) -->
|
||||
<MenuItem Header="服务(_S)">
|
||||
<MenuItem x:Name="MenuSubject" Header="当前主体" Click="SwitchSubject_Click" />
|
||||
<Separator />
|
||||
<MenuItem x:Name="MenuEnableDevice" Header="开启设备服务" Click="EnableDevice_Click" />
|
||||
<MenuItem x:Name="MenuDisableDevice" Header="关闭设备服务" Click="DisableDevice_Click"
|
||||
Visibility="Collapsed" />
|
||||
<Separator />
|
||||
<!-- 服务模式下才有意义:设备服务开着才显示 -->
|
||||
<MenuItem x:Name="MenuNtp" Header="NTP 校时…" Click="SettingsNtp_Click"
|
||||
Visibility="Collapsed" />
|
||||
<MenuItem x:Name="MenuNtpStatus" Header="NTP 校时:未启用" IsEnabled="False"
|
||||
Visibility="Collapsed" />
|
||||
<Separator />
|
||||
<MenuItem x:Name="MenuRefreshToken" Header="立即续期设备令牌" Click="RefreshDeviceToken_Click"
|
||||
Visibility="Collapsed" />
|
||||
<MenuItem x:Name="MenuTokenStatus" Header="设备令牌:—" IsEnabled="False"
|
||||
Visibility="Collapsed" />
|
||||
<Separator />
|
||||
<MenuItem x:Name="MenuServiceStatus" Header="服务状态" IsEnabled="False" />
|
||||
</MenuItem>
|
||||
|
||||
@ -45,34 +72,74 @@
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- ① 当前登录用户(运行状态在菜单「服务 → 服务状态」里看) -->
|
||||
<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,0,0,12">
|
||||
<TextBlock x:Name="UserText" Text="未登录" Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<Button Content="退出登录" Padding="10,4" Click="Logout_Click" />
|
||||
</StackPanel>
|
||||
<!-- ① 当前主体 / 设备服务 / 登录用户 -->
|
||||
<DockPanel Grid.Row="0" LastChildFill="False" Margin="0,0,0,10">
|
||||
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
|
||||
<TextBlock x:Name="UserText" Text="未登录" Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<Button Content="退出登录" Padding="10,4" Click="Logout_Click" />
|
||||
</StackPanel>
|
||||
<TextBlock x:Name="ContextText" Text="主体:未选择 · 设备服务:未开启"
|
||||
Foreground="{StaticResource MutedBrush}" FontSize="12"
|
||||
VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
|
||||
</DockPanel>
|
||||
|
||||
<!-- ② 查询测试(占满剩余高度;日志只写文件,界面上不再展示) -->
|
||||
<Border Grid.Row="1" Background="White" BorderBrush="{StaticResource LineBrush}"
|
||||
BorderThickness="1" CornerRadius="8" Padding="12,10">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<DockPanel Grid.Row="0" Margin="0,0,0,10">
|
||||
<Button DockPanel.Dock="Right" Content="查询" Padding="16,5" Margin="8,0,0,0" Click="Query_Click" />
|
||||
<TextBlock Text="测试查询" Foreground="{StaticResource MutedBrush}" VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<TextBox x:Name="QueryBox" Padding="6,3" VerticalContentAlignment="Center"
|
||||
ToolTip="输入运单号后回车" KeyDown="QueryBox_KeyDown" />
|
||||
</DockPanel>
|
||||
<TextBox Grid.Row="1" x:Name="ResultBox" IsReadOnly="True"
|
||||
AcceptsReturn="True" AcceptsTab="True" TextWrapping="NoWrap"
|
||||
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"
|
||||
FontFamily="Consolas, Microsoft YaHei UI" FontSize="12" Padding="8"
|
||||
Background="#F9FAFB" BorderBrush="{StaticResource LineBrush}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<!-- ② 页签:打包查询 / 扫码通道(开启扫码服务后才出现) -->
|
||||
<TabControl Grid.Row="1" x:Name="MainTabs" Background="Transparent" BorderThickness="0" Padding="0">
|
||||
<TabItem x:Name="QueryTab" Header="打包查询">
|
||||
<Border Background="White" BorderBrush="{StaticResource LineBrush}"
|
||||
BorderThickness="1" CornerRadius="8" Padding="12,10" Margin="0,8,0,0">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<DockPanel Grid.Row="0" Margin="0,0,0,10">
|
||||
<Button DockPanel.Dock="Right" Content="查询" Padding="16,5" Margin="8,0,0,0"
|
||||
Click="Query_Click" />
|
||||
<Button DockPanel.Dock="Right" x:Name="DownloadButton" Content="下载录像…"
|
||||
Padding="12,5" Margin="8,0,0,0" IsEnabled="False" Click="Download_Click"
|
||||
Visibility="Collapsed"
|
||||
ToolTip="按工作台布局逐路下载这段时间的录像到本地目录(校验有录像后才显示)" />
|
||||
<Button DockPanel.Dock="Right" x:Name="PreviewButton" Content="预览回放"
|
||||
Padding="12,5" Margin="8,0,0,0" IsEnabled="False" Click="Preview_Click"
|
||||
Visibility="Collapsed"
|
||||
ToolTip="按工作台画布布局,多路同时播放这段时间的录像(校验有录像后才显示)" />
|
||||
<TextBlock Text="运单号" Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<TextBox x:Name="QueryBox" Padding="6,3" VerticalContentAlignment="Center"
|
||||
ToolTip="输入运单号后回车(开启设备服务后会自动上报);扫码会自动查询本页,但不跳页"
|
||||
KeyDown="QueryBox_KeyDown" />
|
||||
</DockPanel>
|
||||
<TextBox Grid.Row="1" x:Name="ResultBox" IsReadOnly="True"
|
||||
AcceptsReturn="True" AcceptsTab="True" TextWrapping="NoWrap"
|
||||
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"
|
||||
FontFamily="Consolas, Microsoft YaHei UI" FontSize="12" Padding="8"
|
||||
Background="#F9FAFB" BorderBrush="{StaticResource LineBrush}" />
|
||||
<Border Grid.Row="1" x:Name="PlaybackPanel" VerticalAlignment="Bottom" Visibility="Collapsed"
|
||||
Background="#FFFDF5" BorderBrush="#F0E0B0" BorderThickness="1" CornerRadius="6"
|
||||
Padding="8,6" Margin="0,0,0,0">
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Right" Content="关闭" Padding="10,2" VerticalAlignment="Top"
|
||||
Click="HidePlayback_Click" />
|
||||
<Button DockPanel.Dock="Right" x:Name="OpenFolderButton" Content="打开目录"
|
||||
Padding="10,2" Margin="0,0,6,0" VerticalAlignment="Top"
|
||||
Visibility="Collapsed" Click="OpenOutputFolder_Click" />
|
||||
<TextBlock x:Name="PlaybackText" TextWrapping="Wrap" FontSize="12" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
</TabItem>
|
||||
|
||||
<TabItem x:Name="ScanTab" Header="扫码通道" Visibility="Collapsed">
|
||||
<ContentControl x:Name="ScanTabHost" />
|
||||
</TabItem>
|
||||
|
||||
<TabItem x:Name="RecordsTab" Header="扫码记录" Visibility="Collapsed">
|
||||
<ContentControl x:Name="RecordsTabHost" />
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
@ -30,10 +31,61 @@ public sealed record ApiUser(int Id, string? Username, string? Nickname)
|
||||
: $"#{Id}";
|
||||
}
|
||||
|
||||
/// <summary>主体(租户)</summary>
|
||||
public sealed record ApiSubject(int Id, string Name, string? ExpireAt, bool Expired, int Role, int MemberCount, string? MemberName)
|
||||
{
|
||||
/// <summary>1 = 管理员(只有管理员能看到 / 使用「开启设备服务」)</summary>
|
||||
public bool IsAdmin => Role == 1;
|
||||
|
||||
/// <summary>下拉/列表里的显示文案</summary>
|
||||
public string Display => Expired ? $"{Name}(已到期)" : Name;
|
||||
}
|
||||
|
||||
/// <summary>登录结果:会话 + 用户 + 可进入的主体列表(后端登录接口一起下发)</summary>
|
||||
public sealed record LoginResult(Session Session, ApiUser User, IReadOnlyList<ApiSubject> Subjects);
|
||||
|
||||
/// <summary>微信扫码登录:发码结果</summary>
|
||||
public sealed record WechatTicket(string Code, string QrUrl);
|
||||
|
||||
/// <summary>微信扫码登录:轮询结果</summary>
|
||||
public sealed record WechatPollResult(string Status, Session? Session, ApiUser? User, string? Code, string? QrUrl, IReadOnlyList<ApiSubject> Subjects);
|
||||
|
||||
/// <summary>本机设备(scanners 表的一行,够桌面端展示用)</summary>
|
||||
public sealed record ApiDevice(int Id, string Sn, string? Name, string? LastSeenAt);
|
||||
|
||||
/// <summary>录像机登录凭据(**含明文密码**,只在内存里用,别落盘/别打日志)</summary>
|
||||
public sealed record NvrCredential(int Id, string Name, string Host, int Port, string Username, string Password);
|
||||
|
||||
/// <summary>录像机(列表用,不含密码)</summary>
|
||||
public sealed record ApiNvr(int Id, string Name, string Host, int Port, string? SerialNumber);
|
||||
|
||||
/// <summary>激活设备服务的结果</summary>
|
||||
public sealed record DeviceActivation(
|
||||
int Id,
|
||||
string Sn,
|
||||
string? Name,
|
||||
string Token,
|
||||
string TokenType,
|
||||
string? ExpiresIn,
|
||||
bool FirstTime,
|
||||
IReadOnlyList<ApiDevice> Kicked,
|
||||
string RefreshToken,
|
||||
string? RefreshExpiresIn);
|
||||
|
||||
/// <summary>刷新设备令牌的结果</summary>
|
||||
public sealed record DeviceTokenRefresh(
|
||||
string Sn,
|
||||
string Token,
|
||||
string TokenType,
|
||||
string? ExpiresIn,
|
||||
string RefreshToken,
|
||||
string? RefreshExpiresIn);
|
||||
|
||||
/// <summary>
|
||||
/// 后端接口客户端(只用到登录 + 校验令牌,够桌面端跑起来)
|
||||
/// 后端接口客户端(登录 / 主体 / 设备服务 / 上报)
|
||||
///
|
||||
/// 契约见 frontend/README:成功 `{ ok:true, data }`,失败 `{ ok:false, message }`。
|
||||
/// 契约见 backend/README:成功 `{ ok:true, data }`,失败 `{ ok:false, message }`。
|
||||
/// 业务接口除了 `Authorization` 还要带 `X-Subject-Id`(主体范围)。
|
||||
/// </summary>
|
||||
public sealed class ApiClient
|
||||
{
|
||||
@ -52,12 +104,11 @@ public sealed class ApiClient
|
||||
/// <summary>后端根地址(已去掉末尾斜杠)</summary>
|
||||
public string BaseUrl { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 账号密码登录(`POST /api/web/auth/login`)
|
||||
/// </summary>
|
||||
// ==================== 登录 ====================
|
||||
|
||||
/// <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)
|
||||
public async Task<LoginResult> LoginAsync(string account, string password, CancellationToken ct = default)
|
||||
{
|
||||
var body = JsonSerializer.Serialize(new { account, password }, Json);
|
||||
|
||||
@ -68,14 +119,11 @@ public sealed class ApiClient
|
||||
|
||||
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);
|
||||
}
|
||||
if (data is null) throw new ApiException(message, (int)response.StatusCode);
|
||||
|
||||
var token = GetString(data.Value, "token")
|
||||
?? throw new ApiException("登录返回里没有令牌");
|
||||
var token = GetString(data.Value, "token") ?? throw new ApiException("登录返回里没有令牌");
|
||||
var user = ReadUser(data.Value);
|
||||
var subjects = ReadSubjects(data.Value, "subjects");
|
||||
|
||||
var session = new Session
|
||||
{
|
||||
@ -84,14 +132,73 @@ public sealed class ApiClient
|
||||
DisplayName = user.DisplayName,
|
||||
ServerBaseUrl = BaseUrl,
|
||||
};
|
||||
return (session, user);
|
||||
return new LoginResult(session, user, subjects);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 校验令牌是否还有效(`GET /api/web/me`)。
|
||||
/// </summary>
|
||||
/// <summary>微信扫码登录:发一个码(`GET /api/wechat/login`,无需令牌)</summary>
|
||||
public async Task<WechatTicket> StartWechatLoginAsync(CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendAsync(
|
||||
() => new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/api/wechat/login"),
|
||||
"生成登录二维码", 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 code = GetString(data.Value, "code") ?? throw new ApiException("没有拿到登录码");
|
||||
var qrUrl = GetString(data.Value, "qrUrl") ?? $"/api/wechat/qrcode.svg?code={code}";
|
||||
return new WechatTicket(code, qrUrl);
|
||||
}
|
||||
|
||||
/// <summary>微信扫码登录:轮询一次(`GET /api/wechat/login?code=&wait=`)</summary>
|
||||
public async Task<WechatPollResult> PollWechatLoginAsync(string code, int waitSeconds, CancellationToken ct = default)
|
||||
{
|
||||
var url = $"{BaseUrl}/api/wechat/login?code={Uri.EscapeDataString(code)}&wait={waitSeconds}";
|
||||
using var response = await SendAsync(
|
||||
() => new HttpRequestMessage(HttpMethod.Get, url), "等待扫码", 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 status = GetString(data.Value, "status") ?? "pending";
|
||||
if (status != "confirmed")
|
||||
{
|
||||
return new WechatPollResult(status, null, null, GetString(data.Value, "code"), GetString(data.Value, "qrUrl"),
|
||||
Array.Empty<ApiSubject>());
|
||||
}
|
||||
|
||||
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 new WechatPollResult(status, session, user, null, null, Array.Empty<ApiSubject>());
|
||||
}
|
||||
|
||||
/// <summary>拉图片字节(二维码用;`qrcode.gif` 返回 GIF,WPF 能直接显示)</summary>
|
||||
public async Task<byte[]> GetImageAsync(string urlOrPath, CancellationToken ct = default)
|
||||
{
|
||||
var url = urlOrPath.StartsWith("http", StringComparison.OrdinalIgnoreCase)
|
||||
? urlOrPath
|
||||
: $"{BaseUrl}{urlOrPath}";
|
||||
|
||||
using var response = await SendAsync(() => new HttpRequestMessage(HttpMethod.Get, url), "下载二维码", ct)
|
||||
.ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new ApiException($"二维码下载失败(HTTP {(int)response.StatusCode})", (int)response.StatusCode);
|
||||
}
|
||||
return await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>校验令牌是否还有效(`GET /api/web/me`)</summary>
|
||||
/// <returns>令牌有效返回用户;**401/403 返回 null**(真失效,调用方可以清掉本地令牌)</returns>
|
||||
/// <exception cref="ApiException">网络不通 / 超时 / 服务端 5xx —— 不能当成“登录失效”,否则会误删令牌</exception>
|
||||
public async Task<ApiUser?> MeAsync(string token, CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendAsync(() =>
|
||||
@ -101,17 +208,10 @@ public sealed class ApiClient
|
||||
return request;
|
||||
}, "校验登录态", ct).ConfigureAwait(false);
|
||||
|
||||
// 只有 401/403 才是「令牌真失效」;5xx / 网关错误不应该让客户端把登录态抹掉
|
||||
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) return null;
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new ApiException(
|
||||
$"校验登录态失败(HTTP {(int)response.StatusCode})",
|
||||
(int)response.StatusCode);
|
||||
throw new ApiException($"校验登录态失败(HTTP {(int)response.StatusCode})", (int)response.StatusCode);
|
||||
}
|
||||
|
||||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
@ -119,6 +219,326 @@ public sealed class ApiClient
|
||||
return data is null ? null : ReadUser(data.Value);
|
||||
}
|
||||
|
||||
// ==================== 主体 ====================
|
||||
|
||||
/// <summary>我可进入的主体列表(`GET /api/web/subjects`)</summary>
|
||||
public async Task<IReadOnlyList<ApiSubject>> SubjectsAsync(string token, CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendAuthorizedAsync(HttpMethod.Get, "/api/web/subjects", token, 0, null, "读取主体", 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);
|
||||
return ReadSubjects(data.Value, "list");
|
||||
}
|
||||
|
||||
// ==================== 设备服务(本机作为扫码中控) ====================
|
||||
|
||||
/// <summary>本主体已绑定的设备(开启前检查用;`GET /api/web/devices/active`)</summary>
|
||||
public async Task<IReadOnlyList<ApiDevice>> DevicesAsync(string token, int subjectId, CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendAuthorizedAsync(HttpMethod.Get, "/api/web/devices/active", token, subjectId, null,
|
||||
"读取设备", 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 devices = new List<ApiDevice>();
|
||||
if (data.Value.TryGetProperty("list", out var list) && list.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var item in list.EnumerateArray())
|
||||
{
|
||||
devices.Add(new ApiDevice(
|
||||
GetInt(item, "id"),
|
||||
GetString(item, "sn") ?? string.Empty,
|
||||
GetString(item, "name"),
|
||||
GetString(item, "lastSeenAt")));
|
||||
}
|
||||
}
|
||||
return devices;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开启设备服务(`POST /api/web/devices/activate`,**仅主体管理员**)
|
||||
///
|
||||
/// 服务端保证「一个主体只有一台设备在线」:同主体其他设备的令牌会被作废(踢下线)。
|
||||
/// </summary>
|
||||
public async Task<DeviceActivation> ActivateDeviceAsync(
|
||||
string token, int subjectId, string sn, string name, CancellationToken ct = default)
|
||||
{
|
||||
var payload = JsonSerializer.Serialize(new { sn, name }, Json);
|
||||
using var response = await SendAuthorizedAsync(HttpMethod.Post, "/api/web/devices/activate", token, subjectId,
|
||||
payload, "开启设备服务", 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 kicked = new List<ApiDevice>();
|
||||
if (data.Value.TryGetProperty("kicked", out var kickedElement) && kickedElement.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var item in kickedElement.EnumerateArray())
|
||||
{
|
||||
kicked.Add(new ApiDevice(GetInt(item, "id"), GetString(item, "sn") ?? string.Empty,
|
||||
GetString(item, "name"), null));
|
||||
}
|
||||
}
|
||||
|
||||
return new DeviceActivation(
|
||||
GetInt(data.Value, "id"),
|
||||
GetString(data.Value, "sn") ?? sn,
|
||||
GetString(data.Value, "name"),
|
||||
GetString(data.Value, "token") ?? throw new ApiException("开启成功但没拿到设备令牌"),
|
||||
GetString(data.Value, "tokenType") ?? "Bearer",
|
||||
GetString(data.Value, "expiresIn"),
|
||||
data.Value.TryGetProperty("firstTime", out var first) && first.ValueKind == JsonValueKind.True,
|
||||
kicked,
|
||||
GetString(data.Value, "refreshToken") ?? string.Empty,
|
||||
GetString(data.Value, "refreshExpiresIn"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用刷新令牌换新的设备访问令牌(`POST /api/device/refresh`,无需用户登录)
|
||||
///
|
||||
/// 后台服务在访问令牌快到期/已 401 时调用;成功后**刷新令牌也会轮换**,必须覆盖保存。
|
||||
/// </summary>
|
||||
public async Task<DeviceTokenRefresh> RefreshDeviceTokenAsync(string sn, string refreshToken,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var payload = JsonSerializer.Serialize(new { sn, refreshToken }, Json);
|
||||
using var response = await SendAsync(() =>
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/api/device/refresh");
|
||||
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
|
||||
return request;
|
||||
}, "刷新设备令牌", 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);
|
||||
|
||||
return new DeviceTokenRefresh(
|
||||
GetString(data.Value, "sn") ?? sn,
|
||||
GetString(data.Value, "token") ?? throw new ApiException("刷新成功但没拿到设备令牌"),
|
||||
GetString(data.Value, "tokenType") ?? "Bearer",
|
||||
GetString(data.Value, "expiresIn"),
|
||||
GetString(data.Value, "refreshToken") ?? string.Empty,
|
||||
GetString(data.Value, "refreshExpiresIn"));
|
||||
}
|
||||
|
||||
/// <summary>关闭设备服务(`POST /api/web/devices/:id/logout` → 令牌作废)</summary>
|
||||
public async Task DeactivateDeviceAsync(string token, int subjectId, int deviceId, CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendAuthorizedAsync(HttpMethod.Post, $"/api/web/devices/{deviceId}/logout", token,
|
||||
subjectId, "{}", "关闭设备服务", 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);
|
||||
}
|
||||
|
||||
/// <summary>设备心跳(`POST /api/scanner/heartbeat`):刷新服务端 `last_seen_at`</summary>
|
||||
public async Task HeartbeatAsync(string deviceToken, CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendDeviceAsync("/api/scanner/heartbeat", deviceToken, "{}", "设备心跳", 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);
|
||||
}
|
||||
|
||||
/// <summary>上报通道(设备令牌;`POST /api/scan/channels`)</summary>
|
||||
public async Task ReportChannelsAsync(string deviceToken, IEnumerable<(string ChannelId, string ChannelName)> channels,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var rows = new List<object>();
|
||||
foreach (var (id, name) in channels) rows.Add(new { channelId = id, channelName = name });
|
||||
|
||||
var payload = JsonSerializer.Serialize(new { channels = rows }, Json);
|
||||
using var response = await SendDeviceAsync("/api/scan/channels", deviceToken, payload, "上报通道", 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);
|
||||
}
|
||||
|
||||
/// <summary>上报一条扫码记录(设备令牌;`POST /api/scan/records`,服务端按 设备+通道+条码+秒 去重)</summary>
|
||||
public Task ReportRecordAsync(string deviceToken, string channelId, string barcode, DateTime scanTime,
|
||||
CancellationToken ct = default)
|
||||
=> ReportRecordsAsync(deviceToken, new[] { (channelId, barcode, scanTime) }, ct);
|
||||
|
||||
/// <summary>
|
||||
/// 批量上报扫码记录(设备令牌;`POST /api/scan/records`)。
|
||||
///
|
||||
/// 服务端按 **设备 + 通道 + 条码 + 扫描时间(秒)** 去重,重复上报只入库一次、不报错,
|
||||
/// 所以断网重试时可以“整批重发”,不用担心重复落库。
|
||||
/// </summary>
|
||||
public async Task ReportRecordsAsync(string deviceToken,
|
||||
IEnumerable<(string ChannelId, string Barcode, DateTime ScanTime)> records, CancellationToken ct = default)
|
||||
{
|
||||
var rows = new List<object>();
|
||||
foreach (var (channelId, barcode, scanTime) in records)
|
||||
{
|
||||
rows.Add(new { channelId, barcode, scanTime = scanTime.ToString("yyyy-MM-dd HH:mm:ss") });
|
||||
}
|
||||
if (rows.Count == 0) return;
|
||||
|
||||
var payload = JsonSerializer.Serialize(new { records = rows }, Json);
|
||||
using var response = await SendDeviceAsync("/api/scan/records", deviceToken, payload, "上报扫码记录", 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 运单回放查询(**用户令牌**;`GET /api/web/pack-query?code=`)
|
||||
///
|
||||
/// 后端只返回**本主体**的扫码记录;data 里有:
|
||||
/// `found` / `reason` / `hints` / `records`(每条带扫码当时的工作台快照与回放计划)/ `streams`(拍平去重)。
|
||||
/// </summary>
|
||||
/// <exception cref="ApiException">未登录 / 无权限 / 网络不通</exception>
|
||||
public async Task<JsonElement> PackQueryAsync(string token, int subjectId, string code,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var path = $"/api/web/pack-query?code={Uri.EscapeDataString(code ?? string.Empty)}";
|
||||
using var response = await SendAuthorizedAsync(HttpMethod.Get, path, token, subjectId, null, "查询运单回放", 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);
|
||||
return data.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取**当前主体**的全部录像机(用户令牌;`GET /api/web/nvrs`,自动翻页)。
|
||||
/// 后端本来就按主体隔离,桌面端只需要拿列表 + 自己内网连设备。
|
||||
/// </summary>
|
||||
/// <exception cref="ApiException">未登录 / 无权限 / 网络不通</exception>
|
||||
public async Task<IReadOnlyList<ApiNvr>> NvrsAsync(string token, int subjectId, CancellationToken ct = default)
|
||||
{
|
||||
var all = new List<ApiNvr>();
|
||||
|
||||
for (var page = 1; page <= 20; page++)
|
||||
{
|
||||
using var response = await SendAuthorizedAsync(HttpMethod.Get,
|
||||
$"/api/web/nvrs?page={page}&pageSize=100", token, subjectId, null, "查录像机列表", 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);
|
||||
|
||||
if (!data.Value.TryGetProperty("list", out var list) || list.ValueKind != JsonValueKind.Array) break;
|
||||
|
||||
foreach (var item in list.EnumerateArray())
|
||||
{
|
||||
all.Add(new ApiNvr(
|
||||
GetInt(item, "id"),
|
||||
GetString(item, "name") ?? string.Empty,
|
||||
GetString(item, "host") ?? string.Empty,
|
||||
GetInt(item, "port"),
|
||||
GetString(item, "serialNumber")));
|
||||
}
|
||||
|
||||
if (list.GetArrayLength() < 100 || all.Count >= GetInt(data.Value, "total")) break;
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取录像机登录凭据(**含明文密码**,用户令牌;`GET /api/web/nvrs/:id/credential`)
|
||||
///
|
||||
/// 后端只存密文、接口平时不返回密码;只有本机软件真正要去连设备时才现取一次。
|
||||
/// </summary>
|
||||
/// <exception cref="ApiException">不是本主体的 NVR / 网络不通</exception>
|
||||
public async Task<NvrCredential> NvrCredentialAsync(string token, int subjectId, int nvrId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendAuthorizedAsync(HttpMethod.Get, $"/api/web/nvrs/{nvrId}/credential",
|
||||
token, subjectId, null, "取录像机凭据", 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);
|
||||
|
||||
return new NvrCredential(
|
||||
GetInt(data.Value, "id"),
|
||||
GetString(data.Value, "name") ?? string.Empty,
|
||||
GetString(data.Value, "host") ?? string.Empty,
|
||||
GetInt(data.Value, "port"),
|
||||
GetString(data.Value, "username") ?? "admin",
|
||||
GetString(data.Value, "password") ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>查服务器上当前中控已登记的通道(设备令牌;`GET /api/scan/channels`),返回 channelId 集合</summary>
|
||||
public async Task<HashSet<string>> ChannelsAsync(string deviceToken, CancellationToken ct = default)
|
||||
{
|
||||
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
using var response = await SendDeviceAsync(HttpMethod.Get, "/api/scan/channels?pageSize=200", deviceToken, null,
|
||||
"查通道列表", 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);
|
||||
|
||||
if (data.Value.TryGetProperty("list", out var list) && list.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var item in list.EnumerateArray())
|
||||
{
|
||||
var id = GetString(item, "channelId");
|
||||
if (!string.IsNullOrWhiteSpace(id)) result.Add(id);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ==================== 内部:请求 ====================
|
||||
|
||||
/// <summary>带用户令牌 + 主体 header 的请求</summary>
|
||||
private Task<HttpResponseMessage> SendAuthorizedAsync(HttpMethod method, string path, string token, int subjectId,
|
||||
string? jsonBody, string action, CancellationToken ct)
|
||||
{
|
||||
return SendAsync(() =>
|
||||
{
|
||||
var request = new HttpRequestMessage(method, $"{BaseUrl}{path}");
|
||||
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}");
|
||||
if (subjectId > 0) request.Headers.TryAddWithoutValidation("X-Subject-Id", subjectId.ToString());
|
||||
if (jsonBody is not null) request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
|
||||
return request;
|
||||
}, action, ct);
|
||||
}
|
||||
|
||||
/// <summary>带设备令牌的请求(POST,body 为 JSON)</summary>
|
||||
private Task<HttpResponseMessage> SendDeviceAsync(string path, string deviceToken, string jsonBody, string action,
|
||||
CancellationToken ct)
|
||||
=> SendDeviceAsync(HttpMethod.Post, path, deviceToken, jsonBody, action, ct);
|
||||
|
||||
/// <summary>带设备令牌的请求(可指定方法;GET 时 jsonBody 传 null)</summary>
|
||||
private Task<HttpResponseMessage> SendDeviceAsync(HttpMethod method, string path, string deviceToken,
|
||||
string? jsonBody, string action, CancellationToken ct)
|
||||
{
|
||||
return SendAsync(() =>
|
||||
{
|
||||
var request = new HttpRequestMessage(method, $"{BaseUrl}{path}");
|
||||
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {deviceToken}");
|
||||
if (jsonBody is not null)
|
||||
{
|
||||
request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
|
||||
}
|
||||
return request;
|
||||
}, action, ct);
|
||||
}
|
||||
|
||||
/// <summary>发请求:连不上时翻成「无法连接服务器」这种能看懂的提示</summary>
|
||||
private async Task<HttpResponseMessage> SendAsync(
|
||||
Func<HttpRequestMessage> createRequest, string action, CancellationToken ct)
|
||||
@ -138,9 +558,7 @@ public sealed class ApiClient
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析 `{ ok, data, message }`:成功返回 data(JSON 片段),失败返回 message
|
||||
/// </summary>
|
||||
/// <summary>解析 `{ ok, data, message }`:成功返回 data(JSON 片段),失败返回 message</summary>
|
||||
private static (JsonElement? Data, string Message) ReadEnvelope(HttpResponseMessage response, string text)
|
||||
{
|
||||
JsonDocument document;
|
||||
@ -162,7 +580,6 @@ public sealed class ApiClient
|
||||
|
||||
if (ok && root.TryGetProperty("data", out var dataElement))
|
||||
{
|
||||
// 复制一份出来(document 释放后就失效了)
|
||||
return (dataElement.Clone(), "ok");
|
||||
}
|
||||
|
||||
@ -172,6 +589,28 @@ public sealed class ApiClient
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>读主体数组:登录接口是 `data.subjects`,主体列表接口是 `data.list`</summary>
|
||||
private static IReadOnlyList<ApiSubject> ReadSubjects(JsonElement data, string property)
|
||||
{
|
||||
var list = new List<ApiSubject>();
|
||||
if (!data.TryGetProperty(property, out var array) || array.ValueKind != JsonValueKind.Array) return list;
|
||||
|
||||
foreach (var item in array.EnumerateArray())
|
||||
{
|
||||
if (item.ValueKind != JsonValueKind.Object) continue;
|
||||
|
||||
list.Add(new ApiSubject(
|
||||
GetInt(item, "id"),
|
||||
GetString(item, "name") ?? $"#{GetInt(item, "id")}",
|
||||
GetString(item, "expireAt"),
|
||||
item.TryGetProperty("expired", out var expired) && expired.ValueKind == JsonValueKind.True,
|
||||
GetInt(item, "role"),
|
||||
GetInt(item, "memberCount"),
|
||||
GetString(item, "memberName")));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static ApiUser ReadUser(JsonElement data)
|
||||
{
|
||||
// 登录接口是 { token, user },/api/web/me 是直接一个 user
|
||||
@ -189,4 +628,15 @@ public sealed class ApiClient
|
||||
? value.GetString()
|
||||
: null;
|
||||
}
|
||||
|
||||
private static int GetInt(JsonElement element, string property)
|
||||
{
|
||||
if (!element.TryGetProperty(property, out var value)) return 0;
|
||||
return value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Number => value.TryGetInt32(out var number) ? number : 0,
|
||||
JsonValueKind.String => int.TryParse(value.GetString(), out var parsed) ? parsed : 0,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
@ -22,6 +24,10 @@ public static class AppLog
|
||||
private static readonly Encoding Utf8NoBom = new UTF8Encoding(false);
|
||||
|
||||
private static string? _logDirectory;
|
||||
private static int _cleanupState;
|
||||
|
||||
/// <summary>日志保留天数(超过的按天文件自动删除)</summary>
|
||||
public const int KeepDays = 14;
|
||||
|
||||
/// <summary>日志目录(首次访问时创建)</summary>
|
||||
public static string LogDirectory => _logDirectory ??= ResolveDirectory();
|
||||
@ -29,6 +35,8 @@ public static class AppLog
|
||||
/// <summary>写入一行日志(按天分文件,多线程安全)</summary>
|
||||
public static void Write(string message)
|
||||
{
|
||||
EnsureCleanup();
|
||||
|
||||
var now = DateTime.Now;
|
||||
var line = $"[{now:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}";
|
||||
|
||||
@ -45,6 +53,55 @@ public static class AppLog
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>进程内只清理一次(后台服务整天不重启也只跑一次)</summary>
|
||||
private static void EnsureCleanup()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _cleanupState, 1) != 0) return;
|
||||
Cleanup(KeepDays);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除超过 <paramref name="keepDays"/> 天的按天日志(文件名 <c>log_yyyy-MM-dd.txt</c>)。
|
||||
/// 删不掉的文件静默跳过。
|
||||
/// </summary>
|
||||
public static int Cleanup(int keepDays = KeepDays)
|
||||
{
|
||||
var removed = 0;
|
||||
|
||||
try
|
||||
{
|
||||
var dir = LogDirectory;
|
||||
if (!Directory.Exists(dir)) return 0;
|
||||
|
||||
var cutoff = DateTime.Today.AddDays(-Math.Max(keepDays, 1));
|
||||
|
||||
foreach (var file in Directory.EnumerateFiles(dir, "log_*.txt"))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
if (!name.StartsWith("log_", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (!DateTime.TryParseExact(name.Substring(4), "yyyy-MM-dd", CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.None, out var date)) continue;
|
||||
if (date >= cutoff) continue;
|
||||
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
removed++;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 个别文件被占用(用户用记事本开着)就跳过
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 目录不可读:当作没有日志
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清理日志:删除目录下全部 <c>log_*.txt</c>,返回删掉的文件数。
|
||||
/// 当天正在写的文件也能删,下次 <see cref="Write"/> 会重建。
|
||||
|
||||
@ -30,6 +30,76 @@ public sealed class AppSettings
|
||||
/// <summary>是否记住账号</summary>
|
||||
public bool RememberAccount { get; set; } = true;
|
||||
|
||||
// ---------------- 主体(租户) ----------------
|
||||
|
||||
/// <summary>上次选择的主体 id(0 = 未选)</summary>
|
||||
public int SubjectId { get; set; }
|
||||
|
||||
/// <summary>上次选择的主体名称(仅界面展示)</summary>
|
||||
public string SubjectName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>我在该主体里的角色(1 管理员 / 2 成员):非管理员看不到「开启设备服务」</summary>
|
||||
public int SubjectRole { get; set; } = 2;
|
||||
|
||||
// ---------------- 设备服务(本机作为扫码中控上报;**默认关闭**) ----------------
|
||||
|
||||
/// <summary>是否已开启设备服务</summary>
|
||||
public bool DeviceServiceEnabled { get; set; }
|
||||
|
||||
/// <summary>本机设备 id(服务端 scanners.id)</summary>
|
||||
public int DeviceId { get; set; }
|
||||
|
||||
/// <summary>本机设备 SN(默认用机器名,可手工指定)</summary>
|
||||
public string DeviceSn { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>设备长期 JWT(上报用;关闭服务时清空)</summary>
|
||||
public string DeviceToken { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>设备刷新令牌(服务用它自动续期访问令牌;关闭服务时清空)</summary>
|
||||
public string DeviceRefreshToken { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>设备令牌到期时间(展示用)</summary>
|
||||
public string DeviceTokenExpiresAt { get; set; } = string.Empty;
|
||||
|
||||
// ---------------- 录像存储 ----------------
|
||||
|
||||
/// <summary>
|
||||
/// 录像根目录(空 = 默认 <c>~/packVideo</c>)
|
||||
///
|
||||
/// 实际放在这里的文件按 <c>年/月/日</c> 分子目录(见 <see cref="VideoStorage.FolderFor"/>),
|
||||
/// 例如 <c>~/packVideo/2026/03/11/7915…_合并_20260311_101500.mp4</c>。
|
||||
/// </summary>
|
||||
public string VideoRoot { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>解析后的录像根目录(没设置就是默认值)</summary>
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
public string VideoRootResolved => string.IsNullOrWhiteSpace(VideoRoot)
|
||||
? VideoStorage.DefaultRoot
|
||||
: VideoRoot;
|
||||
|
||||
// ---------------- NTP 校时(本机系统时钟) ----------------
|
||||
|
||||
/// <summary>是否启用 NTP 校时(总开关;关闭后启动/定时都不再校时)</summary>
|
||||
public bool NtpEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>NTP 服务器(域名或 IP)</summary>
|
||||
public string NtpServer { get; set; } = "ntp.aliyun.com";
|
||||
|
||||
/// <summary>启动时是否自动校时</summary>
|
||||
public bool NtpSyncOnStartup { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 运行期间的自动校时间隔(分钟;0 = 只在启动时校一次)
|
||||
/// 本机会持续漂移,定时校一次能避免「跑一天又差几秒」。
|
||||
/// </summary>
|
||||
public int NtpSyncIntervalMinutes { get; set; } = 30;
|
||||
|
||||
/// <summary>上次校时时间(展示用,格式 yyyy-MM-dd HH:mm:ss)</summary>
|
||||
public string NtpLastSyncAt { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>上次校时前的本机偏差(秒,正数 = 本机慢了)</summary>
|
||||
public double NtpLastOffsetSeconds { get; set; }
|
||||
|
||||
private static string Dir => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YuncangTrace");
|
||||
|
||||
@ -92,6 +162,22 @@ public sealed class AppSettings
|
||||
ServerBaseUrl = stored,
|
||||
LastAccount = LastAccount,
|
||||
RememberAccount = RememberAccount,
|
||||
SubjectId = SubjectId,
|
||||
SubjectName = SubjectName,
|
||||
SubjectRole = SubjectRole,
|
||||
DeviceServiceEnabled = DeviceServiceEnabled,
|
||||
DeviceId = DeviceId,
|
||||
DeviceSn = DeviceSn,
|
||||
DeviceToken = DeviceToken,
|
||||
DeviceTokenExpiresAt = DeviceTokenExpiresAt,
|
||||
DeviceRefreshToken = DeviceRefreshToken,
|
||||
|
||||
NtpEnabled = NtpEnabled,
|
||||
NtpServer = NtpServer,
|
||||
NtpSyncOnStartup = NtpSyncOnStartup,
|
||||
NtpSyncIntervalMinutes = NtpSyncIntervalMinutes,
|
||||
NtpLastSyncAt = NtpLastSyncAt,
|
||||
NtpLastOffsetSeconds = NtpLastOffsetSeconds,
|
||||
};
|
||||
|
||||
File.WriteAllText(FilePath, JsonSerializer.Serialize(payload, Options));
|
||||
@ -128,5 +214,37 @@ public sealed class AppSettings
|
||||
public string LastAccount { get; set; } = string.Empty;
|
||||
|
||||
public bool RememberAccount { get; set; } = true;
|
||||
|
||||
public int SubjectId { get; set; }
|
||||
|
||||
public string SubjectName { get; set; } = string.Empty;
|
||||
|
||||
public int SubjectRole { get; set; } = 2;
|
||||
|
||||
public bool DeviceServiceEnabled { get; set; }
|
||||
|
||||
public int DeviceId { get; set; }
|
||||
|
||||
public string DeviceSn { get; set; } = string.Empty;
|
||||
|
||||
public string DeviceToken { get; set; } = string.Empty;
|
||||
|
||||
public string DeviceTokenExpiresAt { get; set; } = string.Empty;
|
||||
|
||||
public string DeviceRefreshToken { get; set; } = string.Empty;
|
||||
|
||||
// ---------------- NTP 校时 ----------------
|
||||
|
||||
public bool NtpEnabled { get; set; } = true;
|
||||
|
||||
public string NtpServer { get; set; } = "ntp.aliyun.com";
|
||||
|
||||
public bool NtpSyncOnStartup { get; set; } = true;
|
||||
|
||||
public int NtpSyncIntervalMinutes { get; set; } = 30;
|
||||
|
||||
public string NtpLastSyncAt { get; set; } = string.Empty;
|
||||
|
||||
public double NtpLastOffsetSeconds { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
38
desktop/Services/JwtUtil.cs
Normal file
38
desktop/Services/JwtUtil.cs
Normal file
@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// JWT 的**本地只读**小工具(只解析 payload 里的 exp,不验签)。
|
||||
///
|
||||
/// 后台服务用它判断「访问令牌是不是快到期了」;真正的有效性仍由服务端校验。
|
||||
/// </summary>
|
||||
public static class JwtUtil
|
||||
{
|
||||
/// <summary>取令牌的过期时间(解析不了返回 null)</summary>
|
||||
public static DateTime? Expiry(string? token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token)) return null;
|
||||
|
||||
try
|
||||
{
|
||||
var parts = token.Split('.');
|
||||
if (parts.Length != 3) return null;
|
||||
|
||||
var payload = parts[1].Replace('-', '+').Replace('_', '/');
|
||||
while (payload.Length % 4 != 0) payload += "=";
|
||||
|
||||
using var document = JsonDocument.Parse(Convert.FromBase64String(payload));
|
||||
if (!document.RootElement.TryGetProperty("exp", out var exp)) return null;
|
||||
if (!exp.TryGetInt64(out var seconds)) return null;
|
||||
|
||||
return DateTimeOffset.FromUnixTimeSeconds(seconds).LocalDateTime;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -47,10 +47,13 @@ public sealed class SingleInstance : IDisposable
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
/// <summary>第二个实例调用:把命令行参数送给已运行的实例(连不上就算了,不影响退出)</summary>
|
||||
public void SendArgs(string[] args)
|
||||
/// <summary>
|
||||
/// 第二个实例调用:把命令行参数送给已运行的实例。
|
||||
/// 返回 false = 送不出去(常见原因:第一个实例是**管理员权限**,中完整性的第二个实例写不进它的管道)。
|
||||
/// </summary>
|
||||
public bool SendArgs(string[] args)
|
||||
{
|
||||
if (args.Length == 0) return;
|
||||
if (args.Length == 0) return true;
|
||||
|
||||
try
|
||||
{
|
||||
@ -59,10 +62,13 @@ public sealed class SingleInstance : IDisposable
|
||||
|
||||
using var writer = new StreamWriter(client, new UTF8Encoding(false)) { AutoFlush = true };
|
||||
foreach (var arg in args) writer.WriteLine(arg);
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 拿不到第一个实例(可能正在退出):静默忽略,用户重新点一次即可
|
||||
// 以前这里静默吞掉 → 用户看到的就是“唤起没反应”;现在返回给调用方提示
|
||||
AppLog.Write($"[single] 参数转发失败(第一个实例可能是管理员权限):{ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
29
desktop/SubjectPickerWindow.xaml
Normal file
29
desktop/SubjectPickerWindow.xaml
Normal file
@ -0,0 +1,29 @@
|
||||
<Window x:Class="YuncangTrace.LocalService.SubjectPickerWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="切换主体"
|
||||
Height="400" Width="440"
|
||||
ResizeMode="NoResize"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="{StaticResource BgBrush}"
|
||||
FontFamily="Microsoft YaHei UI, Segoe UI"
|
||||
FontSize="13">
|
||||
<Border Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
|
||||
CornerRadius="10" Margin="18" Padding="18">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="选择主体" FontSize="15" FontWeight="SemiBold" />
|
||||
<TextBlock DockPanel.Dock="Top" Text="设备服务(本机作为扫码中控)会绑定到所选主体"
|
||||
FontSize="12" Foreground="{StaticResource MutedBrush}" Margin="0,4,0,12" />
|
||||
|
||||
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,12,0,0">
|
||||
<Button Content="取消" Padding="14,5" IsCancel="True" Click="Cancel_Click" />
|
||||
<Button Content="确定" Padding="14,5" Margin="8,0,0,0" IsDefault="True"
|
||||
Background="{StaticResource BrandBrush}" Foreground="White" BorderThickness="0"
|
||||
Cursor="Hand" Click="Ok_Click" />
|
||||
</StackPanel>
|
||||
|
||||
<ListBox x:Name="SubjectList" DisplayMemberPath="Display" BorderBrush="{StaticResource LineBrush}"
|
||||
MouseDoubleClick="SubjectList_MouseDoubleClick" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Window>
|
||||
42
desktop/SubjectPickerWindow.xaml.cs
Normal file
42
desktop/SubjectPickerWindow.xaml.cs
Normal file
@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
|
||||
namespace YuncangTrace.LocalService;
|
||||
|
||||
/// <summary>切换主体的小弹窗(列表来自 `GET /api/web/subjects`)</summary>
|
||||
public partial class SubjectPickerWindow : Window
|
||||
{
|
||||
public SubjectPickerWindow(IReadOnlyList<ApiSubject> subjects, int currentId)
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
SubjectList.ItemsSource = subjects;
|
||||
var current = subjects.FirstOrDefault(item => item.Id == currentId);
|
||||
SubjectList.SelectedItem = current ?? subjects.FirstOrDefault(item => !item.Expired) ?? subjects.FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>用户选中的主体(确定后有值)</summary>
|
||||
public ApiSubject? SelectedSubject { get; private set; }
|
||||
|
||||
private void Ok_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (SubjectList.SelectedItem is not ApiSubject subject)
|
||||
{
|
||||
MessageBox.Show(this, "请先选择一个主体", "切换主体", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
SelectedSubject = subject;
|
||||
DialogResult = true;
|
||||
}
|
||||
|
||||
private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false;
|
||||
|
||||
private void SubjectList_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
|
||||
{
|
||||
if (SubjectList.SelectedItem is ApiSubject) Ok_Click(sender, e);
|
||||
}
|
||||
}
|
||||
@ -194,7 +194,9 @@ public partial class UpdateWindow : Window
|
||||
var command = $"/c timeout /t 3 /nobreak >nul & msiexec /i \"{msiPath}\" /passive /norestart";
|
||||
if (File.Exists(exe))
|
||||
{
|
||||
command += $" & start \"\" \"{exe}\"";
|
||||
// ⚠️ 用 explorer 拉起:从提权 cmd “start” 子进程会继续以管理员身份运行,
|
||||
// 而普通权限的协议唤起无法把参数送进管理员实例(表现为“唤起没反应”)。
|
||||
command += $" & explorer.exe \"{exe}\"";
|
||||
}
|
||||
|
||||
AppLog.Write($"启动安装程序(软件退出后执行):{msiPath}");
|
||||
|
||||
@ -2,6 +2,21 @@
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="YuncangTrace.LocalService.app" />
|
||||
|
||||
<!--
|
||||
默认**以普通权限启动**(asInvoker):
|
||||
- 网页 yuncang:// 叫醒、双击、开始菜单都不弹 UAC,日常查件/预览/下载不需要管理员。
|
||||
- 只有真正要改本机系统时间(NTP 校时的「立即校时 / 同步 NVR 时间」)时,
|
||||
才由 Services/ElevatedNtp.cs 用 runas 拉起一个只做校时的临时进程(会弹一次 UAC)。
|
||||
- 本机 HTTP 服务绑定的 http://localhost:端口/ 已验证普通权限可监听。
|
||||
-->
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<security>
|
||||
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<!-- 高 DPI 下别让 WPF 被系统拉伸(否则字发虚) -->
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user