using System.ComponentModel; using System.Net; using System.Runtime.InteropServices.WindowsRuntime; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Media.Imaging; using Windows.Storage.Streams; using XFEExtension.NetCore.WinUIHelper.Implements.Services; using XFEExtension.NetCore.WinUIHelper.Utilities; using XFEWarframe.Client; using XFEWarframe.Player.Interface.Services; using XFEWarframe.Player.Models; using XFEWarframe.Player.Profiles.CrossVersionProfiles; using XFEWarframe.Player.Utilities; namespace XFEWarframe.Player.Implements.Services; public sealed class PlayerAccountService : GlobalServiceBase, IPlayerAccountService { private readonly IPlayerService player = ServiceManager.GetGlobalService()!; private PlayerPortalClient? client; private readonly SemaphoreSlim accountGate = new(1, 1); private PlayerWalletGrant? pendingGrant; private PlayerItemGrant? pendingItem; private readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromSeconds(15) }; private string avatarType = ""; private bool loadingAvatar; private readonly RememberedAccountStore rememberedAccounts = new(); private string? restoreAttemptedOrigin; private byte[]? protectedCredential; public PlayerAccountState State { get; } = new(); public PlayerAccountService() { player.State.PropertyChanged += ServerChanged; timer.Tick += Poll; } private async void Poll(object? sender, object args) { if (State.IsBusy || App.Lifetime.IsCancellationRequested) return; try { await InitializeAsync(); if (State.IsLoggedIn) await RefreshAsync(); } catch { State.CurrencyGrantEnabled = State.ItemGrantEnabled = State.RegistrationEnabled = State.EditingEnabled = State.RivenEditingEnabled = false; } } private void ServerChanged(object? sender, PropertyChangedEventArgs args) { if (args.PropertyName != nameof(ClientState.ServerUrl)) return; client?.Dispose(); client = null; player.State.ServerName = "尚未连接服务器"; ClearSession(); restoreAttemptedOrigin = null; State.AuthenticationNotice = ""; State.RegistrationEnabled = false; } private void ClearSession() { State.IsLoggedIn = false; State.DisplayName = "尚未登录"; State.Email = ""; State.AccountId = ""; State.Credits = State.Platinum = State.Endo = State.RegalAya = State.Dirac = 0; State.CurrencyGrantEnabled = State.ItemGrantEnabled = State.EditingEnabled = State.RivenEditingEnabled = false; State.EditingRevision = ""; State.Avatar = null; avatarType = ""; pendingItem = null; pendingGrant = null; protectedCredential = null; } private async Task RunAsync(Func> action, bool background = false) { await accountGate.WaitAsync(App.Lifetime); if (!background) State.IsBusy = true; try { await player.InitializeAsync(); var api = client ??= new PlayerPortalClient(player.State.ServerUrl); api.ItemLanguage = SystemProfile.ItemLanguage; var result = await action(api); if (!ReferenceEquals(api, client)) throw new OperationCanceledException("服务器地址已更改。"); return result; } catch (PlayerPortalException ex) when (ex.Status == HttpStatusCode.Unauthorized) { ClearSession(); restoreAttemptedOrigin = null; throw; } finally { if (!background) State.IsBusy = false; accountGate.Release(); } } public async Task InitializeAsync() { var result = await RunAsync(async api => { var info = await api.InfoAsync(App.Lifetime); PlayerLogin? login = null; if (SystemProfile.RememberAccount && !State.IsLoggedIn && restoreAttemptedOrigin != api.Origin) { restoreAttemptedOrigin = api.Origin; RememberedAccount? saved; try { saved = await rememberedAccounts.ReadAsync(api.Origin); } catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or System.Security.Cryptography.CryptographicException or System.Text.Json.JsonException or IOException or UnauthorizedAccessException) { saved = null; State.AuthenticationNotice = "无法读取本机保存的登录信息,请重新登录。"; } if (saved is not null && ReferenceEquals(api, client)) { try { login = await api.LoginAsync(saved.Email, saved.Password, App.Lifetime); protectedCredential = await rememberedAccounts.ProtectAsync(api.Origin, saved.Email, saved.Password); } catch (PlayerPortalException ex) when (ex.Status is HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) { rememberedAccounts.Delete(api.Origin); State.AuthenticationNotice = "保存的登录信息已失效,请重新登录。"; } catch { restoreAttemptedOrigin = null; throw; } } } return (Info: info, Login: login); }); var info = result.Info; State.RegistrationEnabled = info.RegistrationEnabled; State.CurrencyGrantEnabled = info.CurrencyGrantEnabled; State.ItemGrantEnabled = info.ItemGrantEnabled; player.State.ServerName = info.ServerName; if (result.Login is PlayerLogin login) { Apply(login.Profile, login.Wallet, login.CurrencyGrantEnabled, login.ItemGrantEnabled, login.EditingEnabled, login.EditingRevision, login.RivenEditingEnabled); SaveEmail(login.Profile.Email); } timer.Start(); } public async Task LoginAsync(string email, string password) { ClearSession(); var login = await RunAsync(async api => { var result = await api.LoginAsync(email.Trim(), password, App.Lifetime); var encrypted = await rememberedAccounts.ProtectAsync(api.Origin, result.Profile.Email, password); if (!ReferenceEquals(api, client)) throw new OperationCanceledException("服务器地址已更改。"); protectedCredential = encrypted; restoreAttemptedOrigin = api.Origin; if (SystemProfile.RememberAccount) await rememberedAccounts.SaveAsync(api.Origin, encrypted); else rememberedAccounts.Delete(api.Origin); return result; }); Apply(login.Profile, login.Wallet, login.CurrencyGrantEnabled, login.ItemGrantEnabled, login.EditingEnabled, login.EditingRevision, login.RivenEditingEnabled); SaveEmail(login.Profile.Email); } public async Task RegisterAsync(string email, string password, string displayName) { ClearSession(); var login = await RunAsync(api => api.RegisterAccountAsync(email.Trim(), password, displayName.Trim(), App.Lifetime)); SaveEmail(login.Profile.Email); } private void SaveEmail(string email) { SystemProfile.PlayerEmail = SystemProfile.RememberAccount ? email : ""; player.SavePreferences(); } public async Task SetRememberAccountAsync(bool remember) { await accountGate.WaitAsync(App.Lifetime); try { if (!remember) await Task.Run(rememberedAccounts.DeleteAll); else if (State.IsLoggedIn && client is not null && protectedCredential is not null) await rememberedAccounts.SaveAsync(client.Origin, protectedCredential); SystemProfile.RememberAccount = remember; SystemProfile.PlayerEmail = remember ? (State.IsLoggedIn ? State.Email : SystemProfile.PlayerEmail) : ""; player.SavePreferences(); } finally { accountGate.Release(); } } public async Task GameLoginAsync(CancellationToken cancellation = default) { await accountGate.WaitAsync(cancellation); try { var api = client; if (!State.IsLoggedIn || api is null || protectedCredential is null) throw new InvalidOperationException("请先在启动器中登录账号。"); var saved = await rememberedAccounts.UnprotectAsync(protectedCredential, api.Origin); cancellation.ThrowIfCancellationRequested(); if (saved is null || !ReferenceEquals(api, client) || !State.IsLoggedIn || saved.Email != State.Email) throw new OperationCanceledException("账号或服务器已更改,请重新启动游戏。", cancellation); var digest = new Org.BouncyCastle.Crypto.Digests.WhirlpoolDigest(); var plain = System.Text.Encoding.UTF8.GetBytes(saved.Password); var hash = new byte[digest.GetDigestSize()]; try { digest.BlockUpdate(plain, 0, plain.Length); digest.DoFinal(hash, 0); return new(Guid.NewGuid().ToString("N"), api.Origin, saved.Email, Convert.ToHexStringLower(hash)); } finally { System.Security.Cryptography.CryptographicOperations.ZeroMemory(plain); System.Security.Cryptography.CryptographicOperations.ZeroMemory(hash); } } finally { accountGate.Release(); } } public async Task RefreshAsync() { var result = await RunAsync(api => api.MeAsync(App.Lifetime)); Apply(result.Profile, result.Wallet, result.CurrencyGrantEnabled, result.ItemGrantEnabled, result.EditingEnabled, result.EditingRevision, result.RivenEditingEnabled); } public async Task InventoryAsync(string query, string category, int skip) { var result = await RunAsync(api => api.InventoryAsync(query, category, skip, App.Lifetime)); Apply(result.Profile, result.Wallet, result.CurrencyGrantEnabled, result.ItemGrantEnabled, result.EditingEnabled, result.EditingRevision, result.RivenEditingEnabled); return result; } public async Task GrantAsync(string currency, long amount) { if (pendingGrant is not null && (pendingGrant.Currency != currency || pendingGrant.Amount != amount)) throw new InvalidOperationException("上次操作尚未确认,请先重试相同类型和数量。"); pendingGrant ??= PlayerWalletGrant.Create(currency, amount); try { var result = await RunAsync(api => api.GrantAsync(pendingGrant, App.Lifetime)); Apply(result.Profile, result.Wallet, result.CurrencyGrantEnabled, result.ItemGrantEnabled, result.EditingEnabled, result.EditingRevision, result.RivenEditingEnabled); pendingGrant = null; } catch (PlayerPortalException ex) when (ex.Status is HttpStatusCode.BadRequest or HttpStatusCode.Forbidden or HttpStatusCode.Conflict) { pendingGrant = null; if (ex.Status == HttpStatusCode.Forbidden) State.CurrencyGrantEnabled = false; throw; } } public Task CatalogAsync(string query, string category, int skip) => RunAsync(api => api.CatalogAsync(query, category, skip, App.Lifetime)); public async Task GrantItemAsync(string type, int count) { if (pendingItem is not null && (pendingItem.Type != type || pendingItem.Count != count)) throw new InvalidOperationException("上次操作尚未确认,请先重试相同物品和数量。"); pendingItem ??= PlayerItemGrant.Create(type, count); try { var result = await RunAsync(api => api.GrantItemAsync(pendingItem, App.Lifetime)); Apply(result.Profile, result.Wallet, result.CurrencyGrantEnabled, result.ItemGrantEnabled, result.EditingEnabled, result.EditingRevision, result.RivenEditingEnabled); pendingItem = null; } catch (PlayerPortalException ex) when (ex.Status is HttpStatusCode.BadRequest or HttpStatusCode.Forbidden or HttpStatusCode.Conflict) { pendingItem = null; if (ex.Status == HttpStatusCode.Forbidden) State.ItemGrantEnabled = false; throw; } } public async Task ReadEditorAsync(string category, string query, string? item, int skip) { var data = await RunAsync(api => api.ReadEditorAsync(category, query, item, skip, App.Lifetime)); return await Task.Run(() => Newtonsoft.Json.Linq.JObject.Parse(data.GetRawText()), App.Lifetime); } public async Task SaveEditorAsync(Newtonsoft.Json.Linq.JObject body) { var payload = await Task.Run(() => System.Text.Json.JsonSerializer.Deserialize(body.ToString(Newtonsoft.Json.Formatting.None)), App.Lifetime); var data = await RunAsync(api => api.SaveEditorAsync(payload, App.Lifetime)); return await Task.Run(() => Newtonsoft.Json.Linq.JObject.Parse(data.GetRawText()), App.Lifetime); } public Task EditorRevisionAsync() => RunAsync(api => api.EditorRevisionAsync(App.Lifetime), background: true); public async Task RivenCatalogAsync(string? family) { var data = await RunAsync(api => api.RivenCatalogAsync(family, App.Lifetime)); return await Task.Run(() => Newtonsoft.Json.Linq.JObject.Parse(data.GetRawText()), App.Lifetime); } public async Task ExportArchiveAsync() { var data = await RunAsync(api => api.ExportArchiveAsync(App.Lifetime)); return await Task.Run(() => Newtonsoft.Json.Linq.JObject.Parse(data.GetRawText()), App.Lifetime); } public async Task ImportArchiveAsync(string version, Newtonsoft.Json.Linq.JObject inventory) { var payload = await Task.Run(() => System.Text.Json.JsonSerializer.Deserialize(new Newtonsoft.Json.Linq.JObject { ["version"] = version, ["inventory"] = inventory.DeepClone() }.ToString(Newtonsoft.Json.Formatting.None)), App.Lifetime); var data = await RunAsync(api => api.ImportArchiveAsync(payload, App.Lifetime)); return await Task.Run(() => Newtonsoft.Json.Linq.JObject.Parse(data.GetRawText()), App.Lifetime); } public async Task CalculateRivenAsync(Newtonsoft.Json.Linq.JObject body) { var payload = await Task.Run(() => System.Text.Json.JsonSerializer.Deserialize(body.ToString(Newtonsoft.Json.Formatting.None)), App.Lifetime); var data = await RunAsync(api => api.CalculateRivenAsync(payload, App.Lifetime)); return await Task.Run(() => Newtonsoft.Json.Linq.JObject.Parse(data.GetRawText()), App.Lifetime); } private async Task LoadAvatarAsync(string type) { if (loadingAvatar || client is null) return; loadingAvatar = true; var api = client; avatarType = type; State.Avatar = null; try { var bytes = await api.AvatarAsync(App.Lifetime); if (bytes is null) return; using var stream = new InMemoryRandomAccessStream(); await stream.WriteAsync(bytes.AsBuffer()); stream.Seek(0); var bitmap = new BitmapImage(); await bitmap.SetSourceAsync(stream); if (ReferenceEquals(api, client) && State.IsLoggedIn && avatarType == type) State.Avatar = bitmap; } catch (Exception) { /* An unavailable avatar must not prevent account access. Retry on the next refresh. */ } finally { loadingAvatar = false; } } public async Task EditIdentityAsync(string action, string password, string value) { var email = State.Email; var result = await RunAsync(api => api.EditIdentityAsync(action, password, value, App.Lifetime)); if (result.Deleted || result.Reauthenticate) { if (client is not null) rememberedAccounts.Delete(client.Origin); ClearSession(); if (result.Reauthenticate) await LoginAsync(action == "email" ? value : email, action == "password" ? value : password); } else await RefreshAsync(); } public async Task LogoutAsync() { try { await RunAsync(async api => { restoreAttemptedOrigin = api.Origin; rememberedAccounts.Delete(api.Origin); await api.LogoutAsync(App.Lifetime); return true; }); } finally { ClearSession(); } } private void Apply(PlayerProfile profile, PlayerWallet wallet, bool grants, bool items, bool editing, string editingRevision, bool rivenEditing) { State.AccountId = profile.Id; State.DisplayName = profile.DisplayName; State.Email = profile.Email; State.Credits = wallet.RegularCredits; State.Platinum = wallet.PremiumCredits; State.Endo = wallet.FusionPoints; State.RegalAya = wallet.PrimeTokens; State.Dirac = wallet.CrewShipFusionPoints; State.CurrencyGrantEnabled = grants; State.ItemGrantEnabled = items; State.IsLoggedIn = true; State.EditingEnabled = editing; State.RivenEditingEnabled = rivenEditing; State.EditingRevision = editingRevision; State.AuthenticationNotice = ""; if (profile.AvatarType != avatarType || State.Avatar is null) _ = LoadAvatarAsync(profile.AvatarType); } public void Stop() { timer.Stop(); timer.Tick -= Poll; player.State.PropertyChanged -= ServerChanged; client?.Dispose(); client = null; ClearSession(); } }