diff --git a/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbumCover.http b/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbumCover.http new file mode 100644 index 00000000..147a43cf --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbumCover.http @@ -0,0 +1,10 @@ +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}}/cover +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: multipart/form-data; boundary=LuminaBoundary + +--LuminaBoundary +Content-Disposition: form-data; name="cover"; filename="cover.jpg" +Content-Type: image/jpeg + +< ./cover.jpg +--LuminaBoundary-- diff --git a/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtistCover.http b/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtistCover.http new file mode 100644 index 00000000..a83a3218 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtistCover.http @@ -0,0 +1,10 @@ +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/cover +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: multipart/form-data; boundary=LuminaBoundary + +--LuminaBoundary +Content-Disposition: form-data; name="cover"; filename="cover.jpg" +Content-Type: image/jpeg + +< ./cover.jpg +--LuminaBoundary-- diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommand.cs new file mode 100644 index 00000000..69f8d7da --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommand.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +using System.IO; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; + +/// +/// Command for updating the cover image of an existing album. +/// +/// The unique identifier of the media library the album belongs to, taken from the route. +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album whose cover image is updated, taken from the route. +/// The stream of the uploaded cover image file. +/// The name of the uploaded cover image file. +[DebuggerDisplay("AlbumId: {AlbumId} FileName: {FileName}")] +public record UpdateAlbumCoverCommand( + string? LibraryId, + string? ArtistId, + string? AlbumId, + Stream? Cover, + string? FileName +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs new file mode 100644 index 00000000..cc24503b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs @@ -0,0 +1,198 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +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.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; + +/// +/// Handler for the command to update the cover image of an existing album. +/// +public class UpdateAlbumCoverCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IMusicArtworkService _musicArtworkService; + private readonly IPathService _pathService; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + 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 storing the artwork of a music library item. + /// Injected service for handling file system paths. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public UpdateAlbumCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IPathService pathService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _musicArtworkService = musicArtworkService; + _pathService = pathService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to update the cover image of an existing album. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the response carrying the relative path of the stored cover image, or an error message. + /// + public async Task> HandleAsync(UpdateAlbumCoverCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + 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(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + return DomainErrors.Music.AlbumNotFound; + AlbumEntity existingAlbum = getAlbumResult.Value; + + // Resource scoping: the album must belong to the library and the artist named by the route, so that an album can never be edited through + // another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere. + if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId) + return DomainErrors.Music.AlbumNotFound; + + // Admins can update the albums of all libraries; for everyone else, only the albums of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingAlbum.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + string libraryName = getLibraryResult.Value.Title; + + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(existingAlbum.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + string artistName = getArtistResult.Value?.Name ?? string.Empty; + + // The artwork of the album is stored under the directory of its release type, mirroring the structure of the scanned files, so that a + // re-uploaded cover replaces the cover stored for the album at its standardized location instead of writing a second copy elsewhere. + Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false); + if (getArtworkResult.IsFailure) + return getArtworkResult.Errors; + string? existingCoverPath = getArtworkResult.Value + .Where(artwork => artwork.ArtworkType == ArtworkType.Cover) + .Select(artwork => artwork.FileName) + .FirstOrDefault(); + string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName) + ?? (existingAlbum.ReleaseTypes.Count > 0 ? existingAlbum.ReleaseTypes[0].ReleaseType.ToString() : null); + + Result storeArtworkResult = await _musicArtworkService.SaveAlbumArtworkAsync( + existingAlbum.LibraryId, + existingAlbum.Id, + libraryName, + artistName, + existingAlbum.Title, + command.Cover!, + command.FileName!, + releaseTypeName, + cancellationToken).ConfigureAwait(false); + if (storeArtworkResult.IsFailure) + return storeArtworkResult.Errors; + + // The stored cover of the album is replaced as a whole: when the new cover is stored under a different name than the previous one + // (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference. + if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value) + { + Result deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath); + if (deleteResult.IsFailure) + return deleteResult.Errors; + } + + // Map the newly stored cover image onto the artwork of the album, replacing the existing cover or adding a new one. + Result upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync( + MusicArtworkOwnerType.Album, albumId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return upsertResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return new UpdateAlbumCoverResponse(storeArtworkResult.Value); + } + + /// + /// Resolves the name of the release type directory the artwork of an album is stored under, from the relative path of its existing cover. + /// + /// The relative path of the existing cover image of the album, or when the album has no cover. + /// The name of the artist of the album. + /// The name of the on-disk release type directory, or when the album does not use one. + private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName) + { + if (string.IsNullOrWhiteSpace(coverRelativePath)) + return null; + // The path is media/music/{library}/{artist}[/{releaseType}]/{album}/{file}, so the segment right before the album directory is the release + // type directory when the album uses one, and the artist directory otherwise. An artist whose name happens to match a release type, like + // "Live", must not be mistaken for one, so the segment is only accepted as a release type when it is not the directory of the artist. + string[] segments = coverRelativePath.Split(_pathService.PathSeparator, StringSplitOptions.RemoveEmptyEntries); + if (segments.Length < 3) + return null; + string candidate = segments[^3]; + if (IsArtistDirectory(candidate, artistName)) + return null; + return Enum.TryParse(candidate, ignoreCase: true, out MusicReleaseType releaseType) && Enum.IsDefined(releaseType) ? candidate : null; + } + + /// + /// Checks whether the provided path segment is the artwork directory of the artist of the album. + /// + /// The path segment to be checked. + /// The name of the artist of the album. + /// when the segment is the artwork directory of the artist, otherwise. + private bool IsArtistDirectory(string pathSegment, string artistName) + { + if (string.IsNullOrWhiteSpace(artistName)) + return false; + Result artistSegmentResult = _pathService.SanitizeSegment(artistName); + return artistSegmentResult.IsSuccess + && string.Equals(pathSegment, artistSegmentResult.Value.Name, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidator.cs new file mode 100644 index 00000000..8d9792eb --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidator.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.Albums.Commands.UpdateAlbumCover; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateAlbumCoverCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateAlbumCoverCommandValidator() + { + // Validates the identifier of the media library the album belongs to, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album belongs to, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album whose cover image is updated, taken from the route. + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the uploaded cover image. + RuleFor(command => command.Cover) + .NotNull() + .WithError(Errors.Music.CoverCannotBeNull); + + RuleFor(command => command.FileName) + .NotEmpty() + .When(command => command.Cover is not null) + .WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommand.cs new file mode 100644 index 00000000..98bb23f2 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommand.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +using System.IO; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; + +/// +/// Command for updating the cover image of an existing artist. +/// +/// The unique identifier of the media library this artist belongs to, taken from the route. +/// The unique identifier of the artist whose cover image is updated, taken from the route. +/// The stream of the uploaded cover image file. +/// The name of the uploaded cover image file. +[DebuggerDisplay("ArtistId: {ArtistId} FileName: {FileName}")] +public record UpdateArtistCoverCommand( + string? LibraryId, + string? ArtistId, + Stream? Cover, + string? FileName +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs new file mode 100644 index 00000000..7b84738e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs @@ -0,0 +1,144 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +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.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; + +/// +/// Handler for the command to update the cover image of an existing artist. +/// +public class UpdateArtistCoverCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IMusicArtworkService _musicArtworkService; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + 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 storing the artwork of a music library item. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public UpdateArtistCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _musicArtworkService = musicArtworkService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to update the cover image of an existing artist. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the response carrying the relative path of the stored cover image, or an error message. + /// + public async Task> HandleAsync(UpdateArtistCoverCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + 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(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the artist must belong to the library named by the route, so that an artist can never be edited through another + // library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return DomainErrors.Music.ArtistNotFound; + + // Admins can update the artists of all libraries; for everyone else, only the artists of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingArtist.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + string libraryName = getLibraryResult.Value.Title; + + // The existing cover of the artist is looked up, so that the previous file can be replaced as a whole instead of being left orphaned on disk. + Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false); + if (getArtworkResult.IsFailure) + return getArtworkResult.Errors; + string? existingCoverPath = getArtworkResult.Value + .Where(artwork => artwork.ArtworkType == ArtworkType.Cover) + .Select(artwork => artwork.FileName) + .FirstOrDefault(); + + Result storeArtworkResult = await _musicArtworkService.SaveArtistArtworkAsync( + existingArtist.LibraryId, + libraryName, + existingArtist.Name, + command.Cover!, + command.FileName!, + cancellationToken).ConfigureAwait(false); + if (storeArtworkResult.IsFailure) + return storeArtworkResult.Errors; + + // The stored cover of the artist is replaced as a whole: when the new cover is stored under a different name than the previous one + // (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference. + if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value) + { + Result deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath); + if (deleteResult.IsFailure) + return deleteResult.Errors; + } + + // Map the newly stored cover image onto the artwork of the artist, replacing the existing cover or adding a new one. + Result upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync( + MusicArtworkOwnerType.Artist, artistId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return upsertResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return new UpdateArtistCoverResponse(storeArtworkResult.Value); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidator.cs new file mode 100644 index 00000000..384522da --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidator.cs @@ -0,0 +1,50 @@ +#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.Artists.Commands.UpdateArtistCover; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateArtistCoverCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistCoverCommandValidator() + { + // Validates the identifier of the media library the artist belongs to, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist whose cover image is updated, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the uploaded cover image. + RuleFor(command => command.Cover) + .NotNull() + .WithError(Errors.Music.CoverCannotBeNull); + + RuleFor(command => command.FileName) + .NotEmpty() + .When(command => command.Cover is not null) + .WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } +} diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponse.cs new file mode 100644 index 00000000..eb6ca6a4 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a response of an update album cover operation. +/// +/// The relative path of the stored cover image. +[DebuggerDisplay("CoverPath: {CoverPath}")] +public record UpdateAlbumCoverResponse( + string CoverPath +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponse.cs new file mode 100644 index 00000000..dc45d9f9 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a response of an update artist cover operation. +/// +/// The relative path of the stored cover image. +[DebuggerDisplay("CoverPath: {CoverPath}")] +public record UpdateArtistCoverResponse( + string CoverPath +); diff --git a/src/Lumina.Domain/Common/Errors/Errors.Music.cs b/src/Lumina.Domain/Common/Errors/Errors.Music.cs index d4cca16a..b636930d 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Music.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Music.cs @@ -65,5 +65,6 @@ public static partial class Errors public static Error IsniValueCannotBeEmpty => Error.Validation(description: nameof(IsniValueCannotBeEmpty)); public static Error IsniValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IsniValueMustBeMaximum20CharactersLong)); public static Error WorkTitleCannotBeEmpty => Error.Validation(description: nameof(WorkTitleCannotBeEmpty)); + public static Error CoverCannotBeNull => Error.Validation(description: nameof(CoverCannotBeNull)); } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs index dd1fafd4..2933c8f6 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs @@ -15,6 +15,7 @@ public static partial class ApiRoutes public const string ADD_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums"; public const string GET_ALBUM_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string UPDATE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; + public const string UPDATE_ALBUM_COVER = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover"; public const string DELETE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; public const string GET_ALBUM_TRACKS = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"; public const string GET_ALBUM_TRACKS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite"; diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs index b3d50a4a..d8c1bd07 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs @@ -15,6 +15,7 @@ public static partial class ApiRoutes public const string GET_ARTISTS_LITE = "/libraries/{libraryId}/artists/lite"; public const string ADD_ARTIST = "/libraries/{libraryId}/artists"; public const string UPDATE_ARTIST = "/libraries/{libraryId}/artists/{artistId}"; + public const string UPDATE_ARTIST_COVER = "/libraries/{libraryId}/artists/{artistId}/cover"; public const string DELETE_ARTIST = "/libraries/{libraryId}/artists/{artistId}"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpoint.cs new file mode 100644 index 00000000..fc91b7ac --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpoint.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover route. +/// +public class UpdateAlbumCoverEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updateAlbumCoverCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update album cover commands. + public UpdateAlbumCoverEndpoint(ICommandHandler> updateAlbumCoverCommandHandler) + { + _updateAlbumCoverCommandHandler = updateAlbumCoverCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Albums.UPDATE_ALBUM_COVER); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the cover image of the album with the image uploaded in the multipart form of the request. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take the 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(); + + IFormFile? cover = null; + if (HttpContext.Request.HasFormContentType) + { + try + { + // The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form, + // so a malformed upload is treated as a missing cover, which the command validator reports. + cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null; + } + catch (InvalidDataException) + { + cover = null; + } + } + + // The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns. + UpdateAlbumCoverCommand command = new(libraryId, artistId, albumId, cover?.OpenReadStream(), cover?.FileName); + try + { + Result result = await _updateAlbumCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } + finally + { + command.Cover?.Dispose(); + } + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointSummary.cs new file mode 100644 index 00000000..318c3267 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointSummary.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCoverEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateAlbumCoverEndpointSummary() + { + Summary = "Updates the cover image of an album."; + Description = "Updates the cover image of the album identified by the route, with the image uploaded in the multipart form of the request."; + + Response(200, "The relative path of the stored cover image is returned.", + example: new UpdateAlbumCoverResponse( + CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/A Night at the Opera-7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f/cover.jpg" + ) + ); + + 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()}/cover" + } + } + ); + + 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()}/cover", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the album or its media library does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", + 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()}/cover", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "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()}/cover", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "CoverCannotBeNull", + "FileNameCannotBeEmpty", + "FileTooLarge", + "CoverFileMustBeAnImage" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpoint.cs new file mode 100644 index 00000000..9439978d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpoint.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/cover route. +/// +public class UpdateArtistCoverEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updateArtistCoverCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update artist cover commands. + public UpdateArtistCoverEndpoint(ICommandHandler> updateArtistCoverCommandHandler) + { + _updateArtistCoverCommandHandler = updateArtistCoverCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Artists.UPDATE_ARTIST_COVER); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the cover image of the artist with the image uploaded in the multipart form of the request. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take the identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + + IFormFile? cover = null; + if (HttpContext.Request.HasFormContentType) + { + try + { + // The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form, + // so a malformed upload is treated as a missing cover, which the command validator reports. + cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null; + } + catch (InvalidDataException) + { + cover = null; + } + } + + // The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns. + UpdateArtistCoverCommand command = new(libraryId, artistId, cover?.OpenReadStream(), cover?.FileName); + try + { + Result result = await _updateArtistCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } + finally + { + command.Cover?.Dispose(); + } + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointSummary.cs new file mode 100644 index 00000000..c3a39e0a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointSummary.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCoverEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistCoverEndpointSummary() + { + Summary = "Updates the cover image of an artist."; + Description = "Updates the cover image of the artist identified by the route, with the image uploaded in the multipart form of the request."; + + Response(200, "The relative path of the stored cover image is returned.", + example: new UpdateArtistCoverResponse( + CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" + ) + ); + + 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()}/cover" + } + } + ); + + 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()}/cover", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the artist or its media library does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", + 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()}/cover", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "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()}/cover", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "CoverCannotBeNull", + "FileNameCannotBeEmpty", + "FileTooLarge", + "CoverFileMustBeAnImage" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.sln b/src/Lumina.sln index 23593842..2614a640 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -265,6 +265,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "albums", "albums", "{B4DF8E ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http + ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbumCover.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbumCover.http EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F3818697-E304-491D-8BF3-4DAA1733B5F5}" @@ -277,6 +278,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F381 ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http + ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtistCover.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtistCover.http EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657B1-60DC-4E22-89D2-6212154D6BA8}" diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandFixture.cs new file mode 100644 index 00000000..b242c423 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandFixture.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCoverCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the album belongs to. + /// Optional. The Id of the artist the album belongs to. + /// Optional. The Id of the album whose cover is updated. + /// Optional. The stream of the uploaded cover image file. + /// Optional. The name of the uploaded cover image file. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// Whether the cover stream should be included, or forced to . + /// Whether the file name should be included, or forced to . + /// The created . + public UpdateAlbumCoverCommand Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + Stream? cover = null, + string? fileName = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includeCover = true, + bool includeFileName = true) + { + return new UpdateAlbumCoverCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null, + includeCover ? (cover ?? CreateCoverStream()) : null, + includeFileName ? (fileName ?? "cover.jpg") : null); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates an in-memory stream carrying a minimal file payload. + /// + /// A non-empty in-memory stream. + private static Stream CreateCoverStream() + { + byte[] payload = Encoding.UTF8.GetBytes("fake cover payload"); + return new MemoryStream(payload); + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandFixture.cs new file mode 100644 index 00000000..6235be2d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandFixture.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCoverCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the artist belongs to. + /// Optional. The Id of the artist whose cover is updated. + /// Optional. The stream of the uploaded cover image file. + /// Optional. The name of the uploaded cover image file. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the cover stream should be included, or forced to . + /// Whether the file name should be included, or forced to . + /// The created . + public UpdateArtistCoverCommand Create( + string? libraryId = null, + string? artistId = null, + Stream? cover = null, + string? fileName = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeCover = true, + bool includeFileName = true) + { + return new UpdateArtistCoverCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeCover ? (cover ?? CreateCoverStream()) : null, + includeFileName ? (fileName ?? "cover.jpg") : null); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates an in-memory stream carrying a minimal file payload. + /// + /// A non-empty in-memory stream. + private static Stream CreateCoverStream() + { + byte[] payload = Encoding.UTF8.GetBytes("fake cover payload"); + return new MemoryStream(payload); + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponseFixture.cs new file mode 100644 index 00000000..1cd18954 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponseFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCoverResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The relative path of the stored cover image. + /// The created . + public UpdateAlbumCoverResponse Create(string? coverPath = null) + { + return new UpdateAlbumCoverResponse( + coverPath ?? _faker.System.FilePath() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponseFixture.cs new file mode 100644 index 00000000..0bdb8166 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponseFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCoverResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The relative path of the stored cover image. + /// The created . + public UpdateArtistCoverResponse Create(string? coverPath = null) + { + return new UpdateArtistCoverResponse( + coverPath ?? _faker.System.FilePath() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs new file mode 100644 index 00000000..91ea5e92 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs @@ -0,0 +1,382 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +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.Albums.UpdateAlbumCover; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCoverEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + 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 MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateAlbumCoverEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdateAlbumCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumWithCoverAsync(userId, "/media/music/old-cover.jpg"); + + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + string storedPath = JsonSerializer.Deserialize(content, _jsonOptions)!.CoverPath; + Assert.False(string.IsNullOrWhiteSpace(storedPath)); + Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + MusicArtworkEntity coverArtwork = dbContext.MusicArtwork + .Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId && artwork.ArtworkType == ArtworkType.Cover); + Assert.Equal(storedPath, coverArtwork.FileName); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + } + + [Fact] + public async Task UpdateAlbumCover_WhenAlbumHasNoExistingCover_ShouldCreateACoverArtwork() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId); + + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + string storedPath = JsonSerializer.Deserialize(content, _jsonOptions)!.CoverPath; + Assert.False(string.IsNullOrWhiteSpace(storedPath)); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + MusicArtworkEntity coverArtwork = dbContext.MusicArtwork + .Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId && artwork.ArtworkType == ArtworkType.Cover); + Assert.Equal(storedPath, coverArtwork.FileName); + } + + [Fact] + public async Task UpdateAlbumCover_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId); + string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertNotFoundAsync(response, "AlbumNotFound", url); + } + + [Fact] + public async Task UpdateAlbumCover_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId); + Guid otherLibraryId = Guid.NewGuid(); + string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums/{albumId}/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertNotFoundAsync(response, "AlbumNotFound", url); + } + + [Fact] + public async Task UpdateAlbumCover_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId); + string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4"); + } + + [Fact] + public async Task UpdateAlbumCover_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover"; + + // Act + HttpResponseMessage response = await unauthenticatedClient.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Fact] + public async Task UpdateAlbumCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithCoverCannotBeNull() + { + // Arrange + MultipartFormDataContent form = []; + form.Add(new StringContent("unrelated-field"), "unrelated-field"); + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, form); + + // Assert + await AssertUnprocessableEntityWithValidationErrors(response, url, "CoverCannotBeNull"); + } + + [Fact] + public async Task UpdateAlbumCover_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Arrange + string url = $"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{Guid.NewGuid()}/albums/not-a-guid/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty"); + } + + /// + /// Creates a multipart form carrying a minimal PNG-like payload. + /// + /// The name of the uploaded file. + /// A configured instance. + private static MultipartFormDataContent CreateCoverForm(string fileName) + { + // The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer. + byte[] payload = new byte[100]; + payload[0] = 137; + payload[1] = 80; + payload[2] = 78; + payload[3] = 71; + payload[4] = 13; + payload[5] = 10; + payload[6] = 26; + payload[7] = 10; + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(payload); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, "cover", fileName); + return form; + } + + /// + /// Seeds a music library owned by , together with an artist and one of its albums that has no cover yet. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId); + } + + /// + /// Seeds a music library owned by , together with an artist and one of its albums that already has a cover. + /// + /// The Id of the user that owns the library. + /// The relative path of the existing cover of the album. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumWithCoverAsync(Guid userId, string existingCoverFileName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: existingCoverFileName, status: ArtworkStatus.Enriched)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// 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; + } + + /// + /// Asserts that the response is a not found problem details carrying the expected detail and request instance path. + /// + /// The HTTP response to assert on. + /// The expected problem detail. + /// The expected request instance path. + private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance) + { + await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5"); + } + + /// + /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type. + /// + /// The HTTP response to assert on. + /// The expected HTTP status code. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + /// The expected problem type URI. + private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType) + { + Assert.Equal(statusCode, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedType, problemDetails["type"].GetString()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"])); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs new file mode 100644 index 00000000..ee8d938b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs @@ -0,0 +1,391 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +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.Artists.UpdateArtistCover; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCoverEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateArtistCoverEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdateArtistCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistWithCoverAsync(userId, "/media/music/old-artist-cover.jpg"); + + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + string storedPath = JsonSerializer.Deserialize(content, _jsonOptions)!.CoverPath; + Assert.False(string.IsNullOrWhiteSpace(storedPath)); + Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + MusicArtworkEntity coverArtwork = dbContext.MusicArtwork + .Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId && artwork.ArtworkType == ArtworkType.Cover); + Assert.Equal(storedPath, coverArtwork.FileName); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + } + + [Fact] + public async Task UpdateArtistCover_WhenArtistHasNoExistingCover_ShouldCreateACoverArtwork() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId); + + // Act + HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", CreateCoverForm("cover.png")); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + string storedPath = JsonSerializer.Deserialize(content, _jsonOptions)!.CoverPath; + Assert.False(string.IsNullOrWhiteSpace(storedPath)); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + MusicArtworkEntity coverArtwork = dbContext.MusicArtwork + .Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId && artwork.ArtworkType == ArtworkType.Cover); + Assert.Equal(storedPath, coverArtwork.FileName); + } + + [Fact] + public async Task UpdateArtistCover_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertNotFoundAsync(response, "ArtistNotFound", url); + } + + [Fact] + public async Task UpdateArtistCover_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid artistId) = await SeedLibraryAndArtistAsync(userId); + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertNotFoundAsync(response, "ArtistNotFound", url); + } + + [Fact] + public async Task UpdateArtistCover_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId); + string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4"); + } + + [Fact] + public async Task UpdateArtistCover_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover"; + + // Act + HttpResponseMessage response = await unauthenticatedClient.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Fact] + public async Task UpdateArtistCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithCoverCannotBeNull() + { + // Arrange + MultipartFormDataContent form = []; + form.Add(new StringContent("unrelated-field"), "unrelated-field"); + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, form); + + // Assert + await AssertUnprocessableEntityWithValidationErrors(response, url, "CoverCannotBeNull"); + } + + [Fact] + public async Task UpdateArtistCover_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Arrange + string url = $"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/not-a-guid/cover"; + + // Act + HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png")); + + // Assert + await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty"); + } + + /// + /// Creates a multipart form carrying a minimal PNG-like payload. + /// + /// The name of the uploaded file. + /// A configured instance. + private static MultipartFormDataContent CreateCoverForm(string fileName) + { + // The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer. + byte[] payload = new byte[100]; + payload[0] = 137; + payload[1] = 80; + payload[2] = 78; + payload[3] = 71; + payload[4] = 13; + payload[5] = 10; + payload[6] = 26; + payload[7] = 10; + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(payload); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, "cover", fileName); + return form; + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a music library owned by , together with an artist that has no cover yet. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId); + } + + /// + /// Seeds a music library owned by , together with an artist that already has a cover. + /// + /// The Id of the user that owns the library. + /// The relative path of the existing cover of the artist. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistWithCoverAsync(Guid userId, string existingCoverFileName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: existingCoverFileName, status: ArtworkStatus.Enriched)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// 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; + } + + /// + /// Asserts that the response is a not found problem details carrying the expected detail and request instance path. + /// + /// The HTTP response to assert on. + /// The expected problem detail. + /// The expected request instance path. + private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance) + { + await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5"); + } + + /// + /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type. + /// + /// The HTTP response to assert on. + /// The expected HTTP status code. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + /// The expected problem type URI. + private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType) + { + Assert.Equal(statusCode, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedType, problemDetails["type"].GetString()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"])); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs new file mode 100644 index 00000000..9f30b955 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs @@ -0,0 +1,320 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCoverEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateAlbumCoverEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateAlbumCover_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task UpdateAlbumCover_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateAlbumCover_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateAlbumCover_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/cover", form); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateAlbumCover_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/cover", form); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty"); + } + + [Fact] + public async Task UpdateAlbumCover_WhenAlbumDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("AlbumNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateAlbumCover_WithMaliciousFileName_ShouldNotCorruptOrLeakData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form); + + // Assert + // The album does not exist, so the handler returns a clean not found response before the uploaded file name is used. + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task UpdateAlbumCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId); + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + _seededUsernames.Add(requesterUsername); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task UpdateAlbumCover_WhenResourceBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + (Guid ownLibraryId, _, _) = await SeedLibraryArtistAndAlbumAsync(actingUserId); + + // The resource lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndAlbumAsync(victimUserId); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("AlbumNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's album is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId); + Assert.NotNull(storedAlbum); + Assert.Equal("News of the World", storedAlbum.Title); + } + + /// + /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload. + /// + /// The HTTP response to assert. + /// The injected payload that must never be echoed back. + /// The validation error code expected in the response. + private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal); + } + + /// + /// Creates a multipart form carrying a minimal cover payload with the specified file name. + /// + /// The name of the uploaded file. + /// A configured instance. + private static MultipartFormDataContent CreateCoverForm(string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload")); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, "cover", fileName); + return form; + } + + /// + /// Seeds a music library owned by , together with an artist and one of its albums. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs new file mode 100644 index 00000000..dab067a8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs @@ -0,0 +1,298 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCoverEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateArtistCoverEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateArtistCover_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task UpdateArtistCover_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateArtistCover_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/cover", form); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateArtistCover_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/cover", form); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty"); + } + + [Fact] + public async Task UpdateArtistCover_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateArtistCover_WithMaliciousFileName_ShouldNotCorruptOrLeakData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form); + + // Assert + // The artist does not exist, so the handler returns a clean not found response before the uploaded file name is used. + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task UpdateArtistCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(ownerId); + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + _seededUsernames.Add(requesterUsername); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task UpdateArtistCover_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + (Guid ownLibraryId, _) = await SeedLibraryAndArtistAsync(actingUserId); + + // The artist lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId) = await SeedLibraryAndArtistAsync(victimUserId); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's artist is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId); + Assert.NotNull(storedArtist); + Assert.Equal("Queen", storedArtist.Name); + } + + /// + /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload. + /// + /// The HTTP response to assert. + /// The injected payload that must never be echoed back. + /// The validation error code expected in the response. + private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal); + } + + /// + /// Creates a multipart form carrying a minimal cover payload with the specified file name. + /// + /// The name of the uploaded file. + /// A configured instance. + private static MultipartFormDataContent CreateCoverForm(string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload")); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, "cover", fileName); + return form; + } + + /// + /// Seeds a music library owned by , together with an artist. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs new file mode 100644 index 00000000..72575f3d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs @@ -0,0 +1,722 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +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.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCoverCommandHandlerTests +{ + private const string STORED_COVER_PATH = "/media/music/library/artist/Album/album/cover.jpg"; + + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IMusicArtworkService _mockMusicArtworkService; + private readonly IPathService _mockPathService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly UpdateAlbumCoverCommandHandler _sut; + private readonly Guid _userId; + private readonly UpdateAlbumCoverCommandFixture _updateAlbumCoverCommandFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateAlbumCoverCommandHandlerTests() + { + _mockAlbumRepository = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + _mockMusicArtworkService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, the album has no artwork yet, and the artwork storage succeeds. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + // The stored artwork paths used by the tests are Unix separated, and sanitizing a name keeps it unchanged, as the real service does for valid names. + _mockPathService.PathSeparator.Returns('/'); + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => PathSegment.Create(callInfo.Arg(), isDirectory: true, isDrive: false)); + _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockMusicArtworkService.SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(STORED_COVER_PATH)); + _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Result.From(Result.Deleted)); + + _sut = new UpdateAlbumCoverCommandHandler(_mockUnitOfWork, _mockMusicArtworkService, _mockPathService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutStoringArtwork() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.CoverCannotBeNull]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.CoverCannotBeNull, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + // The stored album belongs to a different library than the one named by the route. + AlbumEntity existingAlbum = _albumEntityFixture.Create(id: Guid.Parse(command.AlbumId!), artistId: Guid.Parse(command.ArtistId!), libraryId: Guid.NewGuid()); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(existingAlbum)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + // The stored album belongs to a different artist than the one named by the route. + AlbumEntity existingAlbum = _albumEntityFixture.Create(id: Guid.Parse(command.AlbumId!), artistId: Guid.NewGuid(), libraryId: Guid.Parse(command.LibraryId!)); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(existingAlbum)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutStoringArtwork() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + _mockArtistRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldPassEmptyArtistNameToArtworkService() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + _mockArtistRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), string.Empty, Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtworkLookupFails_ShouldReturnFailureResultWithoutStoringArtwork() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command); + _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtworkStorageFails_ShouldReturnFailureResultWithoutUpsertingOrSaving() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command); + _mockMusicArtworkService.SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Errors.FileSystemManagement.FileTooLarge); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingCoverPathHasParseableReleaseType_ShouldPassThatReleaseTypeToArtworkService() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + // The album's release type is Album, but its stored cover already lives under an Ep directory, which wins. + SetupExistingAlbum(command, releaseType: MusicReleaseType.Album); + SetupExistingLibrary(command); + SetupExistingArtist(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/Ep/album/cover.jpg")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), "Ep", Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheSegmentBeforeTheAlbumDirectoryIsTheArtistDirectoryNamedLikeAReleaseType_ShouldNotTreatItAsAReleaseType() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + // The artist is named "Live", which is also a release type name, but the album uses no release type, so the segment right before the album + // directory is the artist directory and must not be mistaken for a release type directory. + SetupExistingAlbum(command, includeReleaseType: false); + SetupExistingLibrary(command); + SetupExistingArtist(command, name: "Live"); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/Live/album/cover.jpg")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), "Live", Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Is(releaseTypeName => releaseTypeName == null), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheSegmentBeforeTheAlbumDirectoryIsAReleaseTypeOfAnArtistNamedLikeAReleaseType_ShouldKeepIt() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + // The artist is named "Album" and its cover is stored under an "Ep" release type directory, which differs from the artist directory, so it is kept. + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command, name: "Album"); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/Album/Ep/album/cover.jpg")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), "Album", Arg.Any(), + Arg.Any(), Arg.Any(), "Ep", Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingCoverPathHasNonParseableReleaseType_ShouldFallBackToFirstReleaseType() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command, releaseType: MusicReleaseType.Single); + SetupExistingLibrary(command); + SetupExistingArtist(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/NotAReleaseType/album/cover.jpg")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), "Single", Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingCoverPathHasTooFewSegments_ShouldFallBackToFirstReleaseType() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command, releaseType: MusicReleaseType.Single); + SetupExistingLibrary(command); + SetupExistingArtist(command); + // The stored cover path carries fewer than three segments, so it does not expose a release type directory. + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "cover.jpg")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), "Single", Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumHasNoExistingCover_ShouldUseFirstReleaseType() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command, releaseType: MusicReleaseType.Single); + SetupExistingLibrary(command); + SetupExistingArtist(command); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), "Single", Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumHasNoExistingCoverAndNoReleaseTypes_ShouldPassNullReleaseTypeToArtworkService() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command, includeReleaseType: false); + SetupExistingLibrary(command); + SetupExistingArtist(command); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Is(releaseTypeName => releaseTypeName == null), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingCoverPathDiffersFromStoredPath_ShouldDeletePreviousArtwork() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/Ep/album/old-cover.jpg")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork("/media/music/library/artist/Ep/album/old-cover.jpg"); + } + + [Fact] + public async Task HandleAsync_WhenExistingCoverPathEqualsStoredPath_ShouldNotDeletePreviousArtwork() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: STORED_COVER_PATH)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); + } + + [Theory] + [InlineData(null)] // no file name at all + [InlineData("")] // empty file name + [InlineData(" ")] // whitespace file name + public async Task HandleAsync_WhenExistingCoverPathIsEmpty_ShouldNotDeletePreviousArtwork(string? existingCoverPath) + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create( + ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: existingCoverPath, includeFileName: existingCoverPath is not null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletingPreviousArtworkFails_ShouldReturnFailureResultWithoutUpsertingOrSaving() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/Ep/album/old-cover.jpg")); + _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Errors.FileSystemManagement.FileTooLarge); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpsertCoverFails_ShouldReturnFailureResultWithoutSaving() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command); + _mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResult() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + SetupExistingAlbum(command); + SetupExistingLibrary(command); + SetupExistingArtist(command); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.Received(1).UpsertCoverAsync( + MusicArtworkOwnerType.Album, Guid.Parse(command.AlbumId!), STORED_COVER_PATH, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldReturnUpdateAlbumCoverResponseAndStoreArtwork() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + AlbumEntity existingAlbum = SetupExistingAlbum(command, releaseType: MusicReleaseType.Album); + LibraryEntity library = SetupExistingLibrary(command); + ArtistEntity artist = SetupExistingArtist(command); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + UpdateAlbumCoverResponse response = Assert.IsType(result.Value); + Assert.Equal(STORED_COVER_PATH, response.CoverPath); + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + existingAlbum.LibraryId, + existingAlbum.Id, + library.Title, + artist.Name, + existingAlbum.Title, + Arg.Any(), + command.FileName!, + "Album", + Arg.Any()); + await _mockMusicArtworkRepository.Received(1).UpsertCoverAsync( + MusicArtworkOwnerType.Album, + existingAlbum.Id, + STORED_COVER_PATH, + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Sets up a stored album that matches the library, artist and album identifiers of the command. + /// + /// The command whose route identifiers the stored album must match. + /// Optional. The release type of the stored album. + /// Whether the stored album should carry a release type, or an empty collection. + /// The created . + private AlbumEntity SetupExistingAlbum(UpdateAlbumCoverCommand command, MusicReleaseType? releaseType = MusicReleaseType.Album, bool includeReleaseType = true) + { + AlbumEntity existingAlbum = _albumEntityFixture.Create( + id: Guid.Parse(command.AlbumId!), + artistId: Guid.Parse(command.ArtistId!), + libraryId: Guid.Parse(command.LibraryId!), + releaseType: releaseType, + includeReleaseType: includeReleaseType); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(existingAlbum)); + return existingAlbum; + } + + /// + /// Sets up a stored media library that matches the library of the command. + /// + /// The command whose library identifier the stored library must match. + /// The created . + private LibraryEntity SetupExistingLibrary(UpdateAlbumCoverCommand command) + { + LibraryEntity library = _libraryEntityFixture.Create(id: Guid.Parse(command.LibraryId!)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + return library; + } + + /// + /// Sets up a stored artist that matches the artist of the command. + /// + /// The command whose artist identifier the stored artist must match. + /// Optional. The name of the stored artist. + /// The created . + private ArtistEntity SetupExistingArtist(UpdateAlbumCoverCommand command, string? name = null) + { + ArtistEntity artist = _artistEntityFixture.Create(id: Guid.Parse(command.ArtistId!), libraryId: Guid.Parse(command.LibraryId!), name: name); + _mockArtistRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + return artist; + } + + /// + /// Sets up the artwork owned by the album. + /// + /// The pieces of artwork owned by the album. + private void SetupExistingArtwork(params MusicArtworkEntity[] artworks) + { + _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>(artworks)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidatorTests.cs new file mode 100644 index 00000000..dc034fc4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidatorTests.cs @@ -0,0 +1,282 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCoverCommandValidatorTests +{ + private readonly UpdateAlbumCoverCommandFixture _updateAlbumCoverCommandFixture = new(); + private readonly UpdateAlbumCoverCommandValidator _validator = new(); + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(libraryId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(libraryId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(artistId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(artistId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(artistId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeAlbumId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(albumId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(albumId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(albumId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCoverIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeCover: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.CoverCannotBeNull); + } + + [Fact] + public void Validate_WhenCoverIsPresentAndFileNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(fileName: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCoverIsPresentAndFileNameIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(includeFileName: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCoverIsMissingAndFileNameIsEmpty_ShouldNotHaveFileNameValidationError() + { + // Arrange + UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create(fileName: string.Empty, includeCover: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandlerTests.cs new file mode 100644 index 00000000..4de61fa1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandlerTests.cs @@ -0,0 +1,473 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +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.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCoverCommandHandlerTests +{ + private const string STORED_COVER_PATH = "/media/music/library/artist/cover.jpg"; + + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IMusicArtworkService _mockMusicArtworkService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly UpdateArtistCoverCommandHandler _sut; + private readonly Guid _userId; + private readonly UpdateArtistCoverCommandFixture _updateArtistCoverCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistCoverCommandHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + _mockMusicArtworkService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, the artist has no artwork yet, and the artwork storage succeeds. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockMusicArtworkService.SaveArtistArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(STORED_COVER_PATH)); + _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Result.From(Result.Deleted)); + + _sut = new UpdateArtistCoverCommandHandler(_mockUnitOfWork, _mockMusicArtworkService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutStoringArtwork() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.CoverCannotBeNull]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.CoverCannotBeNull, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + // The stored artist belongs to a different library than the one named by the route. + ArtistEntity existingArtist = _artistEntityFixture.Create(id: Guid.Parse(command.ArtistId!), libraryId: Guid.NewGuid()); + _mockArtistRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(existingArtist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutStoringArtwork() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtworkLookupFails_ShouldReturnFailureResultWithoutStoringArtwork() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + SetupExistingLibrary(command); + _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtworkStorageFails_ShouldReturnFailureResultWithoutUpsertingOrSaving() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + SetupExistingLibrary(command); + _mockMusicArtworkService.SaveArtistArtworkAsync( + Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Errors.FileSystemManagement.FileTooLarge); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingCoverPathDiffersFromStoredPath_ShouldDeletePreviousArtwork() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + SetupExistingLibrary(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/old-cover.jpg")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork("/media/music/library/artist/old-cover.jpg"); + } + + [Fact] + public async Task HandleAsync_WhenExistingCoverPathEqualsStoredPath_ShouldNotDeletePreviousArtwork() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + SetupExistingLibrary(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, artworkType: ArtworkType.Cover, fileName: STORED_COVER_PATH)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); + } + + [Theory] + [InlineData(null)] // no file name at all + [InlineData("")] // empty file name + [InlineData(" ")] // whitespace file name + public async Task HandleAsync_WhenExistingCoverPathIsEmpty_ShouldNotDeletePreviousArtwork(string? existingCoverPath) + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + SetupExistingLibrary(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create( + ownerType: MusicArtworkOwnerType.Artist, artworkType: ArtworkType.Cover, fileName: existingCoverPath, includeFileName: existingCoverPath is not null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletingPreviousArtworkFails_ShouldReturnFailureResultWithoutUpsertingOrSaving() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + SetupExistingLibrary(command); + SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, artworkType: ArtworkType.Cover, fileName: "/media/music/library/artist/old-cover.jpg")); + _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Errors.FileSystemManagement.FileTooLarge); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpsertCoverFails_ShouldReturnFailureResultWithoutSaving() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + SetupExistingLibrary(command); + _mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResult() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + SetupExistingArtist(command); + SetupExistingLibrary(command); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.Received(1).UpsertCoverAsync( + MusicArtworkOwnerType.Artist, Guid.Parse(command.ArtistId!), STORED_COVER_PATH, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldReturnUpdateArtistCoverResponseAndStoreArtwork() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + ArtistEntity existingArtist = SetupExistingArtist(command); + LibraryEntity library = SetupExistingLibrary(command); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + UpdateArtistCoverResponse response = Assert.IsType(result.Value); + Assert.Equal(STORED_COVER_PATH, response.CoverPath); + await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync( + existingArtist.LibraryId, + library.Title, + existingArtist.Name, + Arg.Any(), + command.FileName!, + Arg.Any()); + await _mockMusicArtworkRepository.Received(1).UpsertCoverAsync( + MusicArtworkOwnerType.Artist, + existingArtist.Id, + STORED_COVER_PATH, + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Sets up a stored artist that matches the library and artist identifiers of the command. + /// + /// The command whose route identifiers the stored artist must match. + /// The created . + private ArtistEntity SetupExistingArtist(UpdateArtistCoverCommand command) + { + ArtistEntity existingArtist = _artistEntityFixture.Create( + id: Guid.Parse(command.ArtistId!), + libraryId: Guid.Parse(command.LibraryId!)); + _mockArtistRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(existingArtist)); + return existingArtist; + } + + /// + /// Sets up a stored media library that matches the library of the command. + /// + /// The command whose library identifier the stored library must match. + /// The created . + private LibraryEntity SetupExistingLibrary(UpdateArtistCoverCommand command) + { + LibraryEntity library = _libraryEntityFixture.Create(id: Guid.Parse(command.LibraryId!)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + return library; + } + + /// + /// Sets up the artwork owned by the artist. + /// + /// The pieces of artwork owned by the artist. + private void SetupExistingArtwork(params MusicArtworkEntity[] artworks) + { + _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>(artworks)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidatorTests.cs new file mode 100644 index 00000000..f01475fe --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidatorTests.cs @@ -0,0 +1,217 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCoverCommandValidatorTests +{ + private readonly UpdateArtistCoverCommandFixture _updateArtistCoverCommandFixture = new(); + private readonly UpdateArtistCoverCommandValidator _validator = new(); + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(libraryId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(libraryId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(includeArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(artistId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(artistId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(artistId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCoverIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(includeCover: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.CoverCannotBeNull); + } + + [Fact] + public void Validate_WhenCoverIsPresentAndFileNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(fileName: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCoverIsPresentAndFileNameIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(includeFileName: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCoverIsMissingAndFileNameIsEmpty_ShouldNotHaveFileNameValidationError() + { + // Arrange + UpdateArtistCoverCommand command = _updateArtistCoverCommandFixture.Create(fileName: string.Empty, includeCover: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs new file mode 100644 index 00000000..14c22b42 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs @@ -0,0 +1,340 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCoverEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdateAlbumCoverEndpoint _sut; + private readonly UpdateAlbumCoverResponseFixture _updateAlbumCoverResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateAlbumCoverEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + string expectedPath = "/media/music/cover.jpg"; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: expectedPath))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedPath, okResult?.Value?.CoverPath); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRouteIdsAndFile_ShouldSendUpdateAlbumCoverCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.AlbumId == albumId.ToString() && + command.Cover != null && + command.FileName == "cover.jpg"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid" && + command.AlbumId == "not-an-album-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg"))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null && + command.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + IFormCollection form = new FormCollection([]); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType>(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.AlbumId == albumId.ToString() && + command.Cover == null && + command.FileName == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldSendCommandWithNullCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.ContentType = "application/json"; + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType>(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Cover == null && command.FileName == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFormIsMalformed_ShouldSendCommandWithNullCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + ConfigureMalformedForm(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType>(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Cover == null && command.FileName == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.CoverCannotBeNull; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "CoverCannotBeNull" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.AlbumNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("AlbumNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_updateAlbumCoverResponseFixture.Create(coverPath: "/media/music/cover.jpg")); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + private void ConfigureForm(byte[] content, string fileName) + { + MemoryStream coverStream = new(content); + IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName); + FormFileCollection files = [formFile]; + IFormCollection form = new FormCollection([], files); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + } + + /// + /// Configures a multipart form request whose body cannot be parsed. + /// + private void ConfigureMalformedForm() + { + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + IFormCollection malformedForm = Substitute.For(); + malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body.")); + _sut.HttpContext.Features.Set(new FormFeature(malformedForm)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs new file mode 100644 index 00000000..0d5bc840 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs @@ -0,0 +1,319 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCoverEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdateArtistCoverEndpoint _sut; + private readonly UpdateArtistCoverResponseFixture _updateArtistCoverResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistCoverEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + string expectedPath = "/media/music/artist-cover.jpg"; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: expectedPath))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedPath, okResult?.Value?.CoverPath); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRouteIdsAndFile_ShouldSendUpdateArtistCoverCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.Cover != null && + command.FileName == "cover.jpg"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg"))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + IFormCollection form = new FormCollection([]); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType>(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.ArtistId == artistId.ToString() && + command.Cover == null && + command.FileName == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldSendCommandWithNullCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.ContentType = "application/json"; + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType>(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Cover == null && command.FileName == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFormIsMalformed_ShouldSendCommandWithNullCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + ConfigureMalformedForm(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType>(result); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Cover == null && command.FileName == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.CoverCannotBeNull; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "CoverCannotBeNull" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_updateArtistCoverResponseFixture.Create(coverPath: "/media/music/artist-cover.jpg")); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + private void ConfigureForm(byte[] content, string fileName) + { + MemoryStream coverStream = new(content); + IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName); + FormFileCollection files = [formFile]; + IFormCollection form = new FormCollection([], files); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + } + + /// + /// Configures a multipart form request whose body cannot be parsed. + /// + private void ConfigureMalformedForm() + { + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + IFormCollection malformedForm = Substitute.For(); + malformedForm.Files.Returns(_ => throw new InvalidDataException("Malformed multipart body.")); + _sut.HttpContext.Features.Set(new FormFeature(malformedForm)); + } +}