ServiceInitializer.cs 7.2 KB

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