mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the web track streaming proxy and streaming HTTP client
This commit is contained in:
1 parent
d7c1ae60c2
commit
aab36dcd29
17 files changed
+969
-29
No files matched your search
@@ -0,0 +1,104 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the streamed response of a remote API request. It exposes the status code, the range related headers and the
|
||||
/// content stream of the response, so that a caller can forward the response to a client without ever buffering its content.
|
||||
/// </summary>
|
||||
public sealed class ApiStreamResult : IAsyncDisposable
|
||||
{
|
||||
private readonly HttpResponseMessage _response;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status code of the response.
|
||||
/// </summary>
|
||||
public HttpStatusCode StatusCode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the content stream of the response.
|
||||
/// </summary>
|
||||
public Stream Content { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media type of the content of the response, or <see langword="null"/> when the response declares none.
|
||||
/// </summary>
|
||||
public string? ContentType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the length of the content of the response, or <see langword="null"/> when the response declares none.
|
||||
/// </summary>
|
||||
public long? ContentLength { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the range of the content of the response, when the response is a partial content response.
|
||||
/// </summary>
|
||||
public string? ContentRange { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ranges the remote API accepts, when the response declares them.
|
||||
/// </summary>
|
||||
public string? AcceptRanges { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the entity tag of the content of the response, when the response declares one.
|
||||
/// </summary>
|
||||
public string? ETag { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the date and time the content of the response was last modified, when the response declares it.
|
||||
/// </summary>
|
||||
public DateTimeOffset? LastModified { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the caching instructions of the response, when the response declares them.
|
||||
/// </summary>
|
||||
public string? CacheControl { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiStreamResult"/> class.
|
||||
/// </summary>
|
||||
/// <param name="response">The response returned by the remote API.</param>
|
||||
/// <param name="content">The content stream of the response.</param>
|
||||
private ApiStreamResult(HttpResponseMessage response, Stream content)
|
||||
{
|
||||
_response = response;
|
||||
Content = content;
|
||||
StatusCode = response.StatusCode;
|
||||
ContentType = response.Content.Headers.ContentType?.ToString();
|
||||
ContentLength = response.Content.Headers.ContentLength;
|
||||
ContentRange = response.Content.Headers.ContentRange?.ToString();
|
||||
AcceptRanges = response.Headers.AcceptRanges.Count > 0 ? string.Join(", ", response.Headers.AcceptRanges) : null;
|
||||
ETag = response.Headers.ETag?.ToString();
|
||||
LastModified = response.Content.Headers.LastModified;
|
||||
CacheControl = response.Headers.CacheControl?.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="ApiStreamResult"/> from a response, without buffering the content of the response.
|
||||
/// </summary>
|
||||
/// <param name="response">The response returned by the remote API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The streamed response.</returns>
|
||||
public static async Task<ApiStreamResult> CreateAsync(HttpResponseMessage response, CancellationToken cancellationToken)
|
||||
{
|
||||
Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new ApiStreamResult(response, content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the content stream and the response it belongs to.
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Content.DisposeAsync().ConfigureAwait(false);
|
||||
_response.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for typed clients that stream responses from the remote API without buffering their content.
|
||||
/// </summary>
|
||||
public interface IStreamingApiHttpClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the response as a stream, without ever buffering its content in memory.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="requestHeaders">The range and conditional headers of the incoming request to forward, so that the API,
|
||||
/// which is the only party that knows the entity tag and the modification time of the resource, validates them itself.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The streamed response of the API request, which the caller must dispose once it has finished copying it.</returns>
|
||||
Task<ApiStreamResult> GetStreamAsync(string endpoint, IReadOnlyDictionary<string, string> requestHeaders, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Typed client for streaming API access. Unlike <see cref="ApiHttpClient"/>, it never buffers a response in memory and is
|
||||
/// intentionally free of any retry or circuit breaker policy, because a stream is meant to be handed to the client as a whole.
|
||||
/// </summary>
|
||||
public class StreamingApiHttpClient : IStreamingApiHttpClient
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly HttpContext? _httpContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamingApiHttpClient"/> class.
|
||||
/// </summary>
|
||||
/// <param name="httpClient">Injected HttpClient for interacting with the API.</param>
|
||||
/// <param name="httpContextAccessor">Injected service for providing the current HTTP context.</param>
|
||||
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
|
||||
public StreamingApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot<ServerConfigurationDto> 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}/");
|
||||
// A streamed response stays open for as long as the client keeps reading it, so the timeout is generously large, but it is bounded:
|
||||
// an upstream that accepts the request and never answers must not hold a connection and a stream permit open forever. No track, and
|
||||
// no movie, is longer than this.
|
||||
httpClient.Timeout = TimeSpan.FromHours(12);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the response
|
||||
/// as a stream, without ever buffering its content in memory.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="requestHeaders">The range and conditional headers of the incoming request to forward, so that the API, which is the only party that knows the entity tag and the modification time of the resource, validates them itself.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The streamed response of the API request, which the caller must dispose once it has finished copying it.</returns>
|
||||
/// <exception cref="ApiException">Thrown if the response is not successful, with the <see cref="ProblemDetailsDto"/> if available.</exception>
|
||||
public async Task<ApiStreamResult> GetStreamAsync(string endpoint, IReadOnlyDictionary<string, string> requestHeaders, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using (HttpRequestMessage request = new(HttpMethod.Get, endpoint))
|
||||
{
|
||||
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
|
||||
if (authenticationHeader is not null)
|
||||
request.Headers.Authorization = authenticationHeader;
|
||||
// The range and the conditional headers are forwarded as they are, so that the API, and never this client, decides what a partial response contains.
|
||||
foreach (KeyValuePair<string, string> header in requestHeaders)
|
||||
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||
|
||||
// Only the headers of the response are awaited, so that its content is streamed to the client instead of being copied into memory first.
|
||||
HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||
// A not modified response and a range not satisfiable response are valid outcomes of a conditional or ranged request, and their
|
||||
// headers (the entity tag, the last modified date, the content range) are the whole answer, so they are passed through instead of
|
||||
// being turned into an error, which would drop the very headers the caller needs to revalidate or recover.
|
||||
if (!response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.NotModified && response.StatusCode != HttpStatusCode.RequestedRangeNotSatisfiable)
|
||||
{
|
||||
HttpStatusCode statusCode = response.StatusCode;
|
||||
string content;
|
||||
try
|
||||
{
|
||||
content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The response is turned into an exception, so it is disposed even when reading its error body fails, otherwise its connection would leak.
|
||||
response.Dispose();
|
||||
}
|
||||
ProblemDetailsDto? problemDetails = null;
|
||||
try
|
||||
{
|
||||
problemDetails = JsonSerializer.Deserialize<ProblemDetailsDto>(content, s_jsonOptions);
|
||||
}
|
||||
catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ }
|
||||
throw new ApiException(problemDetails, statusCode, request.RequestUri?.AbsolutePath);
|
||||
}
|
||||
try
|
||||
{
|
||||
return await ApiStreamResult.CreateAsync(response, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The response was already received, so it must be disposed if its content stream could not be obtained, otherwise its connection would leak.
|
||||
response.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the authentication header for the current user, if available.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// An <see cref="AuthenticationHeaderValue"/> with a Bearer token if the user's token is found, <see langword="null"/> otherwise.
|
||||
/// </returns>
|
||||
private AuthenticationHeaderValue? GetAuthenticationHeader()
|
||||
{
|
||||
string? token = _httpContext?.User?.FindFirst("Token")?.Value;
|
||||
return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null;
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the playback manifest of a track, describing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")]
|
||||
public class PlaybackManifestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the track the manifest describes.
|
||||
/// </summary>
|
||||
public Guid TrackId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the duration of the audio of the track, in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the container of the audio file of the track, as stored by the probe.
|
||||
/// </summary>
|
||||
public string? SourceContainer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec of the audio of the track, as stored by the probe.
|
||||
/// </summary>
|
||||
public string? SourceCodec { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the sample rate of the audio of the track, in Hz.
|
||||
/// </summary>
|
||||
public int SampleRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of audio channels of the track.
|
||||
/// </summary>
|
||||
public int Channels { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the bit depth of the audio of the track.
|
||||
/// </summary>
|
||||
public int? BitDepth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ReplayGain track gain of the track, in decibels.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainTrackGain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ReplayGain track peak of the track.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainTrackPeak { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ReplayGain album gain of the track, in decibels.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainAlbumGain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ReplayGain album peak of the track.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainAlbumPeak { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the player can play the stored audio as it is, without the server changing its container or its codec.
|
||||
/// </summary>
|
||||
public bool DirectPlay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the container of the audio the server delivers, when the delivery is not a direct play.
|
||||
/// </summary>
|
||||
public string? DeliveryContainer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec of the audio the server delivers, when the delivery is not a direct play.
|
||||
/// </summary>
|
||||
public string? DeliveryCodec { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the shape the delivered audio is addressed and seeked by, when the delivery is not a direct play.
|
||||
/// </summary>
|
||||
public PlaybackDeliveryShape? DeliveryShape { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments.
|
||||
/// </summary>
|
||||
public int? SegmentDurationSeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the delivered audio can be seeked by the player.
|
||||
/// </summary>
|
||||
public bool Seekable { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path of the track stream. The API returns it relative to itself; this web application replaces it with
|
||||
/// the URL of its own streaming proxy, so that the browser never reaches the API server directly.
|
||||
/// </summary>
|
||||
public string StreamPath { get; set; } = string.Empty;
|
||||
}
|
||||
+40
@@ -20,6 +20,7 @@ using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.AspNetCore.Localization.Routing;
|
||||
using Microsoft.AspNetCore.Mvc.Localization;
|
||||
using Microsoft.AspNetCore.Mvc.Razor;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Polly;
|
||||
using Polly.CircuitBreaker;
|
||||
@@ -31,7 +32,9 @@ using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.RateLimiting;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -43,6 +46,11 @@ namespace Lumina.Presentation.Web.Common.DependencyInjection;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class PresentationWebLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the rate limiting policy that bounds the number of concurrent track streams held by a single user.
|
||||
/// </summary>
|
||||
public const string TRACK_STREAM_RATE_LIMIT_POLICY = "trackStreamPolicy";
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services of the Presentation Web layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
@@ -288,6 +296,26 @@ public static class PresentationWebLayerServices
|
||||
|
||||
AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
|
||||
|
||||
// Bound the number of long lived streams a single user can hold open at once, mirroring the concurrency limit the API server applies to
|
||||
// its own stream route. Without it, an authenticated user could make this application open an unbounded number of parallel streams, each
|
||||
// pinning a connection towards the API for the whole duration of a track, turning this application into an exhaustion amplifier.
|
||||
services.AddRateLimiter(rateLimiterOptions =>
|
||||
{
|
||||
rateLimiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
rateLimiterOptions.AddPolicy(TRACK_STREAM_RATE_LIMIT_POLICY, httpContext =>
|
||||
{
|
||||
// The limit is partitioned per authenticated user, and it is a concurrency limit, not a per IP attempt window, so it is deliberately separate from any login throttling.
|
||||
string userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous";
|
||||
return RateLimitPartition.GetConcurrencyLimiter(
|
||||
partitionKey: $"trackStream_{userId}",
|
||||
factory: _ => new ConcurrencyLimiterOptions
|
||||
{
|
||||
PermitLimit = 4, // Allow 4 concurrent audio streams per user, matching the API server.
|
||||
QueueLimit = 0 // Don't queue requests, a request beyond the limit is rejected instead of waiting.
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Register the HTTP typed client used for the API interaction.
|
||||
services.AddHttpClient<IApiHttpClient, ApiHttpClient>()
|
||||
.AddHttpMessageHandler<CachedAuthorizationHandler>()
|
||||
@@ -295,6 +323,18 @@ public static class PresentationWebLayerServices
|
||||
.AddPolicyHandler(retryPolicy)
|
||||
.AddPolicyHandler(circuitBreakerPolicy);
|
||||
|
||||
// Register the HTTP typed client used for streaming responses from the API. It deliberately has no retry and no circuit breaker policy,
|
||||
// because a stream cannot be transparently retried once its content has started reaching the client. It configures a bounded, generous
|
||||
// timeout itself, because a stream stays open for as long as the client keeps reading it, yet a stalled one must never be held forever.
|
||||
services.AddHttpClient<IStreamingApiHttpClient, StreamingApiHttpClient>()
|
||||
// Cap the connections a stream can pin towards the API, as a backstop on top of the per user concurrency limit of the stream route.
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
|
||||
{
|
||||
// A blackholed connection attempt must fail on its own, well before the request timeout, instead of holding a stream permit.
|
||||
ConnectTimeout = TimeSpan.FromSeconds(30),
|
||||
MaxConnectionsPerServer = 64
|
||||
});
|
||||
|
||||
services.AddScoped<CachedAuthorizationHandler>();
|
||||
services.AddScoped<CachedThemeHandler>();
|
||||
services.AddScoped<ThemeCachePreferenceService>();
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the shapes in which delivered audio is addressed and seeked.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum PlaybackDeliveryShape
|
||||
{
|
||||
/// <summary>
|
||||
/// The delivered media is the original file itself, addressed and seeked by byte range.
|
||||
/// </summary>
|
||||
ByteRangeSeekable,
|
||||
|
||||
/// <summary>
|
||||
/// The delivered media is a sequence of fixed duration segments, addressed and seeked by time, so that finding a time never
|
||||
/// requires mapping a byte range to it.
|
||||
/// </summary>
|
||||
TimeAddressedSegments,
|
||||
}
|
||||
@@ -10,6 +10,7 @@ using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -47,6 +48,11 @@ public class ExceptionHandlingMiddleware
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
|
||||
{
|
||||
// The client went away while its request or response was being processed, so there is nobody left to answer.
|
||||
context.Abort();
|
||||
}
|
||||
catch (ApiException apiException) // threat API exceptions differently - they contain Problem Details properties
|
||||
{
|
||||
await HandleApiExceptionAsync(context, apiException);
|
||||
@@ -54,6 +60,13 @@ public class ExceptionHandlingMiddleware
|
||||
catch (Exception ex) // other cases -
|
||||
{
|
||||
_logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message);
|
||||
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection
|
||||
// is aborted instead, so that the client sees a failed transfer rather than a success response it cannot trust.
|
||||
if (context.Response.HasStarted)
|
||||
{
|
||||
context.Abort();
|
||||
return;
|
||||
}
|
||||
// return a JSON result with the error details
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
@@ -77,34 +90,23 @@ public class ExceptionHandlingMiddleware
|
||||
apiException.ProblemDetails?.Detail,
|
||||
apiException.ProblemDetails?.Extensions);
|
||||
|
||||
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection
|
||||
// is aborted instead, so that the client sees a failed transfer rather than a redirect it could not follow or a body it would misread.
|
||||
if (context.Response.HasStarted)
|
||||
{
|
||||
context.Abort();
|
||||
return;
|
||||
}
|
||||
|
||||
// handle unauthorized errors by prompting the user to re-login
|
||||
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
|
||||
await HandleUnauthorizedAsync(context);
|
||||
else if (apiException.HttpStatusCode == HttpStatusCode.NotFound) //
|
||||
await HandleNotFoundAsync(context, apiException);
|
||||
else if (apiException.HttpStatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
if (IsApiRequest(context))
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
else
|
||||
await context.ForbidAsync();
|
||||
}
|
||||
await HandleForbiddenAsync(context, apiException);
|
||||
else
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
await HandleGenericApiErrorAsync(context, apiException);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -120,7 +122,7 @@ public class ExceptionHandlingMiddleware
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsApiRequest(context))
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
await WriteJsonResponseAsync(context, new
|
||||
@@ -129,7 +131,7 @@ public class ExceptionHandlingMiddleware
|
||||
errorMessage = "NotFound"
|
||||
});
|
||||
}
|
||||
else
|
||||
else if (IsNavigationRequest(context))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
|
||||
@@ -138,6 +140,48 @@ public class ExceptionHandlingMiddleware
|
||||
_logger.LogInformation("Redirecting user to NotFound url");
|
||||
context.Response.Redirect(notFoundUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.NotFound).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles forbidden exceptions.
|
||||
/// </summary>
|
||||
private async Task HandleForbiddenAsync(HttpContext context, ApiException apiException)
|
||||
{
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
else if (IsNavigationRequest(context))
|
||||
await context.ForbidAsync();
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Forbidden).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the API exceptions that are neither authentication, authorization, nor not found failures.
|
||||
/// </summary>
|
||||
private async Task HandleGenericApiErrorAsync(HttpContext context, ApiException apiException)
|
||||
{
|
||||
// JSON callers and page navigations get the localized error message; any other caller, like an audio request, is answered with
|
||||
// a bare status code, because a JSON body is not a representation such a caller can consume.
|
||||
if (IsJsonRequest(context) || IsNavigationRequest(context))
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)apiException.HttpStatusCode).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -149,7 +193,7 @@ public class ExceptionHandlingMiddleware
|
||||
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
|
||||
context.Response.Cookies.Delete("Token");
|
||||
|
||||
if (IsApiRequest(context))
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
|
||||
await WriteJsonResponseAsync(context, new
|
||||
@@ -158,7 +202,7 @@ public class ExceptionHandlingMiddleware
|
||||
errorMessage = "Unauthorized"
|
||||
});
|
||||
}
|
||||
else
|
||||
else if (IsNavigationRequest(context))
|
||||
{
|
||||
string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
|
||||
string returnUrl = $"{context.Request.Path}{context.Request.QueryString}";
|
||||
@@ -166,6 +210,8 @@ public class ExceptionHandlingMiddleware
|
||||
_logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl);
|
||||
context.Response.Redirect(loginUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Unauthorized).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -203,11 +249,38 @@ public class ExceptionHandlingMiddleware
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current request is an API request.
|
||||
/// Checks if the current request is a programmatic request that expects a JSON response.
|
||||
/// </summary>
|
||||
private static bool IsApiRequest(HttpContext context)
|
||||
/// <remarks>
|
||||
/// Every request is classified into exactly one of three kinds: a JSON request, which this method detects, a browser navigation, which
|
||||
/// <see cref="IsNavigationRequest"/> detects, and a raw request, which is neither of the two and is answered with a bare status code.
|
||||
/// </remarks>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <returns><see langword="true"/> when the request expects JSON, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsJsonRequest(HttpContext context)
|
||||
{
|
||||
return context.Request.Headers.Accept.Any(x => x?.Contains("application/json") == true) || context.Request.Headers.XRequestedWith == "XMLHttpRequest";
|
||||
return context.Request.Headers.Accept.Any(accept => accept?.Contains("application/json", StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| context.Request.Headers.XRequestedWith == "XMLHttpRequest";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current request is a browser navigation, which is the only kind of request that can follow a redirect.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A request that explicitly asks for something other than HTML, like an audio or a media request, is answered with a bare status
|
||||
/// code: treating it as a page would redirect it to an HTML login or not-found page, which its caller cannot consume. A request that
|
||||
/// states no preference at all keeps the historical page behavior, so that callers that send no <c>Accept</c> header are not silently
|
||||
/// changed, but a request that carries no <c>Accept</c> yet asks for a byte range is treated as a raw request, because a headerless
|
||||
/// range request comes from a media client or a probe, not from a browser.
|
||||
/// </remarks>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <returns><see langword="true"/> when the request is a navigation, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsNavigationRequest(HttpContext context)
|
||||
{
|
||||
return (context.Request.Headers.Accept.Count == 0 && context.Request.Headers.Range.Count == 0)
|
||||
|| context.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| string.Equals(context.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(context.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -219,6 +292,34 @@ public class ExceptionHandlingMiddleware
|
||||
await context.Response.WriteAsJsonAsync(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the response of a raw request, which is a status code and no body.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is the third branch of the request classification, the one that answers a request that is neither a JSON request, which
|
||||
/// <see cref="IsJsonRequest"/> detects, nor a browser navigation, which <see cref="IsNavigationRequest"/> detects.
|
||||
/// </remarks>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <param name="statusCode">The status code to answer with.</param>
|
||||
private async Task WriteStatusOnlyResponseAsync(HttpContext context, int statusCode)
|
||||
{
|
||||
context.Response.StatusCode = statusCode;
|
||||
context.Response.ContentLength = 0;
|
||||
try
|
||||
{
|
||||
// Starting the response commits the status code and the headers, so that no outer middleware replaces this decision with a page,
|
||||
// and so that a caller that asked for content never receives HTML instead. A token that is never cancelled is used on purpose,
|
||||
// because a request whose token is already cancelled would otherwise throw here, inside the exception handler, and escape it.
|
||||
await context.Response.StartAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception startException)
|
||||
{
|
||||
// There is nobody left to answer, so the connection is aborted, and the failure is only recorded for diagnostics.
|
||||
_logger.LogDebug(startException, "Could not commit the status only response, the client has likely disconnected.");
|
||||
context.Abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the API exception originated from the authorization check of the currently logged in user.
|
||||
/// </summary>
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to get the playback manifest of a track.
|
||||
/// </summary>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route. Required.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route. Required.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track whose manifest is requested, taken from the route. Required.</param>
|
||||
/// <param name="LibraryId">The Id of the media library the track belongs to. Required.</param>
|
||||
/// <param name="Capabilities">The comma separated list of the container and codec pairs the player advertises it can play directly. Optional.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record GetPlaybackManifestRequest(
|
||||
string ArtistId,
|
||||
string AlbumId,
|
||||
string TrackId,
|
||||
Guid LibraryId,
|
||||
string? Capabilities
|
||||
);
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to stream the audio file of a track.
|
||||
/// </summary>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route. Required.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route. Required.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track to stream, taken from the route. Required.</param>
|
||||
/// <param name="LibraryId">The Id of the media library the track belongs to. Required.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record StreamMusicTrackRequest(
|
||||
string ArtistId,
|
||||
string AlbumId,
|
||||
string TrackId,
|
||||
Guid LibraryId
|
||||
);
|
||||
@@ -24,5 +24,7 @@ public static partial class ApiRoutes
|
||||
public const string GET_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}";
|
||||
public const string UPDATE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}";
|
||||
public const string DELETE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}";
|
||||
public const string STREAM_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream";
|
||||
public const string GET_PLAYBACK_MANIFEST = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest";
|
||||
}
|
||||
}
|
||||
@@ -28,5 +28,7 @@ public static partial class WebRoutes
|
||||
public const string GET_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-track";
|
||||
public const string SAVE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track";
|
||||
public const string DELETE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track";
|
||||
public const string STREAM_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track";
|
||||
public const string GET_PLAYBACK_MANIFEST = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest";
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
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.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest</c> route.
|
||||
/// </summary>
|
||||
public class GetPlaybackManifestEndpoint : BaseEndpoint<GetPlaybackManifestRequest, IResult>
|
||||
{
|
||||
private readonly IApiHttpClient _apiHttpClient;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
|
||||
public GetPlaybackManifestEndpoint(IApiHttpClient apiHttpClient)
|
||||
{
|
||||
_apiHttpClient = apiHttpClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
base.Configure();
|
||||
Verbs(Http.GET);
|
||||
Routes(WebRoutes.Music.GET_PLAYBACK_MANIFEST);
|
||||
DontAutoTag();
|
||||
Options(options => options.WithTags("Music"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the playback manifest of the track identified by <paramref name="request"/>, with the stream path of this application.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the Ids of the artist, album, track and media library to get the manifest of, and the capabilities of the player.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(GetPlaybackManifestRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never
|
||||
// escape its URL segment, and an unparseable id is reported by the API as a missing id.
|
||||
string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString();
|
||||
string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString();
|
||||
string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString();
|
||||
string endpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", normalizedArtistId)
|
||||
.Replace("{albumId}", normalizedAlbumId)
|
||||
.Replace("{trackId}", normalizedTrackId);
|
||||
// The capabilities the player advertises are optional and are forwarded only when the player sent them.
|
||||
if (!string.IsNullOrWhiteSpace(request.Capabilities))
|
||||
endpoint = $"{endpoint}?capabilities={Uri.EscapeDataString(request.Capabilities)}";
|
||||
|
||||
PlaybackManifestDto? manifest = await _apiHttpClient.GetAsync<PlaybackManifestDto>(endpoint, cancellationToken).ConfigureAwait(false) ?? throw new ApiException(new ProblemDetailsDto
|
||||
{
|
||||
Title = "General.Failure",
|
||||
Detail = "InternalServerError",
|
||||
Status = StatusCodes.Status502BadGateway
|
||||
}, HttpStatusCode.BadGateway, endpoint);
|
||||
// The API only knows the relative path of its own stream endpoint, and the browser only reaches this application, so the path is
|
||||
// replaced with the path of the streaming proxy of this application, which is the URL the player actually consumes.
|
||||
manifest.StreamPath = BuildBrowserStreamPath(request.LibraryId, normalizedArtistId, normalizedAlbumId, normalizedTrackId);
|
||||
return JsonSuccess(manifest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the browser facing relative path of the streaming proxy of this application for the track identified by the given Ids.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The path is built from the route template of this application, and never from the host, the scheme, or the port of the incoming request.
|
||||
/// The path base is derived from a forwarded header that a caller can spoof, so it is only used when it is a plain absolute path, and the
|
||||
/// culture is confined to a single path segment, so that no part of the result can introduce an authority, which would make the browser
|
||||
/// resolve the stream from another origin.
|
||||
/// </remarks>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The normalized Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The root relative path the browser fetches the stream from, on its own origin.</returns>
|
||||
private string BuildBrowserStreamPath(Guid libraryId, string artistId, string albumId, string trackId)
|
||||
{
|
||||
string culture = IsSafePathSegment(Culture) ? Culture : "en-US";
|
||||
string pathBase = IsSafePathBase(HttpContext.Request.PathBase.ToString()) ? HttpContext.Request.PathBase.ToString().TrimEnd('/') : string.Empty;
|
||||
string streamPath = WebRoutes.Music.STREAM_TRACK
|
||||
.Replace("{culture}", culture, StringComparison.OrdinalIgnoreCase)
|
||||
.Replace("{artistId}", artistId, StringComparison.Ordinal)
|
||||
.Replace("{albumId}", albumId, StringComparison.Ordinal)
|
||||
.Replace("{trackId}", trackId, StringComparison.Ordinal);
|
||||
return $"{pathBase}/{streamPath}?libraryId={libraryId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a value can be used safely as a single segment of a path the browser resolves against its own origin.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to check.</param>
|
||||
/// <returns><see langword="true"/> when the value cannot introduce a path separator, a query, a fragment, or a control character, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsSafePathSegment(string value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
return false;
|
||||
foreach (char character in value)
|
||||
if (character == '/' || character == '\\' || character == '?' || character == '#' || character == '%' || char.IsControl(character))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a value can be used safely as the path base of a path the browser resolves against its own origin.
|
||||
/// </summary>
|
||||
/// <param name="pathBase">The path base to check.</param>
|
||||
/// <returns><see langword="true"/> when the value is a plain absolute path, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsSafePathBase(string pathBase)
|
||||
{
|
||||
if (string.IsNullOrEmpty(pathBase))
|
||||
return true;
|
||||
// A path base that does not start with a single slash, or that contains a backslash or a control character, can be normalized by a
|
||||
// browser into a protocol relative or absolute reference, which would point the stream fetch at another origin. A query or a fragment
|
||||
// (or an escape that decodes into one) would truncate the built path instead.
|
||||
if (!pathBase.StartsWith('/') || pathBase.StartsWith("//", StringComparison.Ordinal))
|
||||
return false;
|
||||
foreach (char character in pathBase)
|
||||
if (character == '\\' || character == '?' || character == '#' || character == '%' || char.IsControl(character))
|
||||
return false;
|
||||
return !pathBase.Contains("//", StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetPlaybackManifestEndpoint"/> endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackManifestEndpointSummary : Summary<GetPlaybackManifestEndpoint, GetPlaybackManifestRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public GetPlaybackManifestEndpointSummary()
|
||||
{
|
||||
Summary = "Retrieves the playback manifest of a music track.";
|
||||
Description = "Retrieves the playback manifest of the music track identified by the route, with the stream path replaced by the URL of the streaming proxy of this application.";
|
||||
|
||||
RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required.");
|
||||
RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required.");
|
||||
RequestParam(r => r.TrackId, "The unique identifier of the track whose manifest is requested. Required.");
|
||||
RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required.");
|
||||
RequestParam(r => r.Capabilities, "The comma separated list of the container and codec pairs the player advertises it can play directly. Optional.");
|
||||
|
||||
Response(200, "The playback manifest of the track is retrieved.");
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track</c> route.
|
||||
/// </summary>
|
||||
public class StreamMusicTrackEndpoint : BaseEndpoint<StreamMusicTrackRequest, IResult>
|
||||
{
|
||||
private readonly IStreamingApiHttpClient _streamingApiHttpClient;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="streamingApiHttpClient">Injected service for streaming interactions with the API.</param>
|
||||
public StreamMusicTrackEndpoint(IStreamingApiHttpClient streamingApiHttpClient)
|
||||
{
|
||||
_streamingApiHttpClient = streamingApiHttpClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
base.Configure();
|
||||
Verbs(Http.GET);
|
||||
Routes(WebRoutes.Music.STREAM_TRACK);
|
||||
DontAutoTag();
|
||||
// The stream is bounded per user with a concurrency limit, exactly like the stream route of the API server, so that a single user can
|
||||
// never hold an unbounded number of long lived streams open at once and exhaust the connections towards the API.
|
||||
Options(options => options
|
||||
.WithTags("Music")
|
||||
.RequireRateLimiting(PresentationWebLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Streams the audio file of the track identified by <paramref name="request"/> through the API, without buffering it.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the Ids of the artist, album, track and media library to stream.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(StreamMusicTrackRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never
|
||||
// escape its URL segment, and an unparseable id is reported by the API as a missing id.
|
||||
string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString();
|
||||
string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString();
|
||||
string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString();
|
||||
string endpoint = ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", normalizedArtistId)
|
||||
.Replace("{albumId}", normalizedAlbumId)
|
||||
.Replace("{trackId}", normalizedTrackId);
|
||||
// The range and the conditional headers that revalidate it are forwarded as they are, so that the API, which is the only party that
|
||||
// knows the entity tag and the modification time of the file, answers a partial, a resumed, or an unchanged request by itself.
|
||||
Dictionary<string, string> forwardHeaders = [];
|
||||
AddHeader(forwardHeaders, "Range", HttpContext.Request.Headers.Range);
|
||||
AddHeader(forwardHeaders, "If-Range", HttpContext.Request.Headers.IfRange);
|
||||
AddHeader(forwardHeaders, "If-None-Match", HttpContext.Request.Headers.IfNoneMatch);
|
||||
AddHeader(forwardHeaders, "If-Modified-Since", HttpContext.Request.Headers.IfModifiedSince);
|
||||
|
||||
// The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading.
|
||||
await using (ApiStreamResult streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, forwardHeaders, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
HttpContext.Response.StatusCode = (int)streamResult.StatusCode;
|
||||
CopyResponseHeaders(HttpContext.Response, streamResult);
|
||||
// The caching instructions of the API are forwarded, so that the web hop never silently ignores a caching decision the API made,
|
||||
// but the response is always private to the user, and it varies by the cookie that authenticates this hop: the browser never sends
|
||||
// the bearer token the API sees.
|
||||
HttpContext.Response.Headers["Cache-Control"] = BuildCacheControl(streamResult.CacheControl);
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
// The body is copied straight from the API to the client, with no intermediate buffering, and the copy is abandoned when the client disconnects.
|
||||
await streamResult.Content.CopyToAsync(HttpContext.Response.Body, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return Results.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a request header to the set of headers forwarded to the API, unless the incoming request did not carry it.
|
||||
/// </summary>
|
||||
/// <param name="headers">The set of headers forwarded to the API.</param>
|
||||
/// <param name="name">The name of the header.</param>
|
||||
/// <param name="value">The value of the header in the incoming request, which is empty when the header was not sent.</param>
|
||||
private static void AddHeader(Dictionary<string, string> headers, string name, StringValues value)
|
||||
{
|
||||
if (value.Count > 0 && !string.IsNullOrWhiteSpace(value.ToString()))
|
||||
headers[name] = value.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the status and resource headers of the streamed API response to the response sent to the browser.
|
||||
/// </summary>
|
||||
/// <param name="response">The response sent to the browser.</param>
|
||||
/// <param name="streamResult">The streamed response of the API.</param>
|
||||
private static void CopyResponseHeaders(HttpResponse response, ApiStreamResult streamResult)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(streamResult.ContentType))
|
||||
response.ContentType = streamResult.ContentType;
|
||||
if (streamResult.ContentLength.HasValue)
|
||||
response.ContentLength = streamResult.ContentLength.Value;
|
||||
SetHeader(response, "Content-Range", streamResult.ContentRange);
|
||||
SetHeader(response, "Accept-Ranges", streamResult.AcceptRanges);
|
||||
SetHeader(response, "ETag", streamResult.ETag);
|
||||
SetHeader(response, "Last-Modified", streamResult.LastModified?.ToString("R"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a response header to the given value, unless the value is missing.
|
||||
/// </summary>
|
||||
/// <param name="response">The response to set the header on.</param>
|
||||
/// <param name="name">The name of the header.</param>
|
||||
/// <param name="value">The value of the header, or <see langword="null"/> when the API did not send it.</param>
|
||||
private static void SetHeader(HttpResponse response, string name, string? value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
response.Headers[name] = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the caching instructions of the response sent to the browser from the instructions of the API.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A stream is specific to the authenticated user, so it must never be stored by a shared cache. Every other instruction of the API,
|
||||
/// like a maximum age for the private cache of the browser or a no-store, is kept, so that the web hop never silently ignores a caching
|
||||
/// decision the API made for the resource.
|
||||
/// </remarks>
|
||||
/// <param name="apiCacheControl">The caching instructions of the API response, or <see langword="null"/> when it declared none.</param>
|
||||
/// <returns>The caching instructions of the response sent to the browser.</returns>
|
||||
private static string BuildCacheControl(string? apiCacheControl)
|
||||
{
|
||||
if (!CacheControlHeaderValue.TryParse(apiCacheControl, out CacheControlHeaderValue? cacheControl))
|
||||
cacheControl = new CacheControlHeaderValue();
|
||||
cacheControl.Public = false;
|
||||
cacheControl.Private = true;
|
||||
return cacheControl.ToString();
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="StreamMusicTrackEndpoint"/> endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackEndpointSummary : Summary<StreamMusicTrackEndpoint, StreamMusicTrackRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public StreamMusicTrackEndpointSummary()
|
||||
{
|
||||
Summary = "Streams the audio file of a music track.";
|
||||
Description = "Streams the audio file of the music track identified by the route, forwarding the range and the conditional headers the browser sends, so that the player can start playback before the whole file is downloaded, resume a partial download, and revalidate a cached copy.";
|
||||
|
||||
RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required.");
|
||||
RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required.");
|
||||
RequestParam(r => r.TrackId, "The unique identifier of the track to stream. Required.");
|
||||
RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required.");
|
||||
|
||||
Response(200, "The whole audio file of the track is streamed.");
|
||||
Response(206, "The requested range of the audio file of the track is streamed, with its content range.");
|
||||
Response(304, "The audio file of the track did not change since the copy the browser already holds, and its validators are returned.");
|
||||
Response(416, "The requested range cannot be satisfied, and the total length of the audio file is returned in the content range.");
|
||||
Response(401, "The user is not authenticated.");
|
||||
Response(403, "The user is not allowed to stream the track of the media library.");
|
||||
Response(404, "The track, the album, the artist, or the media library was not found, or is out of the scope of the route.");
|
||||
Response(429, "The user is already holding the maximum number of concurrent track streams.");
|
||||
Response(502, "The remote API did not return the audio file of the track.");
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,8 @@ public class Program
|
||||
app.UseSession();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
// The rate limiting policies are evaluated after authentication, because the track stream limit is partitioned per authenticated user.
|
||||
app.UseRateLimiter();
|
||||
// validate the antiforgery token after authentication, because the token is bound to the authenticated user and
|
||||
// validating it before the user is known would reject every request made by a logged-in user
|
||||
app.UseAntiforgeryFE(additionalContentTypes: ["application/json"]);
|
||||
|
||||
@@ -366,7 +366,14 @@ async function updateContentAsync(url, addToHistory) {
|
||||
window.viewCleanups = {};
|
||||
}
|
||||
|
||||
const response = await fetch(url);
|
||||
// The in-place navigation is a page load performed through fetch, so it declares that it expects HTML. Without this header, the
|
||||
// server cannot tell it apart from a media request, since both send Accept: */*, and a failed navigation (an expired session, for
|
||||
// example) would be answered with a bare status code instead of the redirect to the login page this code follows.
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Accept': 'text/html'
|
||||
}
|
||||
});
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
|
||||
Reference in new issue
Block a user