123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158 |
- 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<ServiceInitializer> _logger;
- public ServiceInitializer(IMemoryCache cache,
- IHttpClientFactory clientFactory,
- LiteDBFactory liteDBFactory,
- IConfiguration configuration,
- CenterServiceConnectionService connectionService,
- IHostApplicationLifetime lifetime,
- IServer server,
- ILogger<ServiceInitializer> 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<string>("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<JsonNode>(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<string>("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)
- {
-
- 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();
- // 保存文件的路径
- string filePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot", "package", "schools.json");
- // 确保目录存在
- Directory.CreateDirectory(Path.GetDirectoryName(filePath)!);
- // 将内容写入文件
- await File.WriteAllTextAsync(filePath, content);
- }
- else
- {
- throw new Exception($"Failed to download data. Status code: {message.StatusCode}");
- }
- }
- _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<School> schools = _liteDBFactory.GetLiteDatabase().GetCollection<School>().FindAll();
- School? school = schools?.FirstOrDefault();
- serverDevice.school = school;
- _cache.Set(Constant._KeyServerDevice, serverDevice);
-
- _liteDBFactory.GetLiteDatabase().GetCollection<ServerDevice>().Upsert(serverDevice);
- _connectionService.serverDevice = serverDevice;
- _lifetime.ApplicationStarted.Register(() =>
- {
- var serverDevice= _cache.Get<ServerDevice>(Constant._KeyServerDevice);
- var _url = _server.Features.Get<IServerAddressesFeature>()?.Addresses;
- if (_url!.IsNotEmpty())
- {
- List<UriInfo> ports = new List<UriInfo>();
- 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...");
- // 在这里添加清理资源、保存数据等逻辑
- });
- }
- }
- }
|