ServiceInitializer.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. var httpClient = _clientFactory.CreateClient();
  90. httpClient.Timeout = TimeSpan.FromSeconds(10);
  91. HttpResponseMessage message = await httpClient.GetAsync("https://teammodelos.blob.core.chinacloudapi.cn/0-public/schools.json");
  92. if (message.IsSuccessStatusCode)
  93. {
  94. // 读取响应内容
  95. string content = await message.Content.ReadAsStringAsync();
  96. // 保存文件的路径
  97. string filePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot", "package", "schools.json");
  98. // 确保目录存在
  99. Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
  100. // 将内容写入文件
  101. await File.WriteAllTextAsync(filePath, content);
  102. }
  103. else
  104. {
  105. throw new Exception($"Failed to download data. Status code: {message.StatusCode}");
  106. }
  107. }
  108. _connectionService.notifyUrl = notify == 1 ? notifyUrl : null;
  109. _connectionService.notifyIsConnected = notify == 1;
  110. // 单例模式存储云端数据中心连接状态
  111. _connectionService.centerUrl = hybrid == 1 ?centerUrl : null;
  112. _connectionService.centerIsConnected = hybrid == 1;
  113. ServerDevice serverDevice = IndexService.GetServerDevice(remote, region);
  114. IEnumerable<School> schools = _liteDBFactory.GetLiteDatabase().GetCollection<School>().FindAll();
  115. School? school = schools?.FirstOrDefault();
  116. serverDevice.school = school;
  117. _cache.Set(Constant._KeyServerDevice, serverDevice);
  118. _liteDBFactory.GetLiteDatabase().GetCollection<ServerDevice>().Upsert(serverDevice);
  119. _connectionService.serverDevice = serverDevice;
  120. _lifetime.ApplicationStarted.Register(() =>
  121. {
  122. var serverDevice= _cache.Get<ServerDevice>(Constant._KeyServerDevice);
  123. var _url = _server.Features.Get<IServerAddressesFeature>()?.Addresses;
  124. if (_url!.IsNotEmpty())
  125. {
  126. List<UriInfo> ports = new List<UriInfo>();
  127. foreach (var url in _url!)
  128. {
  129. Uri uri = new Uri(url);
  130. serverDevice.uris.Add(new UriInfo { port= uri.Port, protocol= uri.Scheme });
  131. }
  132. }
  133. else
  134. {
  135. throw new Exception("未获取到端口信息!");
  136. }
  137. _logger.LogInformation($"服务端设备信息:{JsonSerializer.Serialize(serverDevice, options: new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) })}");
  138. _cache.Set(Constant._KeyServerDevice, serverDevice);
  139. });
  140. // 退出程序
  141. _lifetime.ApplicationStopping.Register(() =>
  142. {
  143. Console.WriteLine("The application is stopping. Performing cleanup...");
  144. // 在这里添加清理资源、保存数据等逻辑
  145. });
  146. }
  147. }
  148. }