ServiceInitializer.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. using IES.ExamServer.Services;
  2. using Microsoft.AspNetCore.Hosting.Server.Features;
  3. using Microsoft.AspNetCore.Hosting.Server;
  4. using Microsoft.Extensions.Caching.Memory;
  5. using System.Text.Encodings.Web;
  6. using System.Text.Json.Nodes;
  7. using System.Text.Json;
  8. using System.Text.Unicode;
  9. using IES.ExamServer.Helper;
  10. using IES.ExamServer.Models;
  11. using System.Security.Policy;
  12. using IES.ExamServer.Helpers;
  13. using System.Text;
  14. namespace IES.ExamServer.DI
  15. {
  16. public class ServiceInitializer
  17. {
  18. private readonly IMemoryCache _cache;
  19. private readonly IHttpClientFactory _clientFactory;
  20. private readonly LiteDBFactory _liteDBFactory;
  21. private readonly IConfiguration _configuration;
  22. private readonly CenterServiceConnectionService _connectionService;
  23. private readonly IHostApplicationLifetime _lifetime;
  24. private readonly IServer _server;
  25. private readonly ILogger<ServiceInitializer> _logger;
  26. public ServiceInitializer(IMemoryCache cache,
  27. IHttpClientFactory clientFactory,
  28. LiteDBFactory liteDBFactory,
  29. IConfiguration configuration,
  30. CenterServiceConnectionService connectionService,
  31. IHostApplicationLifetime lifetime,
  32. IServer server,
  33. ILogger<ServiceInitializer> logger)
  34. {
  35. _cache = cache;
  36. _clientFactory = clientFactory;
  37. _liteDBFactory = liteDBFactory;
  38. _configuration = configuration;
  39. _connectionService = connectionService;
  40. _lifetime = lifetime;
  41. _server = server;
  42. _logger = logger;
  43. }
  44. public async Task InitializeAsync()
  45. {
  46. JsonNode? data = null;
  47. int hybrid = 0, notify=0;
  48. string remote = "127.0.0.1";
  49. string region = "局域网·内网";
  50. string? centerUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  51. try
  52. {
  53. var httpClient = _clientFactory.CreateClient();
  54. httpClient.Timeout = TimeSpan.FromSeconds(10);
  55. HttpResponseMessage message = await httpClient.PostAsJsonAsync($"{centerUrl}/core/system-info", new { });
  56. if (message.IsSuccessStatusCode)
  57. {
  58. string content = await message.Content.ReadAsStringAsync();
  59. data = JsonSerializer.Deserialize<JsonNode>(content);
  60. data!["centerUrl"] = centerUrl;
  61. _cache.Set(Constant._KeyServerCenter, data);
  62. remote = $"{data["ip"]}";
  63. region = $"{data["region"]}";
  64. hybrid = 1;
  65. }
  66. }
  67. catch (Exception ex)
  68. {
  69. // 云端服务连接失败
  70. hybrid = 0;
  71. }
  72. string? notifyUrl = _configuration.GetValue<string>("ExamServer:NotifyUrl");
  73. try
  74. {
  75. var httpClient = _clientFactory.CreateClient();
  76. httpClient.Timeout = TimeSpan.FromSeconds(10);
  77. HttpResponseMessage message = await httpClient.PostAsJsonAsync($"{notifyUrl}/index/device-init", new { fp= Guid.NewGuid().ToString() });
  78. if (message.IsSuccessStatusCode)
  79. {
  80. notify = 1;
  81. }
  82. }
  83. catch (Exception ex)
  84. {
  85. // 云端服务连接失败
  86. notify = 0;
  87. }
  88. if (hybrid==1)
  89. {
  90. try {
  91. string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "schools.json");
  92. if (!File.Exists(filePath))
  93. {
  94. var httpClient = _clientFactory.CreateClient();
  95. httpClient.Timeout = TimeSpan.FromSeconds(10);
  96. HttpResponseMessage message = await httpClient.GetAsync("https://teammodelos.blob.core.chinacloudapi.cn/0-public/schools.json");
  97. if (message.IsSuccessStatusCode)
  98. {
  99. // 读取响应内容
  100. string content = await message.Content.ReadAsStringAsync();
  101. // 保存文件的路径
  102. // 确保目录存在
  103. Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
  104. // 将内容写入文件
  105. await File.WriteAllTextAsync(filePath, content);
  106. }
  107. //else
  108. //{
  109. // // throw new Exception($"Failed to download data. Status code: {message.StatusCode}");
  110. //}
  111. }
  112. } catch (Exception ex) {
  113. _logger.LogError(ex.Message);
  114. }
  115. }
  116. _connectionService.musicUrl = _configuration.GetValue<string>("ExamServer:MusicUrl");
  117. _connectionService.notifyUrl = notify == 1 ? notifyUrl : null;
  118. _connectionService.notifyIsConnected = notify == 1;
  119. // 单例模式存储云端数据中心连接状态
  120. _connectionService.centerUrl = hybrid == 1 ?centerUrl : null;
  121. _connectionService.centerIsConnected = hybrid == 1;
  122. ServerDevice serverDevice = IndexService.GetServerDevice(remote, region);
  123. IEnumerable<School> schools = _liteDBFactory.GetLiteDatabase().GetCollection<School>().FindAll();
  124. School? school = schools?.FirstOrDefault();
  125. serverDevice.school = school;
  126. _cache.Set(Constant._KeyServerDevice, serverDevice);
  127. _liteDBFactory.GetLiteDatabase().GetCollection<ServerDevice>().Upsert(serverDevice);
  128. _connectionService.serverDevice = serverDevice;
  129. var dataModify = await IndexService.ModifyHosts(null, _cache, _liteDBFactory, _connectionService);
  130. var dataFile = new {
  131. dataModify.code_zip,
  132. dataModify.zip_msg,
  133. dataModify.code_cer,
  134. dataModify.cer_msg,
  135. dataModify.code_hosts,
  136. dataModify.hosts_msg,
  137. name = dataModify.primaryNetwork?.name,
  138. mac= dataModify.primaryNetwork?.mac,
  139. ip = dataModify.primaryNetwork?.ip,
  140. read=0
  141. };
  142. string startPath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot","start.json");
  143. await File.WriteAllTextAsync(startPath, dataFile.ToJsonString());
  144. StringBuilder sb = new StringBuilder();
  145. _lifetime.ApplicationStarted.Register(() =>
  146. {
  147. var serverDevice= _cache.Get<ServerDevice>(Constant._KeyServerDevice);
  148. var _url = _server.Features.Get<IServerAddressesFeature>()?.Addresses;
  149. if (_url!.IsNotEmpty())
  150. {
  151. List<UriInfo> ports = new List<UriInfo>();
  152. foreach (var url in _url!)
  153. {
  154. Uri uri = new Uri(url);
  155. serverDevice.uris.Add(new UriInfo { port= uri.Port, protocol= uri.Scheme });
  156. }
  157. }
  158. else
  159. {
  160. throw new Exception("未获取到端口信息!");
  161. }
  162. _logger.LogInformation($"服务端设备信息:{JsonSerializer.Serialize(serverDevice, options: new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) })}");
  163. _cache.Set(Constant._KeyServerDevice, serverDevice);
  164. });
  165. // 退出程序
  166. _lifetime.ApplicationStopping.Register(() =>
  167. {
  168. Console.WriteLine("The application is stopping. Performing cleanup...");
  169. // 在这里添加清理资源、保存数据等逻辑
  170. });
  171. }
  172. }
  173. }