diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index fa5e6b17..929ab62b 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -8,6 +8,9 @@ - [Get Track](#get-track) - [Get Track Request](#get-track-request) - [Get Track Response](#get-track-response) + - [Stream Track](#stream-track) + - [Stream Track Request](#stream-track-request) + - [Stream Track Response](#stream-track-response) - [Update Track](#update-track) - [Update Track Request](#update-track-request) - [Update Track Response](#update-track-response) @@ -310,6 +313,35 @@ GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b- ``` +### Stream Track + +#### Stream Track Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream +Authorization: Bearer +Range: bytes=0-1048575 +``` + +Streams the audio file of the track identified by the route, with HTTP range support. The `Range` header is optional: without it the whole file is streamed, and with it only the requested range is streamed, so that a player can start playback before the whole file is downloaded and can seek within the file. 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. + +#### Stream Track Response + +```js +200 Ok +``` + +or, when a range is requested: + +```js +206 Partial Content +Content-Range: bytes 0-1048575/3542771 +Accept-Ranges: bytes +``` + +The response is the raw bytes of the audio file, served with the media type of the file when it is an audio type, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private` and `Vary: Authorization`, together with a `Last-Modified` and an `ETag` derived from the size and the modification time of the file. + + ### Update Track #### Update Track Request diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http new file mode 100644 index 00000000..bd5cf3df --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrack.http @@ -0,0 +1,3 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}/stream +Authorization: Bearer {{ACCESS_TOKEN}} +Range: bytes=0-1048575 diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs new file mode 100644 index 00000000..3ecc0f97 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for a track, containing the data needed to stream, or to describe the streaming of, its audio file. +/// +public sealed record TrackStreamDto +{ + /// + /// Gets the file system path of the track. + /// + public required string Path { get; init; } + + /// + /// Gets the Id of the media library the track belongs to. + /// + public required Guid LibraryId { get; init; } + + /// + /// Gets the Id of the album the track belongs to. + /// + public required Guid AlbumId { get; init; } + + /// + /// Gets the Id of the artist that owns the album the track belongs to. + /// + public required Guid ArtistId { get; init; } + + /// + /// Gets the audio codec used by the audio file of the track, if applicable. + /// + public string? AudioCodec { get; init; } + + /// + /// Gets the duration of the audio of the track in seconds. + /// + public int DurationInSeconds { get; init; } + + /// + /// Gets the sample rate of the audio of the track in Hz. + /// + public int SampleRate { get; init; } + + /// + /// Gets the number of audio channels of the track. + /// + public int Channels { get; init; } + + /// + /// Gets the bit depth of the audio of the track, if applicable. + /// + public int? BitDepth { get; init; } + + /// + /// Gets the bitrate of the audio of the track in kbps, if applicable. + /// + public int? Bitrate { get; init; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs index 72f1b185..5a1eda26 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -58,6 +58,22 @@ public interface ITrackRepository : IRepository, /// An containing either the stored at the provided path, or an error. Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); + /// + /// Gets the data needed to stream the audio file of the track identified by , when it belongs to the album identified by + /// and to the media library identified by , and that album belongs to the artist identified by + /// . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose streaming data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track matches the + /// provided identifiers, or an error. + /// + Task> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken); + /// /// Resets the enrichment state of the tracks stored at the provided in the media library identified by /// , together with their albums and artists, so that they are re-enriched, because their content changed since the last scan. diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs new file mode 100644 index 00000000..6f6f2506 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQuery.cs @@ -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; + +/// +/// Query for getting the audio file of a track, for streaming. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track whose audio file is streamed, taken from the route. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetTrackStreamQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs new file mode 100644 index 00000000..d5c56f6c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get the audio file of a track, for streaming. +/// +public class GetTrackStreamQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IPathService _pathService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. + /// Injected validator for application validation rules. + public GetTrackStreamQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _pathService = pathService; + _validator = validator; + } + + /// + /// Handles the query to get the audio file of a track, for streaming. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the data of the audio file of the track, or an error message. + /// + public async Task> HandleAsync(GetTrackStreamQuery query, CancellationToken cancellationToken) + { + List 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( + 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 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 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; + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs new file mode 100644 index 00000000..4eec9b17 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetTrackStreamQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs new file mode 100644 index 00000000..08f594ae --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for the data of the audio file of a track, needed to stream it. +/// +/// The file system path of the audio file of the track. +/// The file format of the audio file of the track. +/// The length of the audio file of the track, in bytes. +/// The date and time when the audio file of the track was last modified. +[DebuggerDisplay("Format: {Format} Length: {Length}")] +public sealed record TrackStreamDataDto( + string Path, + AudioFileFormat Format, + long Length, + DateTimeOffset LastModified +); diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index a4bbe4ad..aceafa55 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -320,6 +320,43 @@ internal sealed class TrackRepository : ITrackRepository return track; } + /// + /// Gets the data needed to stream the audio file of the track identified by , when it belongs to the album identified by + /// and to the media library identified by , and that album belongs to the artist identified by + /// . + /// + /// The Id of the media library the track must belong to. + /// The Id of the album the track must belong to. + /// The Id of the artist that must own the album the track belongs to. + /// The Id of the track whose streaming data is retrieved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the of the track, when no track matches the + /// provided identifiers, or an error. + /// + public async Task> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken) + { + // The projection is flat and untracked, and the album is joined both to scope the track by its artist and to project the artist Id, so a track + // that is not in the named library, album and artist simply yields no row. + return await _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) + .Select(track => new TrackStreamDto + { + Path = track.Path, + LibraryId = track.LibraryId, + AlbumId = track.AlbumId, + ArtistId = track.Album!.ArtistId, + AudioCodec = track.AudioCodec, + DurationInSeconds = track.DurationInSeconds, + SampleRate = track.SampleRate, + Channels = track.Channels, + BitDepth = track.BitDepth, + Bitrate = track.Bitrate + }) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + } + /// /// Deletes the track identified by , together with its owned collections and contributions, by the database cascade. /// diff --git a/src/Lumina.Domain/Common/Errors/Errors.Music.cs b/src/Lumina.Domain/Common/Errors/Errors.Music.cs index b636930d..a0724fde 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Music.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Music.cs @@ -38,6 +38,7 @@ public static partial class Errors public static Error UnknownMusicKey => Error.Validation(description: nameof(UnknownMusicKey)); public static Error CatalogNumberMustBeMaximum50CharactersLong => Error.Validation(description: nameof(CatalogNumberMustBeMaximum50CharactersLong)); public static Error TrackNotFound => Error.NotFound(description: nameof(TrackNotFound)); + public static Error TrackFileNotFound => Error.NotFound(description: nameof(TrackFileNotFound)); public static Error TrackAlreadyExists => Error.Conflict(description: nameof(TrackAlreadyExists)); public static Error TrackIdCannotBeEmpty => Error.Validation(description: nameof(TrackIdCannotBeEmpty)); public static Error TracksListCannotBeNull => Error.Validation(description: nameof(TracksListCannotBeNull)); diff --git a/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs b/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs new file mode 100644 index 00000000..ba878a82 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Http/SkipEventualConsistencyMetadata.cs @@ -0,0 +1,8 @@ +namespace Lumina.Presentation.Api.Common.Http; + +/// +/// Marker metadata that opts an endpoint out of the eventual consistency pipeline, so that a long lived response (for example a track stream) never holds the request's database transaction open. +/// +public sealed class SkipEventualConsistencyMetadata +{ +} diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs index 7f16b977..76fe9689 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DomainEvents; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; +using Lumina.Presentation.Api.Common.Http; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; @@ -39,6 +40,14 @@ public class EventualConsistencyMiddleware /// In memory queue containing the queued domain events. public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue) { + // Endpoints that serve long lived responses (for example a track stream) opt out through endpoint metadata, so that their response never + // holds the request's database transaction open; the opt out is metadata based, so it follows the endpoint even when its route changes. + if (context.GetEndpoint()?.Metadata.GetMetadata() is not null) + { + await _next(context).ConfigureAwait(false); + return; + } + // begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false); // register an action to be executed once the response is completed (the user already received a response for the request) diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs index b17a5043..eb235189 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -14,5 +14,6 @@ public static partial class ApiRoutes public const string GET_TRACK_BY_ID = "/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"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs new file mode 100644 index 00000000..89971766 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpoint.cs @@ -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; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream route. +/// +public class GetTrackStreamEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getTrackStreamQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get track stream queries. + public GetTrackStreamEndpoint(IQueryHandler> getTrackStreamQueryHandler) + { + _getTrackStreamQueryHandler = getTrackStreamQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + 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())); + } + + /// + /// Streams the audio file of the track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task 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 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); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs new file mode 100644 index 00000000..a6d03136 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.sln b/src/Lumina.sln index 2614a640..9de2e1b3 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -286,6 +286,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657 ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http + ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http EndProjectSection EndProject diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs new file mode 100644 index 00000000..94c3dfea --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs @@ -0,0 +1,310 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-tests-{Guid.NewGuid():N}"); + private readonly List _temporaryFiles = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetTrackStreamEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client and the temporary content root of the test. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + Directory.CreateDirectory(_contentRootPath); + } + + [Fact] + public async Task GetTrackStream_WhenTrackBelongsToAnOwnedLibrary_ShouldStreamTheWholeAudioFile() + { + // Arrange + Guid userId = GetCurrentUserId(); + byte[] audioBytes = CreateAudioBytes(); + string trackPath = WriteContentFile("bohemian-rhapsody.mp3", audioBytes); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType); + Assert.Equal((long)audioBytes.Length, response.Content.Headers.ContentLength!.Value); + Assert.Contains("bytes", response.Headers.AcceptRanges); + Assert.NotNull(response.Headers.ETag); + Assert.NotNull(response.Content.Headers.LastModified); + Assert.Contains("nosniff", response.Headers.GetValues("X-Content-Type-Options")); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + Assert.Equal(audioBytes, await response.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task GetTrackStream_WhenARangeIsRequested_ShouldStreamOnlyTheRequestedRange() + { + // Arrange + Guid userId = GetCurrentUserId(); + byte[] audioBytes = CreateAudioBytes(); + string trackPath = WriteContentFile("love-of-my-life.mp3", audioBytes); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + using HttpRequestMessage request = new(HttpMethod.Get, $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + request.Headers.Range = new RangeHeaderValue(100, 199); + + // Act + HttpResponseMessage response = await _client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode); + Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType); + Assert.Equal(100L, response.Content.Headers.ContentLength!.Value); + Assert.Contains("bytes", response.Headers.AcceptRanges); + Assert.Equal(100L, response.Content.Headers.ContentRange!.From!.Value); + Assert.Equal(199L, response.Content.Headers.ContentRange!.To!.Value); + Assert.Equal((long)audioBytes.Length, response.Content.Headers.ContentRange!.Length!.Value); + Assert.Equal(audioBytes[100..200], await response.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task GetTrackStream_WhenTrackIsRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + string trackPath = WriteContentFile("you-re-my-best-friend.mp3", CreateAudioBytes()); + (Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenAudioFileIsMissing_ShouldReturnTrackFileNotFoundProblemWithoutLeakingThePath() + { + // Arrange + Guid userId = GetCurrentUserId(); + string trackPath = Path.Combine(_contentRootPath, "missing-file.mp3"); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain(trackPath, content, StringComparison.OrdinalIgnoreCase); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackFileNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenAudioFileIsOutsideTheLibraryContentLocations_ShouldReturnTrackFileNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + byte[] audioBytes = CreateAudioBytes(); + string outsideFilePath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-outside-{Guid.NewGuid():N}.mp3"); + await File.WriteAllBytesAsync(outsideFilePath, audioBytes); + _temporaryFiles.Add(outsideFilePath); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, outsideFilePath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain(outsideFilePath, content, StringComparison.OrdinalIgnoreCase); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackFileNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + (Guid otherUserId, _) = await SeedOtherUserAsync(); + string trackPath = WriteContentFile("news-of-the-world.mp3", CreateAudioBytes()); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Dictionary? problemDetails = JsonSerializer.Deserialize>(await response.Content.ReadAsStringAsync(), _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetTrackStream_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. + /// + /// The Id of the user that owns the library. + /// The file system path of the seeded track. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen")); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera")); + dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: trackPath, title: "A Track", includeMetadata: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user and its username. + private async Task<(Guid userId, string username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return (userId, username); + } + + /// + /// Writes an audio file with the provided inside the content root of the test, and returns its full path. + /// + /// The name of the audio file to write. + /// The bytes of the audio file to write. + /// The full path of the written audio file. + private string WriteContentFile(string fileName, byte[] audioBytes) + { + string filePath = Path.Combine(_contentRootPath, fileName); + File.WriteAllBytes(filePath, audioBytes); + return filePath; + } + + /// + /// Creates a deterministic byte array that stands in for the content of an audio file. + /// + /// The created bytes. + private static byte[] CreateAudioBytes() + { + return [.. Enumerable.Range(0, 4096).Select(index => (byte)(index % 256))]; + } + + /// + /// Reads the problem details of a response. + /// + /// The HTTP response to read. + /// The deserialized problem details. + private async Task ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources and the temporary files of the test. + /// + public async Task DisposeAsync() + { + if (Directory.Exists(_contentRootPath)) + Directory.Delete(_contentRootPath, recursive: true); + foreach (string temporaryFile in _temporaryFiles) + { + if (File.Exists(temporaryFile)) + File.Delete(temporaryFile); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs new file mode 100644 index 00000000..a0a644be --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Common.Http; +using Lumina.Presentation.Api.Common.Middlewares; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Common.Middlewares; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EventualConsistencyMiddlewareTests +{ + private readonly EventualConsistencyMiddleware _sut; + private bool _nextInvoked; + + /// + /// Initializes a new instance of the class. + /// + public EventualConsistencyMiddlewareTests() + { + ILogger mockLogger = Substitute.For>(); + _sut = new EventualConsistencyMiddleware( + context => + { + _nextInvoked = true; + return Task.CompletedTask; + }, + mockLogger); + } + + [Fact] + public async Task InvokeAsync_WhenEndpointOptsOutThroughMetadata_ShouldInvokeNextWithoutTouchingTheDatabase() + { + // Arrange + DefaultHttpContext context = new(); + context.SetEndpoint(new Endpoint( + requestDelegate: null, + new EndpointMetadataCollection(new SkipEventualConsistencyMetadata()), + displayName: "GetTrackStream")); + + // Act + // The database, the domain event publisher and the domain events queue are deliberately not supplied: an endpoint that opted out through + // metadata must invoke the next delegate without touching any of them, which is exactly what a long lived stream needs. + await _sut.InvokeAsync(context, null!, null!, null!); + + // Assert + Assert.True(_nextInvoked); + } +}