mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 02: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
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a track, containing the data needed to stream, or to describe the streaming of, its audio file.
|
||||
/// </summary>
|
||||
public sealed record TrackStreamDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the file system path of the track.
|
||||
/// </summary>
|
||||
public required string Path { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library the track belongs to.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the album the track belongs to.
|
||||
/// </summary>
|
||||
public required Guid AlbumId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the artist that owns the album the track belongs to.
|
||||
/// </summary>
|
||||
public required Guid ArtistId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the audio codec used by the audio file of the track, if applicable.
|
||||
/// </summary>
|
||||
public string? AudioCodec { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the audio of the track in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the sample rate of the audio of the track in Hz.
|
||||
/// </summary>
|
||||
public int SampleRate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of audio channels of the track.
|
||||
/// </summary>
|
||||
public int Channels { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bit depth of the audio of the track, if applicable.
|
||||
/// </summary>
|
||||
public int? BitDepth { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bitrate of the audio of the track in kbps, if applicable.
|
||||
/// </summary>
|
||||
public int? Bitrate { get; init; }
|
||||
}
|
||||
+16
@@ -58,6 +58,22 @@ public interface ITrackRepository : IRepository<TrackEntity>,
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="TrackEntity"/> stored at the provided path, or an error.</returns>
|
||||
Task<Result<TrackEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the data needed to stream the audio file of the track identified by <paramref name="trackId"/>, when it belongs to the album identified by
|
||||
/// <paramref name="albumId"/> and to the media library identified by <paramref name="libraryId"/>, and that album belongs to the artist identified by
|
||||
/// <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track must belong to.</param>
|
||||
/// <param name="albumId">The Id of the album the track must belong to.</param>
|
||||
/// <param name="artistId">The Id of the artist that must own the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track whose streaming data is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the <see cref="TrackStreamDto"/> of the track, <see langword="null"/> when no track matches the
|
||||
/// provided identifiers, or an error.
|
||||
/// </returns>
|
||||
Task<Result<TrackStreamDto?>> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Resets the enrichment state of the tracks stored at the provided <paramref name="paths"/> in the media library identified by
|
||||
/// <paramref name="libraryId"/>, together with their albums and artists, so that they are re-enriched, because their content changed since the last scan.
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the audio file of a track, for streaming.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library the track belongs to, taken from the route.</param>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album of the track belongs to, taken from the route.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track whose audio file is streamed, taken from the route.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record GetTrackStreamQuery(
|
||||
string? LibraryId,
|
||||
string? ArtistId,
|
||||
string? AlbumId,
|
||||
string? TrackId
|
||||
) : IQuery;
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the audio file of a track, for streaming.
|
||||
/// </summary>
|
||||
public class GetTrackStreamQueryHandler : IQueryHandler<GetTrackStreamQuery, Result<TrackStreamDataDto>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<GetTrackStreamQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackStreamQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="pathService">Injected service for file system path related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetTrackStreamQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator<GetTrackStreamQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the audio file of a track, for streaming.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the data of the audio file of the track, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<TrackStreamDataDto>> HandleAsync(GetTrackStreamQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route identifiers are non-empty Guids before this point.
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid artistId = Guid.Parse(query.ArtistId!);
|
||||
Guid albumId = Guid.Parse(query.AlbumId!);
|
||||
Guid trackId = Guid.Parse(query.TrackId!);
|
||||
|
||||
// Admins can stream the tracks of all libraries; for everyone else, only the tracks of the libraries they own.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// The projection is filtered by the library, the album and the artist named by the route as well as by the track, so a null row
|
||||
// means the track either does not exist or is not in scope for the route, which is reported as not found without disclosing anything further.
|
||||
Result<TrackStreamDto?> getTrackResult = await _unitOfWork.TrackRepository.GetTrackStreamInfoAsync(libraryId, albumId, artistId, trackId, cancellationToken).ConfigureAwait(false);
|
||||
if (getTrackResult.IsFailure)
|
||||
return getTrackResult.Errors;
|
||||
if (getTrackResult.Value is null)
|
||||
return Errors.Music.TrackNotFound;
|
||||
TrackStreamDto track = getTrackResult.Value;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(track.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return Errors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The audio file is only served when it is stored inside one of the content locations of its library, so that a stored path can never
|
||||
// be used to read an arbitrary file of the host; the failure is reported as not found, and it never includes the path.
|
||||
if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path, contentLocation.Path)))
|
||||
return Errors.Music.TrackFileNotFound;
|
||||
|
||||
try
|
||||
{
|
||||
// The file is read once, before the response starts, so that the response can be streamed without any further database or file system work.
|
||||
FileInfo fileInformation = new(track.Path);
|
||||
if (!fileInformation.Exists)
|
||||
return Errors.Music.TrackFileNotFound;
|
||||
|
||||
long length = fileInformation.Length;
|
||||
DateTimeOffset lastModified = new(fileInformation.LastWriteTimeUtc, TimeSpan.Zero);
|
||||
return new TrackStreamDataDto(track.Path, track.Path.ToAudioFileFormat(), length, lastModified);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException)
|
||||
{
|
||||
// A file that cannot be read is indistinguishable, to the caller, from a file that does not exist, so the same not found error is returned.
|
||||
return Errors.Music.TrackFileNotFound;
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetTrackStreamQuery"/>.
|
||||
/// </summary>
|
||||
public class GetTrackStreamQueryValidator : AbstractValidator<GetTrackStreamQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackStreamQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetTrackStreamQueryValidator()
|
||||
{
|
||||
// Validates the identifier of the media library the track belongs to, taken from the route.
|
||||
RuleFor(query => query.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.LibraryId)
|
||||
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
|
||||
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the artist the album of the track belongs to, taken from the route.
|
||||
RuleFor(query => query.ArtistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.ArtistId)
|
||||
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
|
||||
.When(query => query.ArtistId is not null && query.ArtistId.Length > 0)
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the album the track belongs to, taken from the route.
|
||||
RuleFor(query => query.AlbumId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.AlbumId)
|
||||
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
|
||||
.When(query => query.AlbumId is not null && query.AlbumId.Length > 0)
|
||||
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the track whose audio file is streamed, taken from the route.
|
||||
RuleFor(query => query.TrackId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.TrackId)
|
||||
.Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty)
|
||||
.When(query => query.TrackId is not null && query.TrackId.Length > 0)
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user