using System.Net.Http; using System.Net.Http.Json; using System.Net.NetworkInformation; using ClassNotify.Shared.Models; namespace ClassNotify.Setup.Services; public class ActivationService { private readonly HttpClient _httpClient; public string ServerUrl { get; set; } = "https://classnotify.paradise.eu.org"; public ActivationService(string? serverUrl = null) { if (!string.IsNullOrWhiteSpace(serverUrl)) { ServerUrl = serverUrl.TrimEnd('/'); } _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; } public async Task ActivateAsync(string activationCode, string installationId) { if (string.IsNullOrWhiteSpace(activationCode)) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "请输入 8 位激活码" }; } var hostname = Environment.MachineName; var request = new DeviceActivationRequestDto { ActivationCode = activationCode.Trim().ToUpperInvariant(), InstallationId = installationId, Hostname = hostname, ClientVersion = "2.2.0", HardwareComponentsHash = ClassNotify.Service.Services.HardwareFingerprintProvider.GetHardwareComponentsHash(), FingerprintVersion = 1 }; try { var endpoint = $"{ServerUrl}/api/device/activate"; var response = await _httpClient.PostAsJsonAsync(endpoint, request); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadFromJsonAsync(); return result ?? new DeviceActivationResultDto { Success = false, ErrorMessage = "解析服务器响应失败" }; } else { try { var errorResult = await response.Content.ReadFromJsonAsync(); if (errorResult != null && !string.IsNullOrEmpty(errorResult.ErrorMessage)) { return errorResult; } } catch { } return new DeviceActivationResultDto { Success = false, ErrorMessage = $"激活失败 (HTTP {(int)response.StatusCode}): {response.ReasonPhrase}" }; } } catch (HttpRequestException ex) { return new DeviceActivationResultDto { Success = false, ErrorMessage = $"无法连接到云端服务器 ({ServerUrl}),请检查教室网络连接。详细: {ex.Message}" }; } catch (TaskCanceledException) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "请求云端服务器超时,请检查外网环境后重试。" }; } catch (Exception ex) { return new DeviceActivationResultDto { Success = false, ErrorMessage = $"激活过程发生异常: {ex.Message}" }; } } private static string GetFirstMacAddress() { try { var nic = NetworkInterface.GetAllNetworkInterfaces() .FirstOrDefault(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback); if (nic != null) { var bytes = nic.GetPhysicalAddress().GetAddressBytes(); return string.Join(":", bytes.Select(b => b.ToString("X2"))); } } catch { } return "00:00:00:00:00:00"; } }