using IES.ExamServer.Services; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.Extensions.Caching.Memory; using System.Text.Encodings.Web; using System.Text.Json.Nodes; using System.Text.Json; using System.Text.Unicode; using IES.ExamServer.Helper; using IES.ExamServer.Models; using System.Security.Policy; using IES.ExamServer.Helpers; namespace IES.ExamServer.DI { public class ServiceInitializer { private readonly IMemoryCache _cache; private readonly IHttpClientFactory _clientFactory; private readonly LiteDBFactory _liteDBFactory; private readonly IConfiguration _configuration; private readonly CenterServiceConnectionService _connectionService; private readonly IHostApplicationLifetime _lifetime; private readonly IServer _server; private readonly ILogger _logger; public ServiceInitializer(IMemoryCache cache, IHttpClientFactory clientFactory, LiteDBFactory liteDBFactory, IConfiguration configuration, CenterServiceConnectionService connectionService, IHostApplicationLifetime lifetime, IServer server, ILogger logger) { _cache = cache; _clientFactory = clientFactory; _liteDBFactory = liteDBFactory; _configuration = configuration; _connectionService = connectionService; _lifetime = lifetime; _server = server; _logger = logger; } public async Task InitializeAsync() { JsonNode? data = null; int hybrid = 0, notify=0; string remote = "127.0.0.1"; string region = "局域网·内网"; string? centerUrl = _configuration.GetValue("ExamServer:CenterUrl"); try { var httpClient = _clientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromSeconds(10); HttpResponseMessage message = await httpClient.PostAsJsonAsync($"{centerUrl}/core/system-info", new { }); if (message.IsSuccessStatusCode) { string content = await message.Content.ReadAsStringAsync(); data = JsonSerializer.Deserialize(content); data!["centerUrl"] = centerUrl; _cache.Set(Constant._KeyServerCenter, data); remote = $"{data["ip"]}"; region = $"{data["region"]}"; hybrid = 1; } } catch (Exception ex) { // 云端服务连接失败 hybrid = 0; } string? notifyUrl = _configuration.GetValue("ExamServer:NotifyUrl"); try { var httpClient = _clientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromSeconds(10); HttpResponseMessage message = await httpClient.PostAsJsonAsync($"{notifyUrl}/index/device-init", new { fp= Guid.NewGuid().ToString() }); if (message.IsSuccessStatusCode) { notify = 1; } } catch (Exception ex) { // 云端服务连接失败 notify = 0; } if (hybrid==1) { try { string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "schools.json"); if (!File.Exists(filePath)) { var httpClient = _clientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromSeconds(10); HttpResponseMessage message = await httpClient.GetAsync("https://teammodelos.blob.core.chinacloudapi.cn/0-public/schools.json"); if (message.IsSuccessStatusCode) { // 读取响应内容 string content = await message.Content.ReadAsStringAsync(); // 保存文件的路径 // 确保目录存在 Directory.CreateDirectory(Path.GetDirectoryName(filePath)!); // 将内容写入文件 await File.WriteAllTextAsync(filePath, content); } //else //{ // // throw new Exception($"Failed to download data. Status code: {message.StatusCode}"); //} } } catch (Exception ex) { _logger.LogError(ex.Message); } } _connectionService.musicUrl = _configuration.GetValue("ExamServer:MusicUrl"); _connectionService.notifyUrl = notify == 1 ? notifyUrl : null; _connectionService.notifyIsConnected = notify == 1; // 单例模式存储云端数据中心连接状态 _connectionService.centerUrl = hybrid == 1 ?centerUrl : null; _connectionService.centerIsConnected = hybrid == 1; ServerDevice serverDevice = IndexService.GetServerDevice(remote, region); IEnumerable schools = _liteDBFactory.GetLiteDatabase().GetCollection().FindAll(); School? school = schools?.FirstOrDefault(); serverDevice.school = school; _cache.Set(Constant._KeyServerDevice, serverDevice); _liteDBFactory.GetLiteDatabase().GetCollection().Upsert(serverDevice); _connectionService.serverDevice = serverDevice; await IndexService.ModifyHosts(null, _cache, _liteDBFactory, _connectionService); _lifetime.ApplicationStarted.Register(() => { var serverDevice= _cache.Get(Constant._KeyServerDevice); var _url = _server.Features.Get()?.Addresses; if (_url!.IsNotEmpty()) { List ports = new List(); foreach (var url in _url!) { Uri uri = new Uri(url); serverDevice.uris.Add(new UriInfo { port= uri.Port, protocol= uri.Scheme }); } } else { throw new Exception("未获取到端口信息!"); } _logger.LogInformation($"服务端设备信息:{JsonSerializer.Serialize(serverDevice, options: new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) })}"); _cache.Set(Constant._KeyServerDevice, serverDevice); }); // 退出程序 _lifetime.ApplicationStopping.Register(() => { Console.WriteLine("The application is stopping. Performing cleanup..."); // 在这里添加清理资源、保存数据等逻辑 }); } } }