Replaces the custom EmptyRequest with explicit API client operations

Removes the Web-specific EmptyRequest record struct and keeps FastEndpoints.EmptyRequest only as an endpoint request DTO.

Adds bodyless and response-ignoring client overloads, centralizes request construction and response disposal, and separates stale-session failures from generic 404 responses.

Updates the API client stub and tests, including regression coverage for non-empty response bodies, overload selection, and crafted theme asset paths.
This commit is contained in:
BinaryAlley committed 2026-11-20 08:52:59 +02:00
1 parent c1dd08706c
commit 0a86f1a70b
70 files changed
+679 -384

No files matched your search

@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}</c> route.
/// </summary>
public class GetAlbumEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
public class GetAlbumEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetAlbumQuery, Result<AlbumResponse>> _getAlbumQueryHandler;
@@ -45,7 +45,7 @@ public class GetAlbumEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
@@ -17,7 +17,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks</c> route.
/// </summary>
public class GetAlbumTracksEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
public class GetAlbumTracksEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetAlbumTracksQuery, Result<IReadOnlyList<TrackResponse>>> _getAlbumTracksQueryHandler;
@@ -46,7 +46,7 @@ public class GetAlbumTracksEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, I
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}</c> route.
/// </summary>
public class GetArtistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
public class GetArtistEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetArtistQuery, Result<ArtistResponse>> _getArtistQueryHandler;
@@ -45,7 +45,7 @@ public class GetArtistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResul
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
@@ -17,7 +17,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums</c> route.
/// </summary>
public class GetArtistAlbumsEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
public class GetArtistAlbumsEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetArtistAlbumsQuery, Result<IReadOnlyList<AlbumResponse>>> _getArtistAlbumsQueryHandler;
@@ -46,7 +46,7 @@ public class GetArtistAlbumsEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest,
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}</c> route.
/// </summary>
public class GetTrackEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
public class GetTrackEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetTrackQuery, Result<TrackResponse>> _getTrackQueryHandler;
@@ -45,7 +45,7 @@ public class GetTrackEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
@@ -60,12 +60,10 @@ public class ApiHttpClient : IApiHttpClient
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the GET request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task<TResponse> GetAsync<TResponse>(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 HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint);
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
@@ -78,10 +76,7 @@ public class ApiHttpClient : IApiHttpClient
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(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;
using HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint);
// 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();
@@ -100,25 +95,16 @@ public class ApiHttpClient : IApiHttpClient
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A model containing the deserialized blob.</returns>
/// <returns>A model containing the raw blob bytes and their content type.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task<BlobDataDto> 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 HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint);
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<ProblemDetailsDto>(content, _jsonOptions);
}
catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ }
throw new ApiException(problemDetails, response.StatusCode);
throw CreateApiException(content, response, request);
}
// If the response is successful, read it as a byte array.
byte[] responseContent = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
@@ -127,30 +113,29 @@ public class ApiHttpClient : IApiHttpClient
}
/// <summary>
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation.
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
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;
// 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<ProblemDetailsDto>(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);
}
using HttpRequestMessage request = CreateRequest(HttpMethod.Delete, endpoint);
await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
/// </summary>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task PutIgnoringResponseAsync<TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Put, endpoint, data);
await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -159,35 +144,40 @@ public class ApiHttpClient : IApiHttpClient
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and send to the API.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task<TResponse> PutAsync<TResponse, TModel>(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");
using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Put, endpoint, data);
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// Sends a PUT request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation, and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="fileStream">The stream of the file to upload, or <see langword="null"/> to send a multipart form without any file.</param>
/// <param name="fileName">The name of the file to upload, or <see langword="null"/> when no file is sent.</param>
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
/// <returns>The deserialized response containing the result of the PUT request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream? fileStream, string? fileName, string fieldName, 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");
using MultipartFormDataContent form = [];
if (fileStream is not null)
{
// The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known.
StreamContent fileContent = new(fileStream);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, fieldName, fileName ?? string.Empty);
}
using HttpRequestMessage request = CreateRequest(HttpMethod.Put, endpoint);
request.Content = form;
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
@@ -201,6 +191,7 @@ public class ApiHttpClient : IApiHttpClient
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task<TResponse> PostMultipartAsync<TResponse>(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default)
{
// The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known.
@@ -209,50 +200,116 @@ public class ApiHttpClient : IApiHttpClient
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, fieldName, fileName);
using HttpRequestMessage request = new(HttpMethod.Post, endpoint)
{
Content = form
};
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint);
request.Content = form;
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends a PUT request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint);
await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation, and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="fileStream">The stream of the file to upload, or <see langword="null"/> to send a multipart form without any file.</param>
/// <param name="fileName">The name of the file to upload, or <see langword="null"/> when no file is sent.</param>
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
public async Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default)
/// <returns>The deserialized response containing the result of the POST request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task<TResponse> PostAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default)
{
using MultipartFormDataContent form = [];
if (fileStream is not null)
{
// The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known.
StreamContent fileContent = new(fileStream);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, fieldName, fileName ?? string.Empty);
}
using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint);
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
using HttpRequestMessage request = new(HttpMethod.Put, endpoint)
{
Content = form
};
/// <summary>
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
/// </summary>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task PostIgnoringResponseAsync<TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Post, endpoint, data);
await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
{
using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Post, endpoint, data);
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates an HTTP request for the specified <paramref name="method"/> and <paramref name="endpoint"/>.
/// </summary>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <returns>The created <see cref="HttpRequestMessage"/>.</returns>
private HttpRequestMessage CreateRequest(HttpMethod method, string endpoint)
{
HttpRequestMessage request = new(method, endpoint);
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
return request;
}
/// <summary>
/// Creates an HTTP request for the specified <paramref name="method"/> and <paramref name="endpoint"/>, with the serialized <paramref name="data"/> as its JSON payload.
/// </summary>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <returns>The created <see cref="HttpRequestMessage"/>.</returns>
private HttpRequestMessage CreateRequestWithPayload<TModel>(HttpMethod method, string endpoint, TModel data)
{
HttpRequestMessage request = CreateRequest(method, endpoint);
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
return request;
}
/// <summary>
/// Sends an HTTP request and reads the response content.
/// If the request fails, it attempts to deserialize the response content into a <see cref="ProblemDetailsDto"/> and throws an <see cref="ApiException"/>.
/// </summary>
/// <param name="request">The <see cref="HttpRequestMessage"/> to be sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The raw response content.</returns>
/// <exception cref="ApiException">Thrown if the response is not successful, with the <see cref="ProblemDetailsDto"/> if available.</exception>
private async Task<string> SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
return content;
throw CreateApiException(content, response, request);
}
/// <summary>
/// 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 <see cref="ProblemDetailsDto"/> and throws an <see cref="ApiException"/>.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="request">The <see cref="HttpRequestMessage"/> to be sent.</param>
@@ -261,28 +318,30 @@ public class ApiHttpClient : IApiHttpClient
/// <exception cref="ApiException">Thrown if the response is not successful, with the <see cref="ProblemDetailsDto"/> if available.</exception>
private async Task<TResponse> SendRequestAsync<TResponse>(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)
string content = await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
// Handle empty content case.
if (string.IsNullOrEmpty(content))
return default!;
return JsonSerializer.Deserialize<TResponse>(content, _jsonOptions)!;
}
/// <summary>
/// Creates the exception thrown when an API request fails.
/// </summary>
/// <param name="content">The raw response content.</param>
/// <param name="response">The failed HTTP response.</param>
/// <param name="request">The HTTP request that failed.</param>
/// <returns>The created <see cref="ApiException"/>.</returns>
private ApiException CreateApiException(string content, HttpResponseMessage response, HttpRequestMessage request)
{
ProblemDetailsDto? problemDetails = null;
// Attempt to deserialize the response content to ProblemDetailsDto if the request fails.
try
{
// Handle empty content case.
if (string.IsNullOrEmpty(content))
return default!;
return JsonSerializer.Deserialize<TResponse>(content, _jsonOptions)!;
}
else
{
ProblemDetailsDto? problemDetails = null;
// Attempt to deserialize the response content to ProblemDetailsDto if the request fails.
try
{
problemDetails = JsonSerializer.Deserialize<ProblemDetailsDto>(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);
problemDetails = JsonSerializer.Deserialize<ProblemDetailsDto>(content, _jsonOptions);
}
catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ }
return new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath);
}
/// <summary>
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.Exceptions;
using System.Collections.Generic;
using System.IO;
using System.Threading;
@@ -20,6 +21,7 @@ public interface IApiHttpClient
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the GET request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task<TResponse> GetAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
@@ -36,25 +38,38 @@ public interface IApiHttpClient
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A model containing the deserialized blob.</returns>
/// <returns>A model containing the raw blob bytes and their content type.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task<BlobDataDto> GetBlobAsync(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation.
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
/// </summary>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task PutIgnoringResponseAsync<TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and send to the API.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
/// <summary>
@@ -67,6 +82,7 @@ public interface IApiHttpClient
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default);
/// <summary>
@@ -79,8 +95,37 @@ public interface IApiHttpClient
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task<TResponse> PostMultipartAsync<TResponse>(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
/// </summary>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task<TResponse> PostAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
/// </summary>
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task PostIgnoringResponseAsync<TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
@@ -90,5 +135,6 @@ public interface IApiHttpClient
/// <param name="data">The data to be serialized and sent to the API.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
}
@@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http;
using Polly.CircuitBreaker;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
@@ -74,6 +75,13 @@ public class AuthorizationService : IAuthorizationService
{
return await _apiHttpClient.GetAsync<GetAuthorizationResponse>($"auth/get-authorization?userId={Uri.EscapeDataString(userId)}", cancellationToken);
}
catch (ApiException exception) when (exception.HttpStatusCode == HttpStatusCode.NotFound)
{
// This is the only place that knows the request was the current-user authorization check. Convert a 404 here into an explicit exception, so the middleware can
// invalidate the stale session without guessing from the request path. Do not move this classification into the middleware: it only sees a generic ApiException,
// and a caller-controlled path can contain the authorization route text.
throw new CurrentUserAuthorizationException(exception.ProblemDetails, exception.HttpStatusCode, exception.RequestPath);
}
catch (Exception exception)
{
HttpContext? httpContext = _httpContextAccessor.HttpContext;
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using System.Net;
#endregion
namespace Lumina.Presentation.Web.Common.Exceptions;
/// <summary>
/// Exception for an unsuccessful current-user authorization check, which means that the stored session refers to a user the API no longer knows.
/// </summary>
public class CurrentUserAuthorizationException : ApiException
{
/// <summary>
/// Initializes a new instance of the <see cref="CurrentUserAuthorizationException"/> class.
/// </summary>
/// <param name="problemDetails">The problem details object returned by the API.</param>
/// <param name="httpStatusCode">The HTTP status code returned by the API.</param>
/// <param name="requestPath">The absolute path of the API endpoint that produced this exception.</param>
public CurrentUserAuthorizationException(ProblemDetailsDto? problemDetails, HttpStatusCode httpStatusCode, string? requestPath = null)
: base(problemDetails, httpStatusCode, requestPath)
{
}
}
@@ -137,9 +137,10 @@ public class ExceptionHandlingMiddleware
/// </summary>
private async Task HandleNotFoundAsync(HttpContext context, ApiException apiException)
{
// When the API reports the currently logged-in user no longer exists (404 from the current-user authorization check),
// the stored session is stale: sign out and send the user to the login page instead of the not-found page.
if (context.User?.Identity?.IsAuthenticated == true && IsCurrentUserAuthorizationCheck(apiException))
// When the API reports the currently logged-in user no longer exists, the stored session is stale: sign out and send the user
// to the login page instead of the not-found page. The condition is signaled by the authorization check itself, never inferred
// from the URL of the failed request, because a caller-controlled path can contain the same text.
if (context.User?.Identity?.IsAuthenticated == true && apiException is CurrentUserAuthorizationException)
{
await HandleUnauthorizedAsync(context).ConfigureAwait(false);
return;
@@ -412,13 +413,4 @@ public class ExceptionHandlingMiddleware
}
}
/// <summary>
/// Determines whether the API exception originated from the authorization check of the currently logged in user.
/// </summary>
/// <param name="apiException">The API exception to inspect.</param>
/// <returns><see langword="true"/> if the exception came from the current-user authorization endpoint, <see langword="false"/> otherwise.</returns>
private static bool IsCurrentUserAuthorizationCheck(ApiException apiException)
{
return apiException.RequestPath?.Contains("/auth/get-authorization", StringComparison.OrdinalIgnoreCase) == true;
}
}
@@ -1,6 +0,0 @@
namespace Lumina.Presentation.Web.Common.Requests.Common;
/// <summary>
/// Record used for empty requests and responses.
/// </summary>
public record struct EmptyRequest();
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class FireScheduledJobEndpoint : BaseEndpoint<FireScheduledJobRequest, IR
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FireScheduledJobRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PutIgnoringResponseAsync<FireScheduledJobRequest>(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class StartScheduledJobEndpoint : BaseEndpoint<StartScheduledJobRequest,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(StartScheduledJobRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PutIgnoringResponseAsync<StartScheduledJobRequest>(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class StopScheduledJobEndpoint : BaseEndpoint<StopScheduledJobRequest, IR
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(StopScheduledJobRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PutIgnoringResponseAsync<StopScheduledJobRequest>(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class UpdateSchedulerDisplayPreferencesEndpoint : BaseEndpoint<UpdateSche
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(UpdateSchedulerDisplayPreferencesRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UpdateSchedulerDisplayPreferencesRequest>(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PutIgnoringResponseAsync<UpdateSchedulerDisplayPreferencesRequest>(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -16,7 +15,7 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite</c> route.
/// </summary>
public class RemoveFavoriteEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
public class RemoveFavoriteEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
// A value that is not a name of FavoriteMediaKind, so the API rejects a crafted route value with its own validation error.
private const string INVALID_MEDIA_KIND_PLACEHOLDER = "Invalid";
@@ -50,7 +49,7 @@ public class RemoveFavoriteEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, I
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// The route values are normalized before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment.
// The media kind must be the name of a FavoriteMediaKind member, which also rejects numeric strings and comma separated flag lists, and the Id must be a Guid.
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -57,9 +56,8 @@ public class RestoreMusicAlbumEndpoint : BaseEndpoint<EmptyRequest, IResult>
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
await _apiHttpClient.PostIgnoringResponseAsync(
ApiRoutes.Music.RESTORE_ALBUM.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId).Replace("{albumId}", albumId),
new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -55,9 +54,8 @@ public class RestoreMusicArtistEndpoint : BaseEndpoint<EmptyRequest, IResult>
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
await _apiHttpClient.PostIgnoringResponseAsync(
ApiRoutes.Music.RESTORE_ARTIST.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId),
new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -59,9 +58,8 @@ public class RestoreMusicTrackEndpoint : BaseEndpoint<EmptyRequest, IResult>
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
await _apiHttpClient.PostIgnoringResponseAsync(
ApiRoutes.Music.RESTORE_TRACK.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId).Replace("{albumId}", albumId).Replace("{trackId}", trackId),
new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -47,7 +46,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint<EmptyRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN, new Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -48,7 +47,7 @@ public class CancelLibraryScanEndpoint : BaseEndpoint<CancelLibraryScanRequest,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{scanId}", request.ScanId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PostIgnoringResponseAsync<CancelLibraryScanRequest>(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{scanId}", request.ScanId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -48,7 +47,7 @@ public class ScanLibrariesEndpoint : BaseEndpoint<EmptyRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
ScanLibraryDto[] response = await _apiHttpClient.PostAsync<ScanLibraryDto[], Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.Libraries.SCAN_LIBRARIES, new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
ScanLibraryDto[] response = await _apiHttpClient.PostAsync<ScanLibraryDto[]>(ApiRoutes.Libraries.SCAN_LIBRARIES, cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
}
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -49,7 +48,7 @@ public class ScanLibraryEndpoint : BaseEndpoint<ScanLibraryRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken)
{
ScanLibraryDto response = await _apiHttpClient.PostAsync<ScanLibraryDto, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.Libraries.SCAN_LIBRARY.Replace("{id}", request.Id.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
ScanLibraryDto response = await _apiHttpClient.PostAsync<ScanLibraryDto>(ApiRoutes.Libraries.SCAN_LIBRARY.Replace("{id}", request.Id.ToString()), cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
}
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -56,9 +55,8 @@ public class RestoreBookEndpoint : BaseEndpoint<EmptyRequest, IResult>
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
await _apiHttpClient.PostIgnoringResponseAsync(
ApiRoutes.Books.RESTORE_BOOK.Replace("{libraryId}", libraryId).Replace("{bookId}", bookId),
new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -72,7 +71,7 @@ public class StartConsumptionEndpoint : BaseEndpoint<EmptyRequest, IResult>
.Replace("{libraryId}", libraryId, StringComparison.Ordinal)
.Replace("{mediaKind}", mediaKind, StringComparison.Ordinal)
.Replace("{mediaItemId}", mediaItemId, StringComparison.Ordinal);
ConsumptionRecordDto record = await _apiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(endpoint, request, cancellationToken).ConfigureAwait(false);
ConsumptionRecordDto record = await _apiHttpClient.PostAsync<ConsumptionRecordDto>(endpoint, cancellationToken).ConfigureAwait(false);
return JsonSuccess(record);
}
}
@@ -3,7 +3,6 @@ using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
@@ -15,7 +14,7 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist;
/// <summary>
/// API endpoint for the <c>/{culture}/playlists/item/{playlistId}/api-delete-playlist</c> route.
/// </summary>
public class DeletePlaylistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
public class DeletePlaylistEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
@@ -46,7 +45,7 @@ public class DeletePlaylistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, I
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape its URL segment.
string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty;
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -50,7 +49,7 @@ public class UpdatePluginSettingsEndpoint : BaseEndpoint<UpdatePluginSettingsReq
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(UpdatePluginSettingsRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UpdatePluginSettingsRequest>(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PutIgnoringResponseAsync<UpdatePluginSettingsRequest>(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -48,7 +47,7 @@ public class UpdatePlaybackStateEndpoint : BaseEndpoint<PlaybackStateDto, IResul
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(PlaybackStateDto request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, PlaybackStateDto>(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PutIgnoringResponseAsync<PlaybackStateDto>(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isUpdated = true });
}
}
@@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.UsersManagement;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;
@@ -54,7 +53,7 @@ public class UpdateUserSettingsEndpoint : BaseEndpoint<UserSettingsDto, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(UserSettingsDto request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PutIgnoringResponseAsync<UserSettingsDto>(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false);
// Keep the per-user theme cache preference in sync with the stored settings, so the handler applies it immediately.
Guid? userId = GetCurrentUserId();
@@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Enums.Themes;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using System.Collections.Generic;
using System.IO;
@@ -68,7 +69,7 @@ public sealed class ThemeService
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default)
{
await _apiHttpClient.PutAsync<ThemeResponseDto, object>(ApiRoutes.Themes.SET_CURRENT_THEME, new { ThemeId = themeId }, cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PutIgnoringResponseAsync<SetCurrentThemeRequest>(ApiRoutes.Themes.SET_CURRENT_THEME, new SetCurrentThemeRequest(themeId), cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -101,7 +102,7 @@ public sealed class ThemeService
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task RestoreThemeAsync(string themeId, CancellationToken cancellationToken = default)
{
await _apiHttpClient.PostAsync<ThemeResponseDto, object>(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), new { }, cancellationToken).ConfigureAwait(false);
await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false);
}
/// <summary>