mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 13:11:10 +00:00
Adds the music track stream endpoint
Adds the track stream route, its query, validator and handler, a flat stream projection in the track repository, and an endpoint that streams the audio file with HTTP range support. Excludes the route from the eventual consistency pipeline through endpoint metadata and limits it per user with a concurrency limiter. Missing, unreadable and out of scope files are reported as not found without leaking the path. Adds the API and request documentation and the stream tests.
This commit is contained in:
1 parent
0ad6e1307b
commit
4ffa81fffe
18 files changed
+985
No files matched your search
+86
@@ -0,0 +1,86 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Api.Common.Http;
|
||||
using Lumina.Presentation.Api.Common.MimeTypes;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream</c> route.
|
||||
/// </summary>
|
||||
public class GetTrackStreamEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetTrackStreamQuery, Result<TrackStreamDataDto>> _getTrackStreamQueryHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackStreamEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="getTrackStreamQueryHandler">Injected service for handling get track stream queries.</param>
|
||||
public GetTrackStreamEndpoint(IQueryHandler<GetTrackStreamQuery, Result<TrackStreamDataDto>> getTrackStreamQueryHandler)
|
||||
{
|
||||
_getTrackStreamQueryHandler = getTrackStreamQueryHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(Http.GET);
|
||||
Routes(ApiRoutes.Tracks.STREAM_TRACK);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
// The stream is limited per user with a concurrency limiter (never with the login rate limit policy), and it is excluded from the eventual
|
||||
// consistency pipeline, because a long lived audio response would otherwise hold the request's database transaction open for its whole duration.
|
||||
Options(builder => builder
|
||||
.RequireRateLimiting(PresentationApiLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY)
|
||||
.WithMetadata(new SkipEventualConsistencyMetadata()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Streams the audio file of the track identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take unique identifiers from the route.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
|
||||
string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
|
||||
string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString();
|
||||
GetTrackStreamQuery query = new(libraryId, artistId, albumId, trackId);
|
||||
Result<TrackStreamDataDto> result = await _getTrackStreamQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
if (result.IsFailure)
|
||||
return Problem(result.Errors);
|
||||
|
||||
// Audio is inert content, but it is still served with content sniffing disabled, so that a file with an unexpected extension is never interpreted as active content.
|
||||
HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff";
|
||||
// The audio is private to the authenticated user and its bytes must never be stored by an intermediary, so it is not publicly cacheable and it varies by the bearer token.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private";
|
||||
HttpContext.Response.Headers["Vary"] = "Authorization";
|
||||
|
||||
// The entity tag is derived from the size and the last modification time of the file, never from its path or its name, so no file system detail is exposed, and no download name is passed, so no Content-Disposition is emitted.
|
||||
EntityTagHeaderValue entityTag = new($"\"{result.Value.LastModified.ToUnixTimeSeconds()}-{result.Value.Length}\"");
|
||||
return TypedResults.PhysicalFile(
|
||||
result.Value.Path,
|
||||
MusicMimeTypes.GetMimeType(result.Value.Format),
|
||||
fileDownloadName: null,
|
||||
enableRangeProcessing: true,
|
||||
lastModified: result.Value.LastModified,
|
||||
entityTag: entityTag);
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetTrackStreamEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackStreamEndpointSummary : Summary<GetTrackStreamEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackStreamEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public GetTrackStreamEndpointSummary()
|
||||
{
|
||||
Summary = "Streams the audio file of a track.";
|
||||
Description = "Streams the audio file of the track identified by the route, with HTTP range support, so that a player can start playback before the whole file is downloaded and can seek within it. The audio file is streamed to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track.";
|
||||
|
||||
Response(200, "The audio file of the track is streamed, with the media type of the file when it is an audio type, or application/octet-stream otherwise, and with the length of the file as its content length.", "*/*");
|
||||
|
||||
Response(206, "The requested range of the audio file of the track is streamed, with the range in the Content-Range header and its length as the content length.", "*/*");
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||
title = "General.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the track or its media library does not exist, the track does not belong to the library, album and artist named by the route, or the audio file of the track is outside the content locations of its library, missing, or unreadable.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "TrackNotFound",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "LibraryNotFound",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "TrackFileNotFound",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(416, "The request failed because the requested range is not satisfiable for the size of the audio file.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.17",
|
||||
title = "RangeNotSatisfiable",
|
||||
status = 416,
|
||||
detail = "The requested range is not satisfiable.",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream"
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"LibraryIdCannotBeEmpty",
|
||||
"ArtistIdCannotBeEmpty",
|
||||
"AlbumIdCannotBeEmpty",
|
||||
"TrackIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user