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}"); } } }