mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 08:11:10 +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
+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.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user