using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Reflection; using System.Text.Json; using ClassNotify.Shared.Models; using ClassNotify.Service.Services; namespace ClassNotify.Setup.Services; public class DeploymentService { public static readonly string InstallDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "ClassNotify"); public static readonly string ServiceDir = Path.Combine(InstallDir, "Service"); public static readonly string ClientDir = Path.Combine(InstallDir, "Client"); public static readonly string DataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify"); public static readonly string CredentialsPath = Path.Combine(DataDir, "device_credentials.json"); public static readonly string InstallerStatePath = Path.Combine(DataDir, "installer_state.json"); public class InstallerState { public string InstallationId { get; set; } = string.Empty; public string? ActivationCode { get; set; } public string? DeviceId { get; set; } public bool ActivationCompleted { get; set; } } public InstallerState GetOrCreateInstallerState() { Directory.CreateDirectory(DataDir); try { if (File.Exists(InstallerStatePath)) { var json = File.ReadAllText(InstallerStatePath); var state = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (state != null && !string.IsNullOrWhiteSpace(state.InstallationId)) { return state; } } } catch { } // Generate new installationId and persist immediately var newState = new InstallerState { InstallationId = $"inst_{Guid.NewGuid():D}", ActivationCompleted = false }; SaveInstallerState(newState); return newState; } public void SaveInstallerState(InstallerState state) { Directory.CreateDirectory(DataDir); var json = JsonSerializer.Serialize(state, new JsonSerializerOptions { WriteIndented = true }); var tmpPath = InstallerStatePath + ".tmp"; File.WriteAllText(tmpPath, json); File.Move(tmpPath, InstallerStatePath, overwrite: true); } public DeviceCredentials? CheckExistingBinding() { try { return DeviceCredentialProtector.LoadCredentials(CredentialsPath); } catch { } return null; } public void SaveDeviceCredentials(DeviceActivationResultDto activationResult, string serverUrl) { Directory.CreateDirectory(DataDir); var creds = new DeviceCredentials { DeviceId = activationResult.DeviceId ?? string.Empty, DeviceToken = activationResult.DeviceToken ?? string.Empty, TenantId = activationResult.TenantId ?? string.Empty, ClassId = activationResult.ClassId ?? string.Empty, ClassDisplayName = activationResult.ClassDisplayName ?? string.Empty, ActivatedAt = DateTimeOffset.UtcNow }; DeviceCredentialProtector.SaveCredentials(CredentialsPath, creds); // Configure general ACL on DataDir for SYSTEM & Admins Full, Users Read (logs etc.) try { var p = Process.Start(new ProcessStartInfo { FileName = "icacls.exe", Arguments = $"\"{DataDir}\" /grant \"Administrators:(OI)(CI)F\" \"SYSTEM:(OI)(CI)F\" \"Users:(OI)(CI)R\" /q", CreateNoWindow = true, UseShellExecute = false }); p?.WaitForExit(3000); } catch { } // Explicitly harden CredentialsPath so ordinary Users have NO access DeviceCredentialProtector.SetHardenedFileAcl(CredentialsPath); } public static void QuiesceExistingInstallationOrThrow(Action? onProgress = null) { if (WindowsServiceManager.IsServiceInstalled()) { onProgress?.Invoke("正在停止现有 ClassNotify 守护服务..."); WindowsServiceManager.StopService(); if (WindowsServiceManager.IsServiceRunning()) { throw new InvalidOperationException("无法停止 ClassNotifyService,升级已安全中止。"); } } onProgress?.Invoke("等待服务进程退出..."); WaitUntilNoProcess("ClassNotify.Service", TimeSpan.FromSeconds(10)); onProgress?.Invoke("正在退出桌面客户端进程..."); StartupManager.TerminateClient(); onProgress?.Invoke("等待客户端进程退出..."); WaitUntilNoProcess("ClassNotify.Client", TimeSpan.FromSeconds(5)); var remainingService = Process.GetProcessesByName("ClassNotify.Service"); var remainingClient = Process.GetProcessesByName("ClassNotify.Client"); bool hasRemaining = remainingService.Length > 0 || remainingClient.Length > 0; foreach (var p in remainingService) p.Dispose(); foreach (var p in remainingClient) p.Dispose(); if (hasRemaining) { throw new InvalidOperationException("ClassNotify 进程仍在运行,无法安全替换核心文件,升级已中止。"); } } public static void WaitUntilNoProcess(string processName, TimeSpan timeout) { var sw = Stopwatch.StartNew(); while (sw.Elapsed < timeout) { var procs = Process.GetProcessesByName(processName); if (procs.Length == 0) { return; } foreach (var p in procs) { p.Dispose(); } Thread.Sleep(200); } } public void DeployBinaries(Action? onProgress = null) { onProgress?.Invoke("正在静默停止现有运行进程并释放文件锁...", 0.05); QuiesceExistingInstallationOrThrow(msg => onProgress?.Invoke(msg, 0.1)); Directory.CreateDirectory(InstallDir); Directory.CreateDirectory(ServiceDir); Directory.CreateDirectory(ClientDir); onProgress?.Invoke("正在提取核心程序包...", 0.2); var assembly = Assembly.GetExecutingAssembly(); using var stream = assembly.GetManifestResourceStream("ClassNotify.Setup.Resources.payload.zip"); if (stream != null) { using var archive = new ZipArchive(stream, ZipArchiveMode.Read); var total = archive.Entries.Count; var current = 0; foreach (var entry in archive.Entries) { current++; if (string.IsNullOrEmpty(entry.Name)) continue; // Directory entry string targetPath; if (entry.FullName.StartsWith("Service/", StringComparison.OrdinalIgnoreCase)) { var rel = entry.FullName["Service/".Length..]; targetPath = Path.Combine(ServiceDir, rel); } else if (entry.FullName.StartsWith("Client/", StringComparison.OrdinalIgnoreCase)) { var rel = entry.FullName["Client/".Length..]; targetPath = Path.Combine(ClientDir, rel); } else { targetPath = Path.Combine(InstallDir, entry.FullName); } var dir = Path.GetDirectoryName(targetPath); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); entry.ExtractToFile(targetPath, overwrite: true); onProgress?.Invoke($"正在部署: {entry.Name}", 0.2 + (0.6 * current / total)); } } else { // Debug fallback: If payload.zip not embedded, check local build folders var baseDir = AppDomain.CurrentDomain.BaseDirectory; var payloadFile = Path.Combine(baseDir, "Resources", "payload.zip"); if (File.Exists(payloadFile)) { ZipFile.ExtractToDirectory(payloadFile, InstallDir, overwriteFiles: true); } else { throw new FileNotFoundException("未在安装程序中找到内嵌核心组件包 (payload.zip)。"); } } // Copy setup program as Uninstall.exe var currentExe = Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule?.FileName; if (!string.IsNullOrEmpty(currentExe) && File.Exists(currentExe)) { var uninstallExe = Path.Combine(InstallDir, "Uninstall.exe"); try { File.Copy(currentExe, uninstallExe, overwrite: true); } catch { } } onProgress?.Invoke("核心文件部署完成", 0.8); } }