using System; using System.Diagnostics; using System.IO; using System.Text.Json; using System.Threading.Tasks; using ClassNotify.Shared.Models; namespace ClassNotify.Setup.Services; public class SelfCheckReport { public bool ServiceRunning { get; set; } public bool ClientRunning { get; set; } public bool PipeConnected { get; set; } public string? Details { get; set; } public bool AllPassed { get; set; } public DeviceHealthReportDto? HealthReport { get; set; } } public class SelfCheckService { public async Task RunSelfCheckAsync(string? className = "班级终端", string? customHealthPath = null, int timeoutSeconds = 15) { className ??= "班级终端"; var report = new SelfCheckReport(); // 1. Check Windows Service Running report.ServiceRunning = WindowsServiceManager.IsServiceRunning(); var clientProcesses = Process.GetProcessesByName("ClassNotify.Client"); report.ClientRunning = clientProcesses.Length > 0; if (!report.ServiceRunning) { report.AllPassed = false; report.Details = "自检未通过:ClassNotify Windows Service 守护进程未运行。"; return report; } // 2. Wait up to timeoutSeconds for health_status.json from Service var healthPath = customHealthPath ?? Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "health_status.json"); var sw = Stopwatch.StartNew(); DeviceHealthReportDto? healthDto = null; while (sw.Elapsed < TimeSpan.FromSeconds(timeoutSeconds)) { if (File.Exists(healthPath)) { try { var json = await File.ReadAllTextAsync(healthPath); var candidate = JsonSerializer.Deserialize(json); if (candidate != null) { // Check if fresh (< 30 seconds) if (DateTimeOffset.UtcNow - candidate.CheckedAtUtc < TimeSpan.FromSeconds(30)) { healthDto = candidate; break; } } } catch { // File might be mid-write or locked momentarily, retry } } await Task.Delay(500); } report.HealthReport = healthDto; if (healthDto == null) { report.AllPassed = false; report.Details = "全链路健康检查未通过:未能在15秒内获取到有效的最近健康快照(文件缺失或已过期)。"; return report; } report.PipeConnected = healthDto.PipeOk; // 5. Evaluate AllPassed bool passed = report.ServiceRunning && healthDto.OverallStatus == "Healthy" && healthDto.PipeOk && healthDto.ClientConnected && healthDto.SignalROk && healthDto.HttpsOk && healthDto.TtsOk; report.AllPassed = passed; if (passed) { report.Details = $"全链路健康检查通过:【{className}】后台服务已连接云端,本地 IPC 与 TTS 语音引擎均就绪。"; } else { report.Details = $"全链路健康检查未完全通过: Overall={healthDto.OverallStatus}, Pipe={healthDto.PipeOk}, Client={healthDto.ClientConnected}, SignalR={healthDto.SignalROk}, Https={healthDto.HttpsOk}, TTS={healthDto.TtsOk}"; } return report; } }