#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Api;
///
/// Typed client for API access.
///
public class ApiHttpClient : IApiHttpClient
{
private readonly HttpClient _httpClient;
private readonly HttpContext? _httpContext;
private readonly JsonSerializerOptions _jsonOptions;
///
/// Initializes a new instance of the class.
///
/// Injected HttpClient for interacting with the API.
/// Injected service for providing the current HTTP context.
/// Injected server configuration application settings.
public ApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot serverConfigurationOptions)
{
_httpClient = httpClient;
_httpContext = httpContextAccessor.HttpContext;
// read the API server configuration values from the configuration, and assign them to the injected client
ServerConfigurationDto serverConfiguration = serverConfigurationOptions.Value;
httpClient.BaseAddress = new Uri($"{serverConfiguration.BaseAddress}:{serverConfiguration.Port}/api/v{serverConfiguration.ApiVersion}/");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter() }
};
}
///
/// Sends a GET request to the specified as an asynchronous operation and returns the result.
///
/// The expected type of the response content.
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the GET request.
public async Task GetAsync(string endpoint, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
///
/// Sends a GET request to the specified as an asynchronous operation and returns the result as a streamable response.
///
/// The expected type of the response content.
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
/// An object, which allows for asynchronous iteration over the deserialized items.
public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
// send the request and expect only headers initially - this prevents the client from buffering the entire response
using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
// Deserialize the JSON content asynchronously as an enumerable of TResponse items
await foreach (TResponse? item in JsonSerializer.DeserializeAsyncEnumerable(stream, _jsonOptions, cancellationToken).ConfigureAwait(false))
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return item;
}
}
///
/// Sends a GET request to the specified as an asynchronous operation and returns the result.
///
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
/// A model containing the deserialized blob.
public async Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
// read the content as a string, for error messages
string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
ProblemDetailsDto? problemDetails = null;
try
{
problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
}
catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ }
throw new ApiException(problemDetails, response.StatusCode);
}
// if the response is successful, read it as a byte array
byte[] responseContent = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
string contentType = response.Content.Headers.ContentType?.ToString() ?? "application/octet-stream";
return new BlobDataDto { Data = responseContent, ContentType = contentType };
}
///
/// Sends a DELETE request to the specified as an asynchronous operation.
///
/// The API endpoint where the request is being sent.
/// Cancellation token that can be used to stop the execution.
public async Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = new(HttpMethod.Delete, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
//return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
// send the HTTP request and read the response
HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
ProblemDetailsDto? problemDetails = null;
string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
// attempt to deserialize the response content to ProblemDetailsDto if the request fails
try
{
problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
}
catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ }
throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath);
}
}
///
/// Sends a PUT request to the specified as an asynchronous operation and returns the result.
///
/// The expected type of the response content.
/// The expected type of the payload content.
/// The API endpoint where the request is being sent.
/// The data to be serialized and send to the API.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the PUT request.
public async Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = new(HttpMethod.Put, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
///
/// Sends a POST request to the specified as an asynchronous operation and returns the result.
///
/// The expected type of the response content.
/// The expected type of the payload content.
/// The API endpoint where the request is being sent.
/// The data to be serialized and sent to the API.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response containing the result of the POST request.
public async Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = new(HttpMethod.Post, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
///
/// Sends an HTTP request and deserializes the response into the specified type if the request is successful.
/// If the request fails, it attempts to deserialize the response content into a and throws an .
///
/// The expected type of the response content.
/// The to be sent.
/// Cancellation token that can be used to stop the execution.
/// The deserialized response content as an object of type .
/// Thrown if the response is not successful, with the if available.
private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// send the HTTP request and read the response
HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
// if the response is successful, deserialize the content to TResponse and return it
if (response.IsSuccessStatusCode)
{
// handle empty content case
if (string.IsNullOrEmpty(content))
return default!;
return JsonSerializer.Deserialize(content, _jsonOptions)!;
}
else
{
ProblemDetailsDto? problemDetails = null;
// attempt to deserialize the response content to ProblemDetailsDto if the request fails
try
{
problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
}
catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ }
throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath);
}
}
///
/// Retrieves the authentication header for the current user, if available.
///
///
/// An with a Bearer token if the user's token is found, otherwise.
///
private AuthenticationHeaderValue? GetAuthenticationHeader()
{
string? token = _httpContext?.User?.FindFirst("Token")?.Value;
return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null;
}
}