XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
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<PlayerPortalInfo> InfoAsync(CancellationToken cancellation = default) => SendAsync<PlayerPortalInfo>("info", null, false, cancellation);
    public Task<PlayerLogin> LoginAsync(string email, string password, CancellationToken cancellation = default) => AuthenticateAsync("login", new { email, password }, cancellation);
    public Task<PlayerLogin> RegisterAsync(string email, string password, string displayName, CancellationToken cancellation = default) => AuthenticateAsync("register", new { email, password, displayName }, cancellation);
    public Task<PlayerRegistered> RegisterAccountAsync(string email, string password, string displayName, CancellationToken cancellation = default) =>
        SendAsync<PlayerRegistered>("register", new { email, password, displayName, signIn = false }, false, cancellation);
    private async Task<PlayerLogin> AuthenticateAsync(string path, object body, CancellationToken cancellation)
    {
        token = null;
        var result = await SendAsync<PlayerLogin>(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<JsonElement> RivenCatalogAsync(string? family, CancellationToken cancellation = default) => SendAsync<JsonElement>("riven/catalog?lang=" + Uri.EscapeDataString(ItemLanguage) + (family is null ? "" : "&type=" + Uri.EscapeDataString(family)), null, true, cancellation);
    public Task<JsonElement> CalculateRivenAsync(JsonElement body, CancellationToken cancellation = default) => SendAsync<JsonElement>("riven/calculate?lang=" + Uri.EscapeDataString(ItemLanguage), body, true, cancellation);
    public Task<PlayerSnapshot> MeAsync(CancellationToken cancellation = default) => SendAsync<PlayerSnapshot>("me", null, true, cancellation);
    public Task<PlayerIdentityResult> EditIdentityAsync(string action, string currentPassword, string value, CancellationToken cancellation = default) =>
        SendAsync<PlayerIdentityResult>("identity", new { action, currentPassword, value }, true, cancellation);
    public Task<JsonElement> ReadEditorAsync(string category, string query = "", string? item = null, int skip = 0, CancellationToken cancellation = default) =>
        SendAsync<JsonElement>($"editor?category={Uri.EscapeDataString(category)}&q={Uri.EscapeDataString(query)}&skip={skip}" + (item is null ? "" : "&item=" + Uri.EscapeDataString(item)) + LanguageQuery, null, true, cancellation);
    public Task<JsonElement> SaveEditorAsync(JsonElement body, CancellationToken cancellation = default) => SendAsync<JsonElement>("editor", body, true, cancellation);
    public Task<PlayerEditorRevision> EditorRevisionAsync(CancellationToken cancellation = default) => SendAsync<PlayerEditorRevision>("editor/revision", null, true, cancellation);
    public Task<JsonElement> ExportArchiveAsync(CancellationToken cancellation = default) => SendAsync<JsonElement>("archive", null, true, cancellation);
    public Task<JsonElement> ImportArchiveAsync(JsonElement body, CancellationToken cancellation = default) => SendAsync<JsonElement>("archive", body, true, cancellation);
    public Task<PlayerInventory> InventoryAsync(string query = "", string category = "", int skip = 0, CancellationToken cancellation = default) =>
        SendAsync<PlayerInventory>($"inventory?q={Uri.EscapeDataString(query)}&category={Uri.EscapeDataString(category)}&skip={skip}" + LanguageQuery, null, true, cancellation);
    public Task<PlayerSnapshot> GrantAsync(PlayerWalletGrant request, CancellationToken cancellation = default) => SendAsync<PlayerSnapshot>("wallet/grant", request, true, cancellation);
    public Task<PlayerSnapshot> GrantItemAsync(PlayerItemGrant request, CancellationToken cancellation = default) => SendAsync<PlayerSnapshot>("items/grant", request, true, cancellation);
    public Task<PlayerCatalog> CatalogAsync(string query = "", string category = "", int skip = 0, CancellationToken cancellation = default) =>
        SendAsync<PlayerCatalog>($"catalog?q={Uri.EscapeDataString(query)}&category={Uri.EscapeDataString(category)}&skip={skip}" + LanguageQuery, null, true, cancellation);
    public async Task<byte[]?> 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<JsonElement>("logout", new { }, true, cancellation); }
        finally { token = null; }
    }
    private async Task<T> SendAsync<T>(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<T>(content, Json) ?? throw new InvalidDataException("服务器返回空数据。"), cancellation).ConfigureAwait(false);
    }
    public void Dispose() { token = null; http.Dispose(); }
}