using Microsoft.UI.Xaml; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using XFEExtension.NetCore.WinUIHelper.Implements.Services; using XFEExtension.NetCore.WinUIHelper.Utilities; using XFEWarframe.Admin.Interface.Services; using XFEWarframe.Admin.Models; using XFEWarframe.Admin.Profiles.CrossVersionProfiles; using XFEWarframe.Admin.Utilities; namespace XFEWarframe.Admin.Implements.Services; public sealed class AdminService : GlobalServiceBase, IAdminService { private readonly ApiClient api = new(); private readonly LocalServer local = new(); private readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromSeconds(2) }; private bool initialized; private Task? refreshTask; private Task? polling; public AdminState State { get; } = new(); public string LocalRoot => local.Root; public async Task InitializeAsync() { if (!initialized) { State.Address = SystemProfile.ServerUrl; // Only load local credentials when the saved connection points to loopback. if (local.HasConfiguration && Uri.TryCreate(State.Address, UriKind.Absolute, out var uri) && uri.IsLoopback) ReadLocalConfiguration(); timer.Tick += Tick; initialized = true; timer.Start(); } await RefreshAsync(); } private async void Tick(object? sender, object args) { if (refreshTask is { IsCompleted: false } || App.Lifetime.IsCancellationRequested) return; polling = PollAsync(); await polling; } private async Task PollAsync() { try { await RefreshAsync(); } catch (OperationCanceledException) { } catch { /* Connection status is updated by RefreshAsync; avoid repeating repeated polling toasts. */ } } private void ConfigureClient() { api.Address = State.Address.Trim().TrimEnd('/'); api.Token = State.Token; } public Task RefreshAsync() => refreshTask is { IsCompleted: false } ? refreshTask : refreshTask = RefreshCoreAsync(); private async Task RefreshCoreAsync() { try { ConfigureClient(); State.Apply((JObject)await api.Get("snapshot", App.Lifetime)); } catch { State.Connected = false; State.Status = "服务器未连接"; State.LastRefresh = "检查连接设置,或启动本地服务"; throw; } } public async Task ConnectAsync() { ConfigureClient(); // An explicit connection always validates the submitted credentials even during a background poll. State.Apply((JObject)await api.Get("snapshot", App.Lifetime)); SystemProfile.ServerUrl = api.Address; SystemProfile.SaveProfile(); } public void ReadLocalConfiguration() { if (!local.HasConfiguration) throw new FileNotFoundException("本地服务器尚未生成配置,请先启动服务。", Path.Combine(local.Root, "server.json")); local.ReadConnection(api); State.Address = api.Address; State.Token = api.Token; } public async Task StartLocalAsync() { local.Start(); Exception? failure = null; for (var attempt = 0; attempt < 20; attempt++) { await Task.Delay(500, App.Lifetime); try { ReadLocalConfiguration(); await ConnectAsync(); return; } catch (Exception ex) when (ex is not OperationCanceledException) { failure = ex; } } throw new InvalidOperationException("本地服务器未能完成启动。请检查运行目录中的日志。", failure); } public Task GetAsync(string path) { ConfigureClient(); return api.Get(path + (path.Contains('?') ? "&" : "?") + "lang=" + Uri.EscapeDataString(SystemProfile.ItemLanguage), App.Lifetime); } public Task PostAsync(string path, object body) { ConfigureClient(); return api.Post(path, body, App.Lifetime); } public async Task ExportAsync(JToken data, string name) { var interaction = ServiceManager.GetGlobalService()!; var path = await interaction.SaveJsonAsync(name); if (path is not null) await Task.Run(async () => await File.WriteAllTextAsync(path, data.ToString(Formatting.Indented), App.Lifetime), App.Lifetime); } public async Task ReadInventoryFileAsync() { var interaction = ServiceManager.GetGlobalService()!; var path = await interaction.OpenJsonAsync(); if (path is null) return null; if (new FileInfo(path).Length > 16 * 1024 * 1024) throw new InvalidOperationException("文件不能超过 16 MB。"); return await Task.Run(async () => JObject.Parse(await File.ReadAllTextAsync(path, App.Lifetime)), App.Lifetime); } public async Task StopAsync() { timer.Stop(); timer.Tick -= Tick; try { if (polling is not null) await polling; } finally { api.Dispose(); } } }