using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace XFEWarframe.Client.Runtime;
public sealed class RuntimeControlClient : IDisposable
{
private readonly HttpClient http;
public RuntimeSession Session { get; }
public RuntimeControlClient(RuntimeSession session)
{
RuntimeDiscovery.Validate(session); Session = session;
http = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false }) { BaseAddress = new Uri(session.Endpoint), Timeout = TimeSpan.FromSeconds(3) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token);
}
public async Task<RuntimeStatus> StatusAsync(CancellationToken cancellation = default)
{
var status = await SendAsync("runtime/v1/status", null, RuntimeJson.Default.RuntimeStatus, cancellation).ConfigureAwait(false);
if (status.Instance != Session.Instance || status.ProcessId != Session.ProcessId) throw new InvalidDataException("运行时实例已改变,请重新连接。");
return status;
}
public Task<RuntimeLogs> LogsAsync(long cursor, CancellationToken cancellation = default) =>
SendAsync("runtime/v1/logs?after=" + cursor.ToString(System.Globalization.CultureInfo.InvariantCulture), null, RuntimeJson.Default.RuntimeLogs, cancellation);
public Task<RuntimeSettings> SettingsAsync(RuntimeSettings settings, CancellationToken cancellation = default) =>
SendAsync("runtime/v1/settings", JsonSerializer.Serialize(settings, RuntimeJson.Default.RuntimeSettings), RuntimeJson.Default.RuntimeSettings, cancellation);
public Task<RuntimeSaved> SaveAsync(CancellationToken cancellation = default) => SendAsync("runtime/v1/save", "{}", RuntimeJson.Default.RuntimeSaved, cancellation);
public Task<RuntimeSaved> ClearLogsAsync(CancellationToken cancellation = default) => SendAsync("runtime/v1/logs/clear", "{}", RuntimeJson.Default.RuntimeSaved, cancellation);
public Task<GameLoginStatus> LoginGameAsync(GameLoginRequest request, CancellationToken cancellation = default)
{
request.Validate();
return SendAsync("runtime/v1/account/login", JsonSerializer.Serialize(request, RuntimeJson.Default.GameLoginRequest), RuntimeJson.Default.GameLoginStatus, cancellation);
}
public Task<GameLoginStatus> GameLoginStatusAsync(CancellationToken cancellation = default) =>
SendAsync("runtime/v1/account/login", null, RuntimeJson.Default.GameLoginStatus, cancellation);
public Task<GameLoginStatus> CancelGameLoginAsync(string requestId, CancellationToken cancellation = default)
{
if (!Guid.TryParseExact(requestId, "N", out _)) throw new ArgumentException("Invalid login request ID.");
return SendAsync("runtime/v1/account/login/cancel", "{\"requestId\":\"" + requestId + "\"}", RuntimeJson.Default.GameLoginStatus, cancellation);
}
public Task<NativeCardCacheStatus> CacheCardsAsync(NativeCardCacheRequest request, CancellationToken cancellation = default) =>
SendAsync("runtime/v1/visuals/cards", JsonSerializer.Serialize(request, VisualCacheJson.Default.NativeCardCacheRequest), VisualCacheJson.Default.NativeCardCacheStatus, cancellation);
public Task<NativeCardCacheStatus> CardCacheStatusAsync(CancellationToken cancellation = default) =>
SendAsync("runtime/v1/visuals/cards", null, VisualCacheJson.Default.NativeCardCacheStatus, cancellation);
private async Task<T> SendAsync<T>(string path, string? json, JsonTypeInfo<T> type, CancellationToken cancellation)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); timeout.CancelAfter(TimeSpan.FromSeconds(3));
cancellation = timeout.Token;
using var request = new HttpRequestMessage(json is null ? HttpMethod.Get : HttpMethod.Post, path);
if (json is not null) request.Content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellation).ConfigureAwait(false);
if (response.Content.Headers.ContentLength > 1024 * 1024) throw new InvalidDataException("运行时响应过大。");
await using var input = await response.Content.ReadAsStreamAsync(cancellation).ConfigureAwait(false);
using var buffer = new MemoryStream(); var chunk = new byte[16384]; int read;
while ((read = await input.ReadAsync(chunk, cancellation).ConfigureAwait(false)) > 0)
{
if (buffer.Length + read > 1024 * 1024) throw new InvalidDataException("运行时响应过大。");
buffer.Write(chunk, 0, read);
}
var bytes = buffer.ToArray();
if (!response.IsSuccessStatusCode)
{
var error = JsonSerializer.Deserialize(bytes, RuntimeJson.Default.RuntimeError)?.Error;
throw new HttpRequestException(error ?? "运行时请求失败。", null, response.StatusCode);
}
return JsonSerializer.Deserialize(bytes, type) ?? throw new InvalidDataException("运行时返回了空响应。");
}
public void Dispose() => http.Dispose();
}
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace XFEWarframe.Client.Runtime;
public sealed class RuntimeControlClient : IDisposable
{
private readonly HttpClient http;
public RuntimeSession Session { get; }
public RuntimeControlClient(RuntimeSession session)
{
RuntimeDiscovery.Validate(session); Session = session;
http = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false }) { BaseAddress = new Uri(session.Endpoint), Timeout = TimeSpan.FromSeconds(3) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token);
}
public async Task<RuntimeStatus> StatusAsync(CancellationToken cancellation = default)
{
var status = await SendAsync("runtime/v1/status", null, RuntimeJson.Default.RuntimeStatus, cancellation).ConfigureAwait(false);
if (status.Instance != Session.Instance || status.ProcessId != Session.ProcessId) throw new InvalidDataException("运行时实例已改变,请重新连接。");
return status;
}
public Task<RuntimeLogs> LogsAsync(long cursor, CancellationToken cancellation = default) =>
SendAsync("runtime/v1/logs?after=" + cursor.ToString(System.Globalization.CultureInfo.InvariantCulture), null, RuntimeJson.Default.RuntimeLogs, cancellation);
public Task<RuntimeSettings> SettingsAsync(RuntimeSettings settings, CancellationToken cancellation = default) =>
SendAsync("runtime/v1/settings", JsonSerializer.Serialize(settings, RuntimeJson.Default.RuntimeSettings), RuntimeJson.Default.RuntimeSettings, cancellation);
public Task<RuntimeSaved> SaveAsync(CancellationToken cancellation = default) => SendAsync("runtime/v1/save", "{}", RuntimeJson.Default.RuntimeSaved, cancellation);
public Task<RuntimeSaved> ClearLogsAsync(CancellationToken cancellation = default) => SendAsync("runtime/v1/logs/clear", "{}", RuntimeJson.Default.RuntimeSaved, cancellation);
public Task<GameLoginStatus> LoginGameAsync(GameLoginRequest request, CancellationToken cancellation = default)
{
request.Validate();
return SendAsync("runtime/v1/account/login", JsonSerializer.Serialize(request, RuntimeJson.Default.GameLoginRequest), RuntimeJson.Default.GameLoginStatus, cancellation);
}
public Task<GameLoginStatus> GameLoginStatusAsync(CancellationToken cancellation = default) =>
SendAsync("runtime/v1/account/login", null, RuntimeJson.Default.GameLoginStatus, cancellation);
public Task<GameLoginStatus> CancelGameLoginAsync(string requestId, CancellationToken cancellation = default)
{
if (!Guid.TryParseExact(requestId, "N", out _)) throw new ArgumentException("Invalid login request ID.");
return SendAsync("runtime/v1/account/login/cancel", "{\"requestId\":\"" + requestId + "\"}", RuntimeJson.Default.GameLoginStatus, cancellation);
}
public Task<NativeCardCacheStatus> CacheCardsAsync(NativeCardCacheRequest request, CancellationToken cancellation = default) =>
SendAsync("runtime/v1/visuals/cards", JsonSerializer.Serialize(request, VisualCacheJson.Default.NativeCardCacheRequest), VisualCacheJson.Default.NativeCardCacheStatus, cancellation);
public Task<NativeCardCacheStatus> CardCacheStatusAsync(CancellationToken cancellation = default) =>
SendAsync("runtime/v1/visuals/cards", null, VisualCacheJson.Default.NativeCardCacheStatus, cancellation);
private async Task<T> SendAsync<T>(string path, string? json, JsonTypeInfo<T> type, CancellationToken cancellation)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); timeout.CancelAfter(TimeSpan.FromSeconds(3));
cancellation = timeout.Token;
using var request = new HttpRequestMessage(json is null ? HttpMethod.Get : HttpMethod.Post, path);
if (json is not null) request.Content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellation).ConfigureAwait(false);
if (response.Content.Headers.ContentLength > 1024 * 1024) throw new InvalidDataException("运行时响应过大。");
await using var input = await response.Content.ReadAsStreamAsync(cancellation).ConfigureAwait(false);
using var buffer = new MemoryStream(); var chunk = new byte[16384]; int read;
while ((read = await input.ReadAsync(chunk, cancellation).ConfigureAwait(false)) > 0)
{
if (buffer.Length + read > 1024 * 1024) throw new InvalidDataException("运行时响应过大。");
buffer.Write(chunk, 0, read);
}
var bytes = buffer.ToArray();
if (!response.IsSuccessStatusCode)
{
var error = JsonSerializer.Deserialize(bytes, RuntimeJson.Default.RuntimeError)?.Error;
throw new HttpRequestException(error ?? "运行时请求失败。", null, response.StatusCode);
}
return JsonSerializer.Deserialize(bytes, type) ?? throw new InvalidDataException("运行时返回了空响应。");
}
public void Dispose() => http.Dispose();
}