From 2122c7517bb4f4bdb6015678fe9fc437b66a0fe3 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 19 Oct 2026 22:04:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(desktop):=20=E6=94=AF=E6=8C=81=E4=BB=A5=20?= =?UTF-8?q?Windows=20=E6=9C=8D=E5=8A=A1=E5=B8=B8=E9=A9=BB=EF=BC=8C?= =?UTF-8?q?=E5=AE=89=E8=A3=85=E5=8C=85=E5=86=85=E7=BD=AE=20native=20?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- desktop/Program.cs | 97 ++++ desktop/Services/Agent/AgentFiles.cs | 246 +++++++++ desktop/Services/Agent/AgentHost.cs | 468 ++++++++++++++++ desktop/Services/Agent/AgentWindowsService.cs | 54 ++ desktop/Services/Agent/ServiceInstaller.cs | 519 ++++++++++++++++++ desktop/Services/AgentPaths.cs | 121 ++++ desktop/YuncangTrace.LocalService.csproj | 40 ++ desktop/installer/Product.wxs | 19 +- desktop/installer/build.ps1 | 8 + 9 files changed, 1570 insertions(+), 2 deletions(-) create mode 100644 desktop/Program.cs create mode 100644 desktop/Services/Agent/AgentFiles.cs create mode 100644 desktop/Services/Agent/AgentHost.cs create mode 100644 desktop/Services/Agent/AgentWindowsService.cs create mode 100644 desktop/Services/Agent/ServiceInstaller.cs create mode 100644 desktop/Services/AgentPaths.cs diff --git a/desktop/Program.cs b/desktop/Program.cs new file mode 100644 index 0000000..e149842 --- /dev/null +++ b/desktop/Program.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.ServiceProcess; +using System.Threading; +using YuncangTrace.LocalService.Services; + +namespace YuncangTrace.LocalService; + +/// +/// 进程入口(替代 WPF 自动生成的 Main)——同一个 exe 有三种身份: +/// +/// 1. --service:SCM 拉起的 Windows 服务(LocalSystem),只跑后台扫码/上报/校时,没有界面; +/// 2. --agent-control ...:提权 helper(安装/卸载/启停后台服务),执行完立刻退出; +/// 3. 其它:正常桌面端(WPF 界面、托盘、本机 HTTP 服务)。 +/// +/// 服务/helper 分支必须在这里判断,**不能**等到 App.OnStartup: +/// 服务进程不能创建 WPF Application,helper 进程也不能走单实例逻辑。 +/// +public static class Program +{ + [STAThread] + public static void Main(string[] args) + { + // ① Windows 服务 + if (args.Any(arg => arg.Equals("--service", StringComparison.OrdinalIgnoreCase))) + { + ServiceBase.Run(new AgentWindowsService()); + return; + } + + // ①-b 调试用:不经过 SCM 直接跑后台循环(ServiceBase 在控制台启动会直接抛) + if (args.Any(arg => arg.Equals("--agent-run", StringComparison.OrdinalIgnoreCase))) + { + using var cts = new CancellationTokenSource(); + AgentHost.RunAsync(cts.Token).GetAwaiter().GetResult(); + return; + } + + // ② 提权 helper(安装/卸载/启停服务) + if (ServiceInstaller.IsHelperCall(args)) + { + ServiceInstaller.RunHelper(args); + return; + } + + // ②-b 自愈:旧版本 requireAdministrator 升级后会继承提权,导致 asInvoker 的实例实际仍是管理员。 + // 管理员实例创建的单实例管道/互斥体与普通权限的“协议唤起”不兼容(写不进去)→ 唤起没反应。 + // 这里自动用标准权限重新拉起(explorer 会把请求交给当前用户会话),旧进程退出。 + // ⚠️ NTP 提权 helper(--ntp-sync-elevated)必须保持提权,不能自愈。 + if (!ElevatedNtp.IsHelperCall(args) + && !args.Any(arg => arg.Equals("--keep-elevated", StringComparison.OrdinalIgnoreCase)) + && ClockSyncService.IsElevated + && RelaunchAsStandardUser()) + { + return; + } + + // ③ 桌面端 + var app = new App(); + app.InitializeComponent(); + app.Run(); + } + + /// + /// 以标准权限重新启动自己。 + /// + /// ⚠️ 不能直接用 Process.Start(exe):从提权进程启动子进程会**继承**管理员令牌(asInvoker 也一样)。 + /// 必须交给已经在跑的资源管理器(explorer.exe,中完整性)去启动,才能得到普通权限实例。 + /// 延时 2 秒是为了等当前进程退出、释放互斥体/端口。 + /// + private static bool RelaunchAsStandardUser() + { + try + { + var exe = Environment.ProcessPath; + if (string.IsNullOrEmpty(exe)) return false; + + var command = $"/c timeout /t 2 /nobreak >nul & explorer.exe \"{exe}\""; + Process.Start(new ProcessStartInfo("cmd.exe", command) + { + CreateNoWindow = true, + UseShellExecute = false, + WindowStyle = ProcessWindowStyle.Hidden, + }); + + AppLog.Write("[app] 检测到以管理员权限运行(旧版本升级继承),已用标准权限重新启动"); + return true; + } + catch (Exception ex) + { + AppLog.Write($"[app] 以标准权限重新启动失败(继续以管理员运行):{ex.Message}"); + return false; + } + } +} diff --git a/desktop/Services/Agent/AgentFiles.cs b/desktop/Services/Agent/AgentFiles.cs new file mode 100644 index 0000000..e109395 --- /dev/null +++ b/desktop/Services/Agent/AgentFiles.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; + +namespace YuncangTrace.LocalService.Services; + +/// 后台服务的配置(`%ProgramData%\YuncangTrace\agent.json`,由桌面端写入) +public sealed class AgentConfig +{ + /// 后端根地址(例如 http://127.0.0.1:7300) + public string ServerBaseUrl { get; set; } = ""; + + /// 设备**长期 JWT**(默认 365 天,服务上报扫码用) + public string DeviceToken { get; set; } = ""; + + /// 刷新令牌(服务在访问令牌快过期时自动续期) + public string RefreshToken { get; set; } = ""; + + public string DeviceSn { get; set; } = ""; + public int DeviceId { get; set; } + public int SubjectId { get; set; } + + // ---------------- NTP(服务以 LocalSystem 运行,改系统时间不需要 UAC) ---------------- + + public bool NtpEnabled { get; set; } = true; + public string NtpServer { get; set; } = "ntp.aliyun.com"; + public int NtpIntervalMinutes { get; set; } = 30; + + /// 写入时间(排查用) + public DateTime UpdatedAt { get; set; } = DateTime.Now; +} + +/// 后台服务的令牌文件(`agent-token.json`;服务自动续期后更新) +public sealed class AgentToken +{ + public string DeviceToken { get; set; } = ""; + public string RefreshToken { get; set; } = ""; + public DateTime? ExpiresAt { get; set; } + public DateTime? RefreshExpiresAt { get; set; } + public DateTime UpdatedAt { get; set; } = DateTime.Now; +} + +/// 后台服务的运行状态(桌面端只读展示) +public sealed class AgentStatus +{ + public bool Running { get; set; } + public string Version { get; set; } = ""; + public string DeviceSn { get; set; } = ""; + public int SubjectId { get; set; } + + public string UploadStatus { get; set; } = ""; + public string ChannelSyncStatus { get; set; } = ""; + public int PendingRecords { get; set; } + + public List Channels { get; set; } = new(); + + public string? LastError { get; set; } + + public string NtpLastSyncAt { get; set; } = ""; + public double NtpLastOffsetSeconds { get; set; } + public double NtpRoundTripMs { get; set; } + public DateTime? NtpServerTime { get; set; } + + /// 当前访问令牌到期时间 + public DateTime? TokenExpiresAt { get; set; } + + /// 刷新令牌到期时间 + public DateTime? RefreshTokenExpiresAt { get; set; } + + /// 最近一次续期时间 + public DateTime? LastTokenRefreshAt { get; set; } + + /// 最近一次续期失败原因(成功则 null) + public string? LastTokenRefreshError { get; set; } + + /// 最近一次成功心跳时间 + public DateTime? LastHeartbeatAt { get; set; } + + /// 最近一次心跳失败原因(成功则 null) + public string? LastHeartbeatError { get; set; } + + public DateTime UpdatedAt { get; set; } = DateTime.Now; +} + +/// 服务里某条通道的**运行时状态**(连接/最近条码),桌面端据此显示在线离线 +public sealed class AgentChannelStatus +{ + public string Mac { get; set; } = ""; + public bool Connected { get; set; } + public string LastIp { get; set; } = ""; + public string LastCode { get; set; } = ""; + public DateTime? LastCodeAt { get; set; } +} + +/// 桌面端 → 后台服务的一次性命令(写文件,服务每秒轮询) +public sealed class AgentCommand +{ + public DateTime? TriggerUploadAt { get; set; } + public DateTime? ClearRecordsAt { get; set; } + public string? ClearChannelId { get; set; } + public DateTime? ReloadChannelsAt { get; set; } + public DateTime? NtpSyncAt { get; set; } + public string? NtpServer { get; set; } + + /// 请求后台服务立即用刷新令牌续期访问令牌(测试/排障用) + public DateTime? RefreshTokenAt { get; set; } +} + +/// 服务发现到的设备(写文件供桌面端展示;只保留必要字段) +public sealed class AgentDiscoveredDevice +{ + public string Mac { get; set; } = ""; + public string Ip { get; set; } = ""; + public string HostName { get; set; } = ""; + public string Model { get; set; } = ""; + public string Firmware { get; set; } = ""; + public DateTime UpdatedAt { get; set; } = DateTime.Now; +} + +/// +/// agent.json / agent-status.json / agent-command.json 的读写。 +/// +/// 两个进程(桌面端 + 服务)会同时读写这些文件,所以: +/// - 读:FileShare.ReadWrite,读到一半也不会抛; +/// - 写:先写 .tmp 再原子替换,避免对方读到半截 JSON。 +/// +public static class AgentFiles +{ + private static readonly JsonSerializerOptions Options = new() + { + WriteIndented = true, + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + public static AgentConfig? LoadConfig() => Read(AgentPaths.ConfigFile); + + public static void SaveConfig(AgentConfig config) + { + config.UpdatedAt = DateTime.Now; + Write(AgentPaths.ConfigFile, config); + } + + public static AgentToken? LoadToken() => Read(AgentPaths.TokenFile); + + public static void SaveToken(AgentToken token) + { + token.UpdatedAt = DateTime.Now; + Write(AgentPaths.TokenFile, token); + } + + public static void ClearToken() + { + try + { + if (File.Exists(AgentPaths.TokenFile)) File.Delete(AgentPaths.TokenFile); + } + catch + { + // 删不掉不影响下次开启(会覆盖写) + } + } + + public static AgentStatus? LoadStatus() => Read(AgentPaths.StatusFile); + public static void SaveStatus(AgentStatus status) + { + status.UpdatedAt = DateTime.Now; + Write(AgentPaths.StatusFile, status); + } + + public static AgentCommand? LoadCommand() => Read(AgentPaths.CommandFile); + + public static void SaveCommand(AgentCommand command) => Write(AgentPaths.CommandFile, command); + + /// 追加一条命令(保留还没被服务取走的其它命令) + public static void QueueCommand(Action apply) + { + var command = LoadCommand() ?? new AgentCommand(); + apply(command); + SaveCommand(command); + } + + /// 服务执行完命令后清掉文件(下一条命令不会重复执行) + public static void ClearCommand() + { + try + { + if (File.Exists(AgentPaths.CommandFile)) File.Delete(AgentPaths.CommandFile); + } + catch + { + // 删不掉下次也只是重复执行一遍(幂等) + } + } + + public static List LoadDiscovered() + => Read>(AgentPaths.DiscoveredFile) ?? new List(); + + public static void SaveDiscovered(List devices) + => Write(AgentPaths.DiscoveredFile, devices); + + public static DateTime? FileTime(string path) + { + try + { + return File.Exists(path) ? File.GetLastWriteTimeUtc(path) : null; + } + catch + { + return null; + } + } + + private static T? Read(string path) where T : class + { + try + { + if (!File.Exists(path)) return null; + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var reader = new StreamReader(stream); + var text = reader.ReadToEnd(); + return string.IsNullOrWhiteSpace(text) ? null : JsonSerializer.Deserialize(text, Options); + } + catch + { + return null; + } + } + + private static void Write(string path, T value) + { + try + { + var dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + + var temp = path + ".tmp"; + File.WriteAllText(temp, JsonSerializer.Serialize(value, Options)); + File.Move(temp, path, overwrite: true); + } + catch (Exception ex) + { + AppLog.Write($"[agent] 写文件失败({path}):{ex.Message}"); + } + } +} diff --git a/desktop/Services/Agent/AgentHost.cs b/desktop/Services/Agent/AgentHost.cs new file mode 100644 index 0000000..500847f --- /dev/null +++ b/desktop/Services/Agent/AgentHost.cs @@ -0,0 +1,468 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using YuncangTrace.LocalService.Services.Scan; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 后台扫码服务的运行主体(LocalSystem)。 +/// +/// 职责: +/// 1. 读 %ProgramData%\YuncangTrace\agent.json 里的**长期设备令牌**,跑扫码 TCP 收码 + 上报循环; +/// 2. 监视 channels.json(桌面端改通道后自动重连); +/// 3. 定时 NTP 校时(LocalSystem 改系统时间不需要 UAC); +/// 4. 把运行状态写进 agent-status.json,桌面端只读展示; +/// 5. 执行桌面端写进 agent-command.json 的一次性命令(立即上传 / 清空记录 / 立即校时)。 +/// +/// 与桌面端**完全解耦**:桌面端退出、用户注销都不影响这里。 +/// +public static class AgentHost +{ + /// 状态写盘保活间隔(内容没变也最多 30 秒写一次) + private static readonly TimeSpan StatusKeepAlive = TimeSpan.FromSeconds(30); + + private sealed class NtpState + { + public string LastSyncAt { get; set; } = ""; + public double OffsetSeconds { get; set; } + public double RoundTripMs { get; set; } + public DateTime? ServerTime { get; set; } + public string? Error { get; set; } + } + + public static async Task RunAsync(CancellationToken ct) + { + AgentPaths.MachineMode = true; + AgentPaths.IsServiceProcess = true; + AppLog.Write("[agent] 后台扫码服务启动"); + + try + { + while (!ct.IsCancellationRequested) + { + var config = AgentFiles.LoadConfig(); + if (config is null + || string.IsNullOrWhiteSpace(config.ServerBaseUrl) + || string.IsNullOrWhiteSpace(config.DeviceToken)) + { + AppLog.Write("[agent] 还没有可用配置(等待桌面端「开启设备服务」写入 agent.json)"); + AgentFiles.SaveStatus(new AgentStatus + { + Running = false, + Version = Version, + LastError = "没有配置(agent.json 缺失或缺少设备令牌)", + }); + + if (!await DelayAsync(TimeSpan.FromSeconds(3), ct).ConfigureAwait(false)) break; + continue; + } + + try + { + await RunCoreAsync(config, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + AppLog.Write($"[agent] 运行失败:{ex.Message}"); + AgentFiles.SaveStatus(new AgentStatus + { + Running = false, + Version = Version, + DeviceSn = config.DeviceSn, + SubjectId = config.SubjectId, + LastError = ex.Message, + }); + + if (!await DelayAsync(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false)) break; + } + } + } + finally + { + AgentFiles.SaveStatus(new AgentStatus { Running = false, Version = Version }); + AppLog.Write("[agent] 后台扫码服务停止"); + } + } + + private static string Version => + typeof(AgentHost).Assembly.GetName().Version?.ToString() ?? "1.0.0"; + + private static async Task RunCoreAsync(AgentConfig config, CancellationToken ct) + { + // 用内存里的设置喂给 DeviceService:它只用到 DeviceToken / DeviceSn / SubjectId / Enabled + var settings = new AppSettings + { + ServerBaseUrl = config.ServerBaseUrl, + SubjectId = config.SubjectId, + DeviceId = config.DeviceId, + DeviceSn = config.DeviceSn, + DeviceServiceEnabled = true, + DeviceToken = config.DeviceToken, + NtpEnabled = config.NtpEnabled, + NtpServer = config.NtpServer, + NtpSyncIntervalMinutes = config.NtpIntervalMinutes, + }; + + var api = new ApiClient(config.ServerBaseUrl); + // 服务不需要用户令牌(激活/停用由桌面端做),只用长期设备令牌上报 + var session = new Session { ServerBaseUrl = config.ServerBaseUrl }; + var device = new DeviceService(api, settings, session); + var scan = new ScanService(device); + var ntp = new NtpState(); + + // 令牌以 agent-token.json 为准(服务续期后会更新它),没有才退回 agent.json + var storedToken = AgentFiles.LoadToken(); + var refreshToken = !string.IsNullOrWhiteSpace(storedToken?.RefreshToken) + ? storedToken!.RefreshToken + : config.RefreshToken; + if (!string.IsNullOrWhiteSpace(storedToken?.DeviceToken)) + { + settings.DeviceToken = storedToken!.DeviceToken; + } + var nextRefreshAt = DateTime.MinValue; + DateTime? lastTokenRefreshAt = null; + string? lastTokenRefreshError = null; + var nextHeartbeatAt = DateTime.MinValue; + DateTime? lastHeartbeatAt = null; + string? lastHeartbeatError = null; + + var configTime = AgentFiles.FileTime(AgentPaths.ConfigFile); + var channelsTime = AgentFiles.FileTime(AgentPaths.ChannelsFile); + var nextNtpAt = config.NtpEnabled ? DateTime.UtcNow : DateTime.MaxValue; + var lastStatusJson = string.Empty; + var lastStatusWriteAt = DateTime.MinValue; + + try + { + device.EnsureUploadLoop(); + await scan.StartAsync().ConfigureAwait(false); + scan.StartDiscovery(); // 常驻发现:设备 DHCP 换 IP 时能自己重连 + AppLog.Write($"[agent] 扫码已启动:{scan.Channels.Count(item => item.Enabled)} 个通道" + + $"(SN {config.DeviceSn},主体 {config.SubjectId})"); + + while (!ct.IsCancellationRequested) + { + if (!await DelayAsync(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false)) break; + + // ① 配置变了(换令牌 / 换服务器 / 改 NTP)→ 外层重建链路 + var newConfigTime = AgentFiles.FileTime(AgentPaths.ConfigFile); + if (newConfigTime != configTime) + { + AppLog.Write("[agent] agent.json 已变更,重建扫码链路"); + break; + } + + // ② 通道配置变了(桌面端增删/启停/改静音)→ 重新加载并连接 + var newChannelsTime = AgentFiles.FileTime(AgentPaths.ChannelsFile); + if (newChannelsTime != channelsTime) + { + channelsTime = newChannelsTime; + AppLog.Write("[agent] channels.json 已变更,重新加载通道"); + scan.Stop(); + await scan.StartAsync().ConfigureAwait(false); + scan.StartDiscovery(); + } + + // ③ 桌面端的一次性命令 + var command = AgentFiles.LoadCommand(); + if (command is not null) + { + AgentFiles.ClearCommand(); + + // 手动续期(测试/排障):不管剩多少天都立即换一次 + if (command.RefreshTokenAt is not null) + { + var refreshed = await TryRefreshTokenAsync(api, config.DeviceSn, refreshToken) + .ConfigureAwait(false); + + if (refreshed is not null) + { + settings.DeviceToken = refreshed.Token; + refreshToken = refreshed.RefreshToken; + AgentFiles.SaveToken(new AgentToken + { + DeviceToken = refreshed.Token, + RefreshToken = refreshed.RefreshToken, + ExpiresAt = JwtUtil.Expiry(refreshed.Token), + }); + lastTokenRefreshAt = DateTime.Now; + lastTokenRefreshError = null; + nextRefreshAt = DateTime.MinValue; + } + else + { + lastTokenRefreshError = "手动续期失败(详见日志)"; + } + } + + await ApplyCommandAsync(command, device, scan, config, ntp).ConfigureAwait(false); + + if (command.ReloadChannelsAt is not null) + { + channelsTime = AgentFiles.FileTime(AgentPaths.ChannelsFile); + } + + if (command.NtpSyncAt is not null && config.NtpEnabled) + { + nextNtpAt = DateTime.UtcNow.AddMinutes(Math.Max(config.NtpIntervalMinutes, 5)); + } + } + + // ④ 令牌自动续期:访问令牌剩不到 7 天(或已过期)时用刷新令牌换新 + if (!string.IsNullOrWhiteSpace(refreshToken) && DateTime.Now >= nextRefreshAt) + { + var expiresAt = JwtUtil.Expiry(settings.DeviceToken); + var needRefresh = expiresAt is null || expiresAt.Value - DateTime.Now < TimeSpan.FromDays(7); + + if (needRefresh) + { + var refreshed = await TryRefreshTokenAsync(api, config.DeviceSn, refreshToken) + .ConfigureAwait(false); + + if (refreshed is not null) + { + settings.DeviceToken = refreshed.Token; + refreshToken = refreshed.RefreshToken; + AgentFiles.SaveToken(new AgentToken + { + DeviceToken = refreshed.Token, + RefreshToken = refreshed.RefreshToken, + ExpiresAt = JwtUtil.Expiry(refreshed.Token), + }); + lastTokenRefreshAt = DateTime.Now; + lastTokenRefreshError = null; + nextRefreshAt = DateTime.MinValue; + } + else + { + lastTokenRefreshError = "自动续期失败(10 分钟后重试)"; + nextRefreshAt = DateTime.Now.AddMinutes(10); // 失败 10 分钟后再试(别每分钟刷日志) + } + } + else + { + nextRefreshAt = DateTime.Now.AddMinutes(30); // 还没到窗口,半小时后复查 + } + } + + // ⑤ 设备心跳:每 60 秒一次,让后端 last_seen_at 反映「后台服务还在」 + if (DateTime.UtcNow >= nextHeartbeatAt) + { + try + { + await api.HeartbeatAsync(settings.DeviceToken, ct).ConfigureAwait(false); + + if (lastHeartbeatAt is null) + { + AppLog.Write("[agent] 设备心跳已开始(每 60 秒)"); + } + else if (lastHeartbeatError is not null) + { + AppLog.Write("[agent] 设备心跳已恢复"); + } + + lastHeartbeatAt = DateTime.Now; + lastHeartbeatError = null; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + // 只在第一次失败时记日志,恢复时再记一行,避免每 30 秒刷屏 + if (lastHeartbeatError is null) + { + AppLog.Write($"[agent] 设备心跳失败:{ex.Message}"); + } + lastHeartbeatError = ex.Message; + + // 401 = 令牌过期/被撤销,下一轮让续期逻辑先试一下 + if (ex is ApiException { StatusCode: 401 }) + { + nextRefreshAt = DateTime.MinValue; + } + } + finally + { + nextHeartbeatAt = DateTime.UtcNow.AddSeconds(60); + } + } + + // ⑥ NTP + if (config.NtpEnabled && DateTime.UtcNow >= nextNtpAt) + { + await SyncNtpAsync(config.NtpServer, ntp).ConfigureAwait(false); + nextNtpAt = DateTime.UtcNow.AddMinutes(Math.Max(config.NtpIntervalMinutes, 5)); + } + + // ⑦ 状态:内容变化才写,30 秒没变化保活写一次(避免每 2 秒重写文件) + { + var status = BuildStatus(scan, device, config, ntp); + status.TokenExpiresAt = JwtUtil.Expiry(settings.DeviceToken); + status.RefreshTokenExpiresAt = AgentFiles.LoadToken()?.RefreshExpiresAt; + status.LastTokenRefreshAt = lastTokenRefreshAt; + status.LastTokenRefreshError = lastTokenRefreshError; + status.LastHeartbeatAt = lastHeartbeatAt; + status.LastHeartbeatError = lastHeartbeatError; + + status.UpdatedAt = default; // 签名忽略时间戳 + var signature = JsonSerializer.Serialize(status); + + if (signature != lastStatusJson || DateTime.UtcNow - lastStatusWriteAt >= StatusKeepAlive) + { + AgentFiles.SaveStatus(status); + lastStatusJson = signature; + lastStatusWriteAt = DateTime.UtcNow; + SaveDiscovered(scan); + } + } + } + } + finally + { + scan.Stop(); + device.StopUploadLoop(); + + AgentFiles.SaveStatus(BuildStatus(scan, device, config, ntp, running: false)); + AppLog.Write("[agent] 扫码链路已停止"); + } + } + + private static async Task ApplyCommandAsync(AgentCommand command, DeviceService device, ScanService scan, + AgentConfig config, NtpState ntp) + { + if (command.TriggerUploadAt is not null) + { + AppLog.Write("[agent] 收到命令:立即上传"); + device.TriggerUpload(); + } + + if (command.ClearRecordsAt is not null) + { + var removed = ScanRecordStore.Clear(command.ClearChannelId); + AppLog.Write($"[agent] 收到命令:清空扫码记录 {removed} 条" + + (string.IsNullOrWhiteSpace(command.ClearChannelId) ? "" : $"(通道 {command.ClearChannelId})")); + } + + if (command.ReloadChannelsAt is not null) + { + AppLog.Write("[agent] 收到命令:重新加载通道"); + scan.Stop(); + await scan.StartAsync().ConfigureAwait(false); + scan.StartDiscovery(); + } + + if (command.NtpSyncAt is not null) + { + var server = string.IsNullOrWhiteSpace(command.NtpServer) ? config.NtpServer : command.NtpServer!; + AppLog.Write("[agent] 收到命令:立即校时"); + await SyncNtpAsync(server, ntp).ConfigureAwait(false); + } + } + + private static async Task TryRefreshTokenAsync(ApiClient api, string sn, string refreshToken) + { + try + { + var result = await api.RefreshDeviceTokenAsync(sn, refreshToken).ConfigureAwait(false); + var expiresAt = JwtUtil.Expiry(result.Token); + AppLog.Write($"[agent] 设备令牌已续期(新到期 {expiresAt?.ToString("yyyy-MM-dd HH:mm:ss") ?? "未知"})"); + return result; + } + catch (Exception ex) + { + AppLog.Write($"[agent] 设备令牌续期失败:{ex.Message}"); + return null; + } + } + + private static async Task SyncNtpAsync(string server, NtpState state) + { + try + { + var result = await ClockSyncService.SyncAsync(server).ConfigureAwait(false); + + state.LastSyncAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); + state.OffsetSeconds = result.Offset.TotalSeconds; + state.RoundTripMs = result.RoundTrip.TotalMilliseconds; + state.ServerTime = result.ServerTime.LocalDateTime; + state.Error = null; + + AppLog.Write(result.Offset.Duration() < ClockSyncService.MinimumAdjust + ? $"[agent] NTP 校时:{server} 偏差 {result.Offset.TotalSeconds:+0.00;-0.00} 秒(在误差范围内,未调整)" + : $"[agent] NTP 校时完成:{server} 偏差 {result.Offset.TotalSeconds:+0.00;-0.00} 秒," + + $"往返 {result.RoundTrip.TotalMilliseconds:0} ms"); + } + catch (Exception ex) + { + state.Error = $"NTP 校时失败:{ex.Message}"; + AppLog.Write($"[agent] NTP 校时失败({server}):{ex.Message}"); + } + } + + private static AgentStatus BuildStatus(ScanService scan, DeviceService device, AgentConfig config, + NtpState ntp, bool running = true) + { + return new AgentStatus + { + Running = running && scan.Running, + Version = Version, + DeviceSn = config.DeviceSn, + SubjectId = config.SubjectId, + UploadStatus = scan.UploadStatus, + ChannelSyncStatus = scan.ChannelSyncStatus, + PendingRecords = ScanRecordStore.PendingCount(), + Channels = scan.Channels.Select(channel => new AgentChannelStatus + { + Mac = channel.Mac, + Connected = channel.Connected, + LastIp = channel.LastIp, + LastCode = channel.LastCode, + LastCodeAt = channel.LastCodeAt, + }).ToList(), + LastError = ntp.Error, + NtpLastSyncAt = ntp.LastSyncAt, + NtpLastOffsetSeconds = ntp.OffsetSeconds, + NtpRoundTripMs = ntp.RoundTripMs, + NtpServerTime = ntp.ServerTime, + }; + } + + private static void SaveDiscovered(ScanService scan) + { + var devices = scan.DiscoveredDevices + .Select(item => new AgentDiscoveredDevice + { + Mac = item.Mac, + Ip = item.Ip, + HostName = item.HostName, + Model = item.Model, + Firmware = item.Version, + }) + .ToList(); + + AgentFiles.SaveDiscovered(devices); + } + + private static async Task DelayAsync(TimeSpan delay, CancellationToken ct) + { + try + { + await Task.Delay(delay, ct).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) + { + return false; + } + } +} diff --git a/desktop/Services/Agent/AgentWindowsService.cs b/desktop/Services/Agent/AgentWindowsService.cs new file mode 100644 index 0000000..476cb13 --- /dev/null +++ b/desktop/Services/Agent/AgentWindowsService.cs @@ -0,0 +1,54 @@ +using System; +using System.ServiceProcess; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services; + +/// +/// Windows 服务壳:SCM 拉起后在这里跑 。 +/// +/// 进程仍是同一个 exe(YuncangTrace.LocalService.exe --service), +/// 但**不创建任何 WPF 窗口/托盘/HTTP 服务** —— Session 0 里没有桌面。 +/// +public sealed class AgentWindowsService : ServiceBase +{ + private CancellationTokenSource? _cts; + private Task? _task; + + public AgentWindowsService() + { + ServiceName = ServiceInstaller.ServiceName; + CanStop = true; + CanShutdown = true; + AutoLog = false; // 不写事件日志:没注册 EventLog source 会直接抛 + } + + protected override void OnStart(string[] args) + { + _cts = new CancellationTokenSource(); + _task = Task.Run(() => AgentHost.RunAsync(_cts.Token)); + } + + protected override void OnStop() + { + try + { + _cts?.Cancel(); + _task?.Wait(TimeSpan.FromSeconds(10)); + } + catch + { + // 停服务不能卡住 SCM + } + finally + { + _cts?.Dispose(); + _cts = null; + _task = null; + } + } + + /// 系统关机:与 Stop 一样尽力停下来(把扫码记录落盘) + protected override void OnShutdown() => OnStop(); +} diff --git a/desktop/Services/Agent/ServiceInstaller.cs b/desktop/Services/Agent/ServiceInstaller.cs new file mode 100644 index 0000000..cc59baa --- /dev/null +++ b/desktop/Services/Agent/ServiceInstaller.cs @@ -0,0 +1,519 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Win32; + +namespace YuncangTrace.LocalService.Services; + +/// Windows 服务当前状态(SCM 的 dwCurrentState) +public enum AgentServiceState +{ + Unknown = 0, + NotInstalled, + Stopped, + StartPending, + StopPending, + Running, +} + +/// +/// 「扫码后台服务」的安装/卸载/启停(服务名 YuncangTraceAgent)。 +/// +/// 设计要点: +/// - **服务跑自己的 exe 副本**(%ProgramData%\YuncangTrace\agent\YuncangTraceAgent.exe), +/// MSI 升级替换安装目录的 exe 时不会撞「文件被占用」; +/// - 安装/卸载/启停都需要管理员权限 → 用 runas 起一个临时进程执行(**只在这些操作时弹 UAC**); +/// - 服务以 LocalSystem 自动启动,用户注销/退出桌面端不影响扫码上报。 +/// +public static class ServiceInstaller +{ + public const string ServiceName = "YuncangTraceAgent"; + public const string DisplayName = "云仓视频溯源-扫码服务"; + + /// 提权 helper 的命令行标记 + private const string ControlArg = "--agent-control"; + + private const int ErrorCancelled = 1223; + + private sealed class HelperResult + { + public bool Ok { get; set; } + public string Message { get; set; } = ""; + } + + /// 这次启动是不是「服务管理 helper」 + public static bool IsHelperCall(string[] args) + => args.Length > 0 && args[0].Equals(ControlArg, StringComparison.OrdinalIgnoreCase); + + /// 服务是否已注册(读注册表,普通权限即可) + public static bool IsInstalled + { + get + { + try + { + using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{ServiceName}"); + return key is not null; + } + catch + { + return false; + } + } + } + + /// 服务是否正在运行 + public static bool IsRunning => QueryState() == AgentServiceState.Running; + + /// 服务副本是否和当前程序版本不一致(升级后需要更新) + public static bool NeedsBinaryUpdate + { + get + { + try + { + var source = Environment.ProcessPath; + if (string.IsNullOrEmpty(source) || !File.Exists(source)) return false; + if (!File.Exists(AgentPaths.AgentExe)) return true; + + var running = FileVersionInfo.GetVersionInfo(AgentPaths.AgentExe).FileVersion ?? ""; + var current = FileVersionInfo.GetVersionInfo(source).FileVersion ?? ""; + if (!string.Equals(running, current, StringComparison.OrdinalIgnoreCase)) return true; + + return new FileInfo(source).Length != new FileInfo(AgentPaths.AgentExe).Length; + } + catch + { + return true; + } + } + } + + // ==================== 桌面端调用(会弹 UAC) ==================== + + public static Task<(bool Ok, string Message)> InstallOrUpdateAsync(CancellationToken ct = default) + => RunElevatedAsync("install", ct); + + public static Task<(bool Ok, string Message)> UninstallAsync(CancellationToken ct = default) + => RunElevatedAsync("uninstall", ct); + + public static Task<(bool Ok, string Message)> StartAsync(CancellationToken ct = default) + => RunElevatedAsync("start", ct); + + public static Task<(bool Ok, string Message)> StopAsync(CancellationToken ct = default) + => RunElevatedAsync("stop", ct); + + private static async Task<(bool Ok, string Message)> RunElevatedAsync(string action, CancellationToken ct) + { + var exe = Environment.ProcessPath; + if (string.IsNullOrEmpty(exe)) return (false, "找不到当前程序路径,无法请求管理员权限"); + + var resultFile = Path.Combine(Path.GetTempPath(), $"yuncang_agent_{Guid.NewGuid():N}.json"); + + try + { + var psi = new ProcessStartInfo(exe, $"{ControlArg} {action} \"{resultFile}\"") + { + UseShellExecute = true, // runas 只能走 ShellExecute + Verb = "runas", + WindowStyle = ProcessWindowStyle.Hidden, + }; + + using var process = await Task.Run(() => Process.Start(psi), ct).ConfigureAwait(false); + if (process is null) return (false, "提权进程启动失败"); + + await process.WaitForExitAsync(ct).ConfigureAwait(false); + + var result = ReadResult(resultFile); + return result is null + ? (false, $"操作没有返回结果(退出码 {process.ExitCode})") + : (result.Ok, result.Message); + } + catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled) + { + return (false, "已取消管理员授权(安装/管理后台服务需要管理员权限)"); + } + catch (Exception ex) + { + return (false, ex.Message); + } + finally + { + TryDelete(resultFile); + } + } + + // ==================== 提权 helper 入口 ==================== + + /// + /// 提权后的实际执行体:--agent-control install|uninstall|start|stop "<结果文件>" + /// + public static void RunHelper(string[] args) + { + var action = args.Length > 1 ? args[1].ToLowerInvariant() : ""; + var resultFile = args.Length > 2 ? args[2] : ""; + + HelperResult result; + try + { + result = action switch + { + "install" => InstallCore(), + "uninstall" => UninstallCore(), + "start" => StartCore(), + "stop" => StopCore(), + _ => new HelperResult { Ok = false, Message = $"未知操作:{action}" }, + }; + } + catch (Exception ex) + { + result = new HelperResult { Ok = false, Message = ex.Message }; + } + + if (resultFile.Length > 0) + { + try + { + File.WriteAllText(resultFile, JsonSerializer.Serialize(result)); + } + catch (Exception ex) + { + AppLog.Write($"[agent] 写服务管理结果失败:{ex.Message}"); + } + } + + AppLog.Write($"[agent] 服务管理({action}):{(result.Ok ? "成功" : "失败")} {result.Message}"); + } + + private static HelperResult InstallCore() + { + if (!ClockSyncService.IsElevated) return Fail("提权失败:当前进程不是管理员权限"); + + var source = Environment.ProcessPath; + if (string.IsNullOrEmpty(source) || !File.Exists(source)) return Fail("找不到当前程序 exe"); + + Directory.CreateDirectory(AgentPaths.MachineRoot); + Directory.CreateDirectory(AgentPaths.AgentDir); + + // 桌面端(普通用户)要能写 agent.json / channels.json / 命令文件,并读状态 + RunTool("icacls.exe", AgentPaths.MachineRoot, "/grant", "*S-1-5-32-545:(OI)(CI)M", "/T", "/C", "/Q"); + + // 先停旧服务,才能替换副本 exe + StopCore(); + WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled, + TimeSpan.FromSeconds(15)); + + // 服务进程退出后文件句柄还要几十毫秒才释放 → 重试几次 + Exception? copyError = null; + for (var attempt = 0; attempt < 20; attempt++) + { + try + { + CopyAgentFiles(source); + copyError = null; + break; + } + catch (Exception ex) + { + copyError = ex; + Thread.Sleep(500); + } + } + if (copyError is not null) return Fail($"复制后台服务程序失败:{copyError.Message}"); + + var binPath = $"\"{AgentPaths.AgentExe}\" --service"; + + if (!IsInstalled) + { + var create = RunSc("create", ServiceName, + "binPath=", binPath, + "start=", "auto", + "DisplayName=", DisplayName); + + // 1072 = 服务标记为删除(上一次卸载还没完全生效)→ 等一会重试 + for (var i = 0; i < 20 && create.Code == 1072; i++) + { + Thread.Sleep(500); + create = RunSc("create", ServiceName, + "binPath=", binPath, + "start=", "auto", + "DisplayName=", DisplayName); + } + + if (create.Code != 0) return Fail($"创建服务失败({create.Code}):{create.Output}"); + } + else + { + var config = RunSc("config", ServiceName, "binPath=", binPath, "start=", "auto"); + if (config.Code != 0) return Fail($"更新服务配置失败({config.Code}):{config.Output}"); + } + + RunSc("description", ServiceName, "云仓视频溯源扫码服务(后台收码/上报,退出桌面端后仍运行)"); + // 崩溃自动重启:5s → 10s → 30s + RunSc("failure", ServiceName, "reset=", "86400", + "actions=", "restart/5000/restart/10000/restart/30000"); + + var start = StartCore(); + if (!start.Ok) return start; + + return new HelperResult + { + Ok = true, + Message = $"后台服务已安装并启动:{AgentPaths.AgentExe}", + }; + } + + private static HelperResult UninstallCore() + { + if (!ClockSyncService.IsElevated) return Fail("提权失败:当前进程不是管理员权限"); + + StopCore(); + WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled, + TimeSpan.FromSeconds(15)); + + if (IsInstalled) + { + var delete = RunSc("delete", ServiceName); + if (delete.Code != 0 && delete.Code != 1060) + { + return Fail($"删除服务失败({delete.Code}):{delete.Output}"); + } + + // sc delete 是异步的:等注册表项真的消失,避免下次安装报 1072(标记为删除) + for (var i = 0; i < 40 && IsInstalled; i++) Thread.Sleep(250); + } + + // 只删「服务程序 + 服务专用文件」,通道/扫码记录保留给桌面端回写 + foreach (var file in new[] + { + AgentPaths.ConfigFile, AgentPaths.TokenFile, AgentPaths.StatusFile, + AgentPaths.CommandFile, AgentPaths.DiscoveredFile, + }) + { + TryDelete(file); + } + TryDeleteDirectory(AgentPaths.AgentDir); + + return new HelperResult { Ok = true, Message = "后台服务已卸载" }; + } + + private static HelperResult StartCore() + { + if (!IsInstalled) return Fail("服务未安装"); + + var (code, output) = RunSc("start", ServiceName); + // 1056 = 已在运行;1053 = 已受理但还没进入 Running(下面轮询确认) + if (code is not (0 or 1056 or 1053)) return Fail($"启动服务失败({code}):{output}"); + + return WaitForState(state => state == AgentServiceState.Running, TimeSpan.FromSeconds(20)) + ? new HelperResult { Ok = true, Message = "后台服务已启动" } + : Fail("后台服务启动超时(查看 事件查看器/服务日志)"); + } + + private static HelperResult StopCore() + { + if (!IsInstalled) return new HelperResult { Ok = true, Message = "服务未安装,无需停止" }; + + var (code, output) = RunSc("stop", ServiceName); + // 1062 = 服务未启动;1073 = 已停止 + if (code is not (0 or 1062 or 1073)) return Fail($"停止服务失败({code}):{output}"); + + return WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled, + TimeSpan.FromSeconds(15)) + ? new HelperResult { Ok = true, Message = "后台服务已停止" } + : Fail("后台服务停止超时"); + } + + private static HelperResult Fail(string message) => new() { Ok = false, Message = message }; + + /// + /// 把当前程序复制到 ProgramData 作为服务副本。 + /// 单文件发布只复制一个 exe;开发环境(framework-dependent)连 dll/json 一起复制, + /// 但不复制 native(服务不跑 ffmpeg / 海康 SDK)。 + /// + private static void CopyAgentFiles(string source) + { + var sourceDir = Path.GetDirectoryName(source) + ?? throw new InvalidOperationException("取不到程序目录"); + + var singleFile = !File.Exists(Path.Combine(sourceDir, "YuncangTrace.LocalService.dll")); + + foreach (var file in Directory.EnumerateFiles(AgentPaths.AgentDir)) + { + try + { + File.Delete(file); + } + catch + { + // 旧文件删不掉就覆盖写 + } + } + + if (singleFile) + { + File.Copy(source, AgentPaths.AgentExe, overwrite: true); + return; + } + + foreach (var file in Directory.EnumerateFiles(sourceDir)) + { + var extension = Path.GetExtension(file).ToLowerInvariant(); + if (extension is not (".exe" or ".dll" or ".json")) continue; + if (Path.GetFileName(file).Contains("ffmpeg", StringComparison.OrdinalIgnoreCase)) continue; + + File.Copy(file, Path.Combine(AgentPaths.AgentDir, Path.GetFileName(file)), overwrite: true); + } + + if (!File.Exists(AgentPaths.AgentExe)) File.Copy(source, AgentPaths.AgentExe, overwrite: true); + } + + // ==================== 状态查询(SCM,无需管理员) ==================== + + public static AgentServiceState QueryState() + { + IntPtr manager = IntPtr.Zero; + IntPtr service = IntPtr.Zero; + try + { + manager = OpenSCManager(null, null, ScManagerConnect); + if (manager == IntPtr.Zero) return AgentServiceState.Unknown; + + service = OpenService(manager, ServiceName, ServiceQueryStatus); + if (service == IntPtr.Zero) return AgentServiceState.NotInstalled; + + if (!QueryServiceStatus(service, out var status)) return AgentServiceState.Unknown; + + return status.dwCurrentState switch + { + 1 => AgentServiceState.Stopped, + 2 => AgentServiceState.StartPending, + 3 => AgentServiceState.StopPending, + 4 => AgentServiceState.Running, + _ => AgentServiceState.Unknown, + }; + } + catch + { + return AgentServiceState.Unknown; + } + finally + { + if (service != IntPtr.Zero) CloseServiceHandle(service); + if (manager != IntPtr.Zero) CloseServiceHandle(manager); + } + } + + private static bool WaitForState(Func predicate, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < deadline) + { + if (predicate(QueryState())) return true; + Thread.Sleep(250); + } + return predicate(QueryState()); + } + + // ==================== 工具 ==================== + + private static (int Code, string Output) RunSc(params string[] args) => RunTool("sc.exe", args); + + private static (int Code, string Output) RunTool(string file, params string[] args) + { + try + { + var psi = new ProcessStartInfo(file) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var arg in args) psi.ArgumentList.Add(arg); + + using var process = Process.Start(psi); + if (process is null) return (-1, $"{file} 启动失败"); + + var output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd(); + process.WaitForExit(); + return (process.ExitCode, output.Trim()); + } + catch (Exception ex) + { + return (-1, ex.Message); + } + } + + private static HelperResult? ReadResult(string path) + { + try + { + if (!File.Exists(path)) return null; + var text = File.ReadAllText(path); + return string.IsNullOrWhiteSpace(text) ? null : JsonSerializer.Deserialize(text); + } + catch + { + return null; + } + } + + private static void TryDelete(string path) + { + try + { + if (File.Exists(path)) File.Delete(path); + } + catch + { + // 忽略 + } + } + + private static void TryDeleteDirectory(string path) + { + try + { + if (Directory.Exists(path)) Directory.Delete(path, recursive: true); + } + catch + { + // 文件还被占用时下次安装会覆盖,不必强求 + } + } + + // ==================== Win32 ==================== + + private const uint ScManagerConnect = 0x0001; + private const uint ServiceQueryStatus = 0x0004; + + [StructLayout(LayoutKind.Sequential)] + private struct ServiceStatus + { + public uint dwServiceType; + public uint dwCurrentState; + public uint dwControlsAccepted; + public uint dwWin32ExitCode; + public uint dwServiceSpecificExitCode; + public uint dwCheckPoint; + public uint dwWaitHint; + } + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern IntPtr OpenSCManager(string? machineName, string? databaseName, uint desiredAccess); + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern IntPtr OpenService(IntPtr manager, string serviceName, uint desiredAccess); + + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool QueryServiceStatus(IntPtr service, out ServiceStatus status); + + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool CloseServiceHandle(IntPtr handle); +} diff --git a/desktop/Services/AgentPaths.cs b/desktop/Services/AgentPaths.cs new file mode 100644 index 0000000..29d07d2 --- /dev/null +++ b/desktop/Services/AgentPaths.cs @@ -0,0 +1,121 @@ +using System; +using System.IO; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 桌面端(用户会话)与后台扫码服务(LocalSystem)**共用的数据目录**。 +/// +/// - 普通模式:通道 / 扫码记录放 `%LOCALAPPDATA%\YuncangTrace`(和以前一样); +/// - 服务模式(设备服务以 Windows 服务方式运行):两边都读写 +/// `%ProgramData%\YuncangTrace`,这样退出桌面端、用户注销后服务照样收码上报, +/// 重新打开桌面端也能看到服务写的通道状态/扫码记录。 +/// +/// 服务进程只认 下的文件,桌面端通过 +/// / / 与它交互。 +/// +public static class AgentPaths +{ + /// true = 当前处于「服务模式」(通道/扫码记录走 ProgramData) + public static bool MachineMode { get; set; } + + /// 当前进程是不是后台服务进程(服务进程不回读自己写的文件) + public static bool IsServiceProcess { get; set; } + + /// ProgramData 根:`C:\ProgramData\YuncangTrace` + public static string MachineRoot => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "YuncangTrace"); + + /// 用户数据根:`%LOCALAPPDATA%\YuncangTrace` + public static string UserRoot => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YuncangTrace"); + + /// 当前生效的数据根(由 决定) + public static string DataRoot => MachineMode ? MachineRoot : UserRoot; + + /// 通道配置(桌面端和服务共用同名文件) + public static string ChannelsFile => Path.Combine(DataRoot, "channels.json"); + + /// 本地扫码记录(桌面端只读展示,服务负责写) + public static string RecordsFile => Path.Combine(DataRoot, "scan-records.json"); + + /// 后台服务程序目录(服务跑自己的副本,避免 MSI 升级时 exe 被占用) + public static string AgentDir => Path.Combine(MachineRoot, "agent"); + + /// 后台服务实际运行的 exe(从安装目录复制过来) + public static string AgentExe => Path.Combine(AgentDir, "YuncangTraceAgent.exe"); + + /// 服务配置(服务器地址 + 长期设备令牌 + NTP 设置),由桌面端写入 + public static string ConfigFile => Path.Combine(MachineRoot, "agent.json"); + + /// + /// 服务令牌(访问令牌 + 刷新令牌),由服务在自动续期后更新;桌面端开启服务时也会写一份。 + /// 单独放文件是为了避免与桌面端写 agent.json 时互相覆盖(NTP 修改等)。 + /// + public static string TokenFile => Path.Combine(MachineRoot, "agent-token.json"); + + /// 服务运行状态(桌面端只读) + public static string StatusFile => Path.Combine(MachineRoot, "agent-status.json"); + + /// 桌面端 → 服务的命令(立即上传 / 清空记录 / 立即校时) + public static string CommandFile => Path.Combine(MachineRoot, "agent-command.json"); + + /// 服务发现到的设备列表(桌面端「扫码通道」页展示用) + public static string DiscoveredFile => Path.Combine(MachineRoot, "agent-discovered.json"); + + /// + /// 开启服务模式时把用户目录里已有的通道/扫码记录搬到 ProgramData(**不覆盖已有文件**)。 + /// + public static string? MigrateUserDataToMachine() + { + try + { + Directory.CreateDirectory(MachineRoot); + + var copied = new System.Collections.Generic.List(); + foreach (var name in new[] { "channels.json", "scan-records.json" }) + { + var from = Path.Combine(UserRoot, name); + var to = Path.Combine(MachineRoot, name); + if (!File.Exists(from) || File.Exists(to)) continue; + File.Copy(from, to, overwrite: false); + copied.Add(name); + } + + return copied.Count == 0 ? null : $"已迁移本地数据:{string.Join("、", copied)}"; + } + catch (Exception ex) + { + return $"迁移本地数据失败:{ex.Message}"; + } + } + + /// + /// 关闭服务模式时把 ProgramData 里的通道/扫码记录写回用户目录(覆盖), + /// 让后续的普通模式继续沿用这些数据。 + /// + public static string? CopyMachineDataToUser() + { + try + { + if (!Directory.Exists(MachineRoot)) return null; + + var copied = new System.Collections.Generic.List(); + foreach (var name in new[] { "channels.json", "scan-records.json" }) + { + var from = Path.Combine(MachineRoot, name); + var to = Path.Combine(UserRoot, name); + if (!File.Exists(from)) continue; + Directory.CreateDirectory(UserRoot); + File.Copy(from, to, overwrite: true); + copied.Add(name); + } + + return copied.Count == 0 ? null : $"已回写本地数据:{string.Join("、", copied)}"; + } + catch (Exception ex) + { + return $"回写本地数据失败:{ex.Message}"; + } + } +} diff --git a/desktop/YuncangTrace.LocalService.csproj b/desktop/YuncangTrace.LocalService.csproj index 13cd22f..06ec88f 100644 --- a/desktop/YuncangTrace.LocalService.csproj +++ b/desktop/YuncangTrace.LocalService.csproj @@ -47,6 +47,12 @@ 云仓 云仓视频溯源软件(本机服务) zh-CN + + + YuncangTrace.LocalService.Program @@ -61,4 +67,38 @@ + + + + PreserveNewest + PreserveNewest + + true + + + + + PreserveNewest + PreserveNewest + true + + + + + + diff --git a/desktop/installer/Product.wxs b/desktop/installer/Product.wxs index 503954c..360ff4b 100644 --- a/desktop/installer/Product.wxs +++ b/desktop/installer/Product.wxs @@ -29,7 +29,10 @@ - + + + + @@ -40,12 +43,13 @@ + + - + + + + + + + diff --git a/desktop/installer/build.ps1 b/desktop/installer/build.ps1 index e910789..4b6d312 100644 --- a/desktop/installer/build.ps1 +++ b/desktop/installer/build.ps1 @@ -125,6 +125,14 @@ finally { $exe = Join-Path $publishDir 'YuncangTrace.LocalService.exe' if (-not (Test-Path $exe)) { throw "发布产物不存在:$exe" } +# ffmpeg 必须随包安装:回放校验 / 多路合并 / 主码流转 MJPEG 都依赖它。 +# 客户机(尤其非设备服务器)普遍没有 ffmpeg,缺了它就只能拿到「合并失败,保留各路段」。 +$ffmpeg = Join-Path $publishDir 'native\ffmpeg\ffmpeg.exe' +if (-not (Test-Path $ffmpeg)) { + throw "缺少 ffmpeg:$ffmpeg`n请把 ffmpeg.exe 放到 desktop\native\ffmpeg\ffmpeg.exe 后再打包(详见该目录的 README.md)。" +} +Write-Host "ffmpeg:$([math]::Round((Get-Item $ffmpeg).Length / 1MB, 1)) MB" + # ---------------- 4. 打 MSI ---------------- $wix = (Get-Command wix.exe -ErrorAction SilentlyContinue).Source if (-not $wix) { $wix = Join-Path $env:USERPROFILE '.dotnet\tools\wix.exe' }