using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; namespace XFEWarframe.Client; public sealed class PlayerPortalException(HttpStatusCode status, string message) : Exception(message) { public HttpStatusCode Status { get; } = status; } public sealed record PlayerProfile(string Id, string Email, string DisplayName, bool Online, string AvatarType = ""); public sealed record PlayerWallet(long RegularCredits, long PremiumCredits, long FusionPoints, long PrimeTokens = 0, long CrewShipFusionPoints = 0); public sealed record PlayerPortalInfo(bool RegistrationEnabled, bool CurrencyGrantEnabled, bool ItemGrantEnabled = false, string ServerName = "XFEWarframe", int ApiVersion = 0, bool EditingEnabled = false, string EditingRevision = "", bool RivenEditingEnabled = false); public sealed record PlayerSnapshot(PlayerProfile Profile, PlayerWallet Wallet, bool CurrencyGrantEnabled, bool ItemGrantEnabled = false, bool EditingEnabled = false, string EditingRevision = "", bool RivenEditingEnabled = false); public sealed record PlayerLogin(PlayerProfile Profile, PlayerWallet Wallet, bool CurrencyGrantEnabled, string Token, DateTimeOffset ExpiresAt, bool ItemGrantEnabled = false, bool EditingEnabled = false, string EditingRevision = "", bool RivenEditingEnabled = false); public sealed record PlayerInventory(PlayerProfile Profile, PlayerWallet Wallet, bool CurrencyGrantEnabled, int Total, string[] Categories, PlayerInventoryItem[] Items, bool ItemGrantEnabled = false, bool EditingEnabled = false, string EditingRevision = "", bool RivenEditingEnabled = false); public sealed record PlayerRegistered(PlayerProfile Profile); public sealed record PlayerEditorRevision(string Version, string Permissions, bool Enabled); public sealed record PlayerIdentityResult(bool Deleted, bool Reauthenticate); public sealed record PlayerCatalog(int Total, string[] Categories, PlayerCatalogItem[] Items); public sealed record PlayerCatalogItem(string Type, string Name, string Category, string Tags = ""); public sealed record PlayerItemGrant(string Type, int Count, string RequestId, DateTimeOffset RequestedAt) { public static PlayerItemGrant Create(string type, int count) => new(type, count, Guid.NewGuid().ToString("D"), DateTimeOffset.UtcNow); } public sealed record PlayerInventoryItem(string Id, string Type, string Name, string Category, long Count, long Xp, string Tags = ""); public sealed record PlayerWalletGrant(string Currency, long Amount, string RequestId, DateTimeOffset RequestedAt) { public static PlayerWalletGrant Create(string currency, long amount) => new(currency, amount, Guid.NewGuid().ToString("D"), DateTimeOffset.UtcNow); } public sealed class PlayerPortalClient : IDisposable { private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); private readonly HttpClient http; private string? token; public string Origin { get; } public string ItemLanguage { get; set; } = "zh"; private string LanguageQuery => "&lang=" + Uri.EscapeDataString(ItemLanguage); public bool IsAuthenticated => token is not null; public PlayerPortalClient(string origin, HttpMessageHandler? handler = null) { Origin = ClientProtocol.NormalizeServer(origin); http = new(handler ?? new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(20) }; } public Task InfoAsync(CancellationToken cancellation = default) => SendAsync("info", null, false, cancellation); public Task LoginAsync(string email, string password, CancellationToken cancellation = default) => AuthenticateAsync("login", new { email, password }, cancellation); public Task RegisterAsync(string email, string password, string displayName, CancellationToken cancellation = default) => AuthenticateAsync("register", new { email, password, displayName }, cancellation); public Task RegisterAccountAsync(string email, string password, string displayName, CancellationToken cancellation = default) => SendAsync("register", new { email, password, displayName, signIn = false }, false, cancellation); private async Task AuthenticateAsync(string path, object body, CancellationToken cancellation) { token = null; var result = await SendAsync(path, body, false, cancellation); if (result.Token.Length != 64 || result.Profile is null || result.Wallet is null) throw new InvalidDataException("服务器返回的登录信息无效。"); token = result.Token; return result; } public Task RivenCatalogAsync(string? family, CancellationToken cancellation = default) => SendAsync("riven/catalog?lang=" + Uri.EscapeDataString(ItemLanguage) + (family is null ? "" : "&type=" + Uri.EscapeDataString(family)), null, true, cancellation); public Task CalculateRivenAsync(JsonElement body, CancellationToken cancellation = default) => SendAsync("riven/calculate?lang=" + Uri.EscapeDataString(ItemLanguage), body, true, cancellation); public Task MeAsync(CancellationToken cancellation = default) => SendAsync("me", null, true, cancellation); public Task EditIdentityAsync(string action, string currentPassword, string value, CancellationToken cancellation = default) => SendAsync("identity", new { action, currentPassword, value }, true, cancellation); public Task ReadEditorAsync(string category, string query = "", string? item = null, int skip = 0, CancellationToken cancellation = default) => SendAsync($"editor?category={Uri.EscapeDataString(category)}&q={Uri.EscapeDataString(query)}&skip={skip}" + (item is null ? "" : "&item=" + Uri.EscapeDataString(item)) + LanguageQuery, null, true, cancellation); public Task SaveEditorAsync(JsonElement body, CancellationToken cancellation = default) => SendAsync("editor", body, true, cancellation); public Task EditorRevisionAsync(CancellationToken cancellation = default) => SendAsync("editor/revision", null, true, cancellation); public Task ExportArchiveAsync(CancellationToken cancellation = default) => SendAsync("archive", null, true, cancellation); public Task ImportArchiveAsync(JsonElement body, CancellationToken cancellation = default) => SendAsync("archive", body, true, cancellation); public Task InventoryAsync(string query = "", string category = "", int skip = 0, CancellationToken cancellation = default) => SendAsync($"inventory?q={Uri.EscapeDataString(query)}&category={Uri.EscapeDataString(category)}&skip={skip}" + LanguageQuery, null, true, cancellation); public Task GrantAsync(PlayerWalletGrant request, CancellationToken cancellation = default) => SendAsync("wallet/grant", request, true, cancellation); public Task GrantItemAsync(PlayerItemGrant request, CancellationToken cancellation = default) => SendAsync("items/grant", request, true, cancellation); public Task CatalogAsync(string query = "", string category = "", int skip = 0, CancellationToken cancellation = default) => SendAsync($"catalog?q={Uri.EscapeDataString(query)}&category={Uri.EscapeDataString(category)}&skip={skip}" + LanguageQuery, null, true, cancellation); public async Task AvatarAsync(CancellationToken cancellation = default) { if (token is null) return null; using var request = new HttpRequestMessage(HttpMethod.Get, Origin + "/player/v1/avatar"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellation); if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is > 2_000_000) return null; await using var stream = await response.Content.ReadAsStreamAsync(cancellation); using var data = new MemoryStream(); var buffer = new byte[8192]; int read; while ((read = await stream.ReadAsync(buffer, cancellation)) != 0) { if (data.Length + read > 2_000_000) return null; data.Write(buffer, 0, read); } return data.ToArray(); } public async Task LogoutAsync(CancellationToken cancellation = default) { try { if (token is not null) await SendAsync("logout", new { }, true, cancellation); } finally { token = null; } } private async Task SendAsync(string path, object? body, bool authenticated, CancellationToken cancellation) { if (authenticated && token is null) throw new PlayerPortalException(HttpStatusCode.Unauthorized, "请先登录玩家账号。"); // Keep path-shaped query values compatible with ServerInteractive's transport parser. var queryAt = path.IndexOf('?'); if (queryAt >= 0) path = path[..queryAt] + path[queryAt..].Replace("%2F", "/", StringComparison.OrdinalIgnoreCase); using var request = new HttpRequestMessage(body is null ? HttpMethod.Get : HttpMethod.Post, Origin + "/player/v1/" + path); if (body is not null) request.Content = JsonContent.Create(body, options: Json); if (authenticated) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellation).ConfigureAwait(false); var content = await response.Content.ReadAsStringAsync(cancellation).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { if (response.StatusCode == HttpStatusCode.Unauthorized) token = null; var error = $"服务器返回 {(int)response.StatusCode},请检查地址与服务版本。"; try { using var document = JsonDocument.Parse(content); error = document.RootElement.GetProperty("error").GetString() ?? error; } catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException) { } if (response.StatusCode == HttpStatusCode.NotFound) error = "服务器版本过旧,未提供玩家账号接口。请启动同一发行包中的新版 Server。"; throw new PlayerPortalException(response.StatusCode, error); } return await Task.Run(() => JsonSerializer.Deserialize(content, Json) ?? throw new InvalidDataException("服务器返回空数据。"), cancellation).ConfigureAwait(false); } public void Dispose() { token = null; http.Dispose(); } }