mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 04:11:10 +00:00
Adds seekable normalized audio track delivery
This commit is contained in:
1 parent
4e13b23f16
commit
45f9aa3bd5
57 files changed
+3452
-344
No files matched your search
+51
-4
@@ -4,10 +4,10 @@ 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.Playback;
|
||||
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;
|
||||
@@ -72,9 +72,31 @@ public class GetPlaybackManifestEndpoint : BaseEndpoint<GetPlaybackManifestReque
|
||||
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.
|
||||
// The API only knows the relative paths of its own stream and segment endpoints, and the browser only reaches this application, so
|
||||
// they are replaced with the paths of the streaming proxies of this application, which are the URLs the player actually consumes.
|
||||
manifest.StreamPath = BuildBrowserStreamPath(request.LibraryId, normalizedArtistId, normalizedAlbumId, normalizedTrackId);
|
||||
if (string.IsNullOrEmpty(manifest.SegmentStreamPathTemplate))
|
||||
{
|
||||
manifest.DeliveryId = null;
|
||||
manifest.SegmentStreamPathTemplate = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The API decides how its delivery is addressed: the web app only rewrites the path it reported, and only requires the opaque
|
||||
// handle the path needs. It never infers the addressing from the direct play flag.
|
||||
if (!PlaybackDeliveryId.IsValid(manifest.DeliveryId))
|
||||
throw new ApiException(new ProblemDetailsDto
|
||||
{
|
||||
Title = "General.Failure",
|
||||
Detail = "InternalServerError",
|
||||
Status = StatusCodes.Status502BadGateway
|
||||
}, HttpStatusCode.BadGateway, endpoint);
|
||||
manifest.SegmentStreamPathTemplate = BuildBrowserSegmentStreamPath(request.LibraryId, normalizedArtistId, normalizedAlbumId, normalizedTrackId);
|
||||
}
|
||||
// The manifest is specific to the authenticated user and carries a stateful delivery handle, so the browser hop never stores it publicly and
|
||||
// it varies by the cookie that authenticates this hop.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
return JsonSuccess(manifest);
|
||||
}
|
||||
|
||||
@@ -104,12 +126,37 @@ public class GetPlaybackManifestEndpoint : BaseEndpoint<GetPlaybackManifestReque
|
||||
return $"{pathBase}/{streamPath}?libraryId={libraryId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the browser facing relative path template of the segment streaming proxy of this application for the track identified by the given Ids.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The placeholders of the route template are replaced with the Ids the manifest was requested for, and the delivery handle and segment index
|
||||
/// placeholders are kept for the player to expand. The player substitutes the handle the manifest reported, so the segment request addresses
|
||||
/// exactly the delivery that manifest declared, and the path is built exactly like the track stream path, so it can only ever point at this 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 template the browser fetches a segment from, on its own origin.</returns>
|
||||
private string BuildBrowserSegmentStreamPath(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 segmentPath = WebRoutes.Music.STREAM_TRACK_SEGMENT
|
||||
.Replace("{culture}", culture, StringComparison.OrdinalIgnoreCase)
|
||||
.Replace("{artistId}", artistId, StringComparison.Ordinal)
|
||||
.Replace("{albumId}", albumId, StringComparison.Ordinal)
|
||||
.Replace("{trackId}", trackId, StringComparison.Ordinal);
|
||||
return $"{pathBase}/{segmentPath}?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)
|
||||
private static bool IsSafePathSegment(string? value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
return false;
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ public class GetPlaybackManifestEndpointSummary : Summary<GetPlaybackManifestEnd
|
||||
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.";
|
||||
Description = "Retrieves the playback manifest of the music track identified by the route, with the stream path and the segment path template replaced by the URLs of the streaming proxies of this application. A normalized delivery also carries the opaque delivery handle the segment proxy forwards, so the segments are addressed by the delivery the manifest declared.";
|
||||
|
||||
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.");
|
||||
|
||||
+3
-59
@@ -2,6 +2,7 @@
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Common;
|
||||
@@ -10,7 +11,6 @@ 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
|
||||
@@ -76,16 +76,8 @@ public class StreamMusicTrackEndpoint : BaseEndpoint<StreamMusicTrackRequest, IR
|
||||
|
||||
// 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);
|
||||
{ // The proxy owns the status, header, caching and body rules shared with the normalized segment proxy.
|
||||
await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return Results.Empty;
|
||||
}
|
||||
@@ -101,52 +93,4 @@ public class StreamMusicTrackEndpoint : BaseEndpoint<StreamMusicTrackRequest, IR
|
||||
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();
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Playback;
|
||||
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.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}</c> route.
|
||||
/// </summary>
|
||||
public class StreamMusicTrackSegmentEndpoint : BaseEndpoint<StreamMusicTrackSegmentRequest, IResult>
|
||||
{
|
||||
private readonly IStreamingApiHttpClient _streamingApiHttpClient;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="streamingApiHttpClient">Injected service for streaming interactions with the API.</param>
|
||||
public StreamMusicTrackSegmentEndpoint(IStreamingApiHttpClient streamingApiHttpClient)
|
||||
{
|
||||
_streamingApiHttpClient = streamingApiHttpClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
base.Configure();
|
||||
Verbs(Http.GET);
|
||||
Routes(WebRoutes.Music.STREAM_TRACK_SEGMENT);
|
||||
DontAutoTag();
|
||||
// The segment stream is bounded per user with the same concurrency limit as the track stream, so a single user can never hold an
|
||||
// unbounded number of long lived responses open at once and exhaust the connections towards the API.
|
||||
Options(options => options
|
||||
.WithTags("Music")
|
||||
.RequireRateLimiting(PresentationWebLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Streams one segment of the normalized audio 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, the delivery handle, and the segment index.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(StreamMusicTrackSegmentRequest 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();
|
||||
// The handle has exactly one accepted format, so it is never normalized into another value that would silently address a different delivery.
|
||||
if (!PlaybackDeliveryId.IsValid(request.DeliveryId))
|
||||
{
|
||||
HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
HttpContext.Response.ContentLength = 0;
|
||||
return Results.Empty;
|
||||
}
|
||||
string endpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT
|
||||
.Replace("{libraryId}", request.LibraryId.ToString())
|
||||
.Replace("{artistId}", normalizedArtistId)
|
||||
.Replace("{albumId}", normalizedAlbumId)
|
||||
.Replace("{trackId}", normalizedTrackId)
|
||||
.Replace("{deliveryId}", request.DeliveryId)
|
||||
.Replace("{segmentIndex}", request.SegmentIndex.ToString());
|
||||
|
||||
// The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading.
|
||||
ApiStreamResult streamResult;
|
||||
try
|
||||
{
|
||||
streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, new Dictionary<string, string>(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ApiException apiException) when (apiException.HttpStatusCode is HttpStatusCode.ServiceUnavailable or HttpStatusCode.TooManyRequests)
|
||||
{
|
||||
// A busy normalization pipeline or the stream concurrency limit is an expected, transient condition that the player retries. It is
|
||||
// answered with a bare status instead of being logged as an unexpected API failure with a stack trace.
|
||||
HttpContext.Response.StatusCode = (int)apiException.HttpStatusCode;
|
||||
HttpContext.Response.ContentLength = 0;
|
||||
return Results.Empty;
|
||||
}
|
||||
await using (streamResult) // The proxy owns the status, header, caching and body rules shared with the direct track stream proxy.
|
||||
await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false);
|
||||
return Results.Empty;
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#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.StreamMusicTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="StreamMusicTrackSegmentEndpoint"/> endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackSegmentEndpointSummary : Summary<StreamMusicTrackSegmentEndpoint, StreamMusicTrackSegmentRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackSegmentEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public StreamMusicTrackSegmentEndpointSummary()
|
||||
{
|
||||
Summary = "Streams one segment of the normalized audio of a music track.";
|
||||
Description = "Streams one fixed duration segment of the normalized audio of the music track identified by the route, through the API. A track the player cannot play directly is delivered as time addressed segments, so the player seeks by segment index instead of by byte range. The delivery handle is the opaque value the playback manifest reported, and it binds the segment to exactly the delivery that manifest declared.";
|
||||
|
||||
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.DeliveryId, "The opaque handle of the normalized delivery, reported by the playback manifest. Required.");
|
||||
RequestParam(r => r.SegmentIndex, "The zero based index of the segment of the normalized audio. Required.");
|
||||
RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required.");
|
||||
|
||||
Response(200, "The requested segment of the normalized audio of the track is streamed.");
|
||||
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, the media library, the delivery handle, or the requested segment was not found, or is out of the scope of the route.");
|
||||
Response(409, "The delivery handle no longer describes the delivery, or the source file changed. The player requests the manifest again.");
|
||||
Response(429, "The user is already holding the maximum number of concurrent track streams.");
|
||||
Response(502, "The remote API did not return the segment of the normalized audio of the track.");
|
||||
Response(503, "The normalization pipeline is temporarily busy. The player retries the request.");
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@
|
||||
updatePlaybackStateUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.UPDATE_PLAYBACK_STATE)',
|
||||
getPlaybackManifestUrl: '@_urlService.GetRelativeUrl(WebRoutes.Music.GET_PLAYBACK_MANIFEST)',
|
||||
streamTrackRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Music.STREAM_TRACK)',
|
||||
streamTrackSegmentRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Music.STREAM_TRACK_SEGMENT)',
|
||||
strings: {
|
||||
play: '@localizer["AudioPlayerPlay"]',
|
||||
pause: '@localizer["AudioPlayerPause"]',
|
||||
@@ -85,5 +86,6 @@
|
||||
<script defer src="~/js/audio-player/audio-player.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-manifest.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js" asp-append-version="true"></script>
|
||||
Reference in new issue
Block a user