From 4f43bf352bb4772228e7a89f726735ba36a4ccab Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 13 Oct 2026 13:26:26 +0300 Subject: [PATCH] Cleans up the artwork and the stored media of deleted music library items and libraries. --- .../BookLibrary/IBookRepository.cs | 8 + .../MusicLibrary/IArtistRepository.cs | 8 + .../MusicLibrary/IMusicArtworkRepository.cs | 19 + ...IMusicLibraryScanItemMetadataRepository.cs | 8 + .../ApplicationLayerServices.cs | 2 + .../DeleteAlbum/DeleteAlbumCommandHandler.cs | 12 +- .../DeleteArtistCommandHandler.cs | 12 +- .../Artwork/IMusicArtworkCleanupService.cs | 38 ++ .../Artwork/MusicArtworkCleanupService.cs | 119 +++++++ .../DeleteTrack/DeleteTrackCommandHandler.cs | 12 +- .../LibraryDeletedDomainEventHandler.cs | 99 ++++-- .../BookLibrary/BookRepository.cs | 15 + .../MusicLibrary/MusicArtworkRepository.cs | 93 ++++- .../MusicLibraryScanItemMetadataRepository.cs | 14 + .../BookLibrary/BookRepositoryTests.cs | 32 ++ .../DeleteAlbum/DeleteAlbumEndpointTests.cs | 93 +++++ .../DeleteArtist/DeleteArtistEndpointTests.cs | 87 +++++ .../DeleteTrack/DeleteTrackEndpointTests.cs | 68 +++- .../DeleteAlbumCommandHandlerTests.cs | 41 ++- .../DeleteArtistCommandHandlerTests.cs | 41 ++- .../MusicArtworkCleanupServiceTests.cs | 324 ++++++++++++++++++ .../DeleteTrackCommandHandlerTests.cs | 39 ++- .../LibraryDeletedDomainEventHandlerTests.cs | 280 ++++++++++++++- 23 files changed, 1390 insertions(+), 74 deletions(-) create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkCleanupService.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupService.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupServiceTests.cs diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs index 56ebf0c6..d9516d0b 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs @@ -123,4 +123,12 @@ public interface IBookRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An containing either the display names of the authors of the books, keyed by book Id, or an error. Task>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection bookIds, CancellationToken cancellationToken); + + /// + /// Deletes all the books of the media library identified by , together with their artwork and their related data. + /// + /// The Id of the media library whose books are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs index 1cc604ac..b1aed090 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs @@ -78,4 +78,12 @@ public interface IArtistRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Deletes all the artists of the media library identified by , together with their albums and tracks and their related data. + /// + /// The Id of the media library whose artists are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs index 2d1686e8..dd5898c4 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs @@ -46,4 +46,23 @@ public interface IMusicArtworkRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Deletes all the pieces of artwork owned by the artists, albums and tracks of the media library identified by . + /// + /// The Id of the media library whose artwork is deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Stores the cover image of the music library item of the provided identified by , + /// replacing the file of its existing cover, or adding a new cover artwork when it has none. + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// The relative file name of the stored cover image. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> UpsertCoverAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicLibraryScanItemMetadataRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicLibraryScanItemMetadataRepository.cs index 488c0d9c..073d8c6e 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicLibraryScanItemMetadataRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicLibraryScanItemMetadataRepository.cs @@ -32,4 +32,12 @@ public interface IMusicLibraryScanItemMetadataRepository : IRepositoryCancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> DeleteByScanIdAsync(Guid scanId, CancellationToken cancellationToken); + + /// + /// Deletes all the staged music metadata items of the media library identified by . + /// + /// The Id of the media library whose staged music metadata is deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 6ca6bec2..f85aabf0 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Telemetry; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.Management.Deletion; using Lumina.Domain.Common.Events; using Microsoft.Extensions.DependencyInjection; @@ -44,6 +45,7 @@ public static class ApplicationLayerServices services.AddScoped(); services.AddScoped(); + services.AddScoped(); foreach (var registration in handlerRegistrations) { diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs index 3c63ada0..173bbe3b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; @@ -28,6 +29,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums. public class DeleteAlbumCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IMusicArtworkCleanupService _musicArtworkCleanupService; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; @@ -36,12 +38,14 @@ public class DeleteAlbumCommandHandler : ICommandHandler class. /// /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for removing the artwork of a music library item and of its children. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; + _musicArtworkCleanupService = musicArtworkCleanupService; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; @@ -115,6 +119,12 @@ public class DeleteAlbumCommandHandler : ICommandHandler deleteArtworkResult = await _musicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, cancellationToken).ConfigureAwait(false); + if (deleteArtworkResult.IsFailure) + return deleteArtworkResult.Errors; + Result updateResult = await _unitOfWork.ArtistRepository .UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs index 5a6d2fbb..ed03a91b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs @@ -7,6 +7,7 @@ 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.Domain.Common.Primitives; using System; using System.Collections.Generic; @@ -24,6 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists public class DeleteArtistCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IMusicArtworkCleanupService _musicArtworkCleanupService; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; @@ -32,12 +34,14 @@ public class DeleteArtistCommandHandler : ICommandHandler class. /// /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for removing the artwork of a music library item and of its children. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; + _musicArtworkCleanupService = musicArtworkCleanupService; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; @@ -92,6 +96,12 @@ public class DeleteArtistCommandHandler : ICommandHandler deleteArtworkResult = await _musicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, cancellationToken).ConfigureAwait(false); + if (deleteArtworkResult.IsFailure) + return deleteArtworkResult.Errors; + Result deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false); if (deleteArtistResult.IsFailure) return deleteArtistResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkCleanupService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkCleanupService.cs new file mode 100644 index 00000000..7da9ca4f --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkCleanupService.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Interface for the service that removes the artwork records and the stored artwork files of a music library item, together with the artwork of its children. +/// +public interface IMusicArtworkCleanupService +{ + /// + /// Removes the artwork records and the stored artwork files of the artist identified by , together with the artwork of its albums and tracks. + /// + /// The Id of the artist whose artwork is removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteArtistArtworkAsync(Guid artistId, CancellationToken cancellationToken); + + /// + /// Removes the artwork records and the stored artwork files of the album identified by , together with the artwork of its tracks. + /// + /// The Id of the album whose artwork is removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteAlbumArtworkAsync(Guid albumId, CancellationToken cancellationToken); + + /// + /// Removes the artwork records and the stored artwork files of the track identified by . + /// + /// The Id of the track whose artwork is removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteTrackArtworkAsync(Guid trackId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupService.cs new file mode 100644 index 00000000..42864d01 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupService.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Service that removes the artwork records and the stored artwork files of a music library item, together with the artwork of its children. +/// The artwork table is shared by all the music library item types and references its owners by a plain id, so the artwork of an item does not +/// cascade when the item is removed, and is removed explicitly instead, from the innermost children outwards. +/// +internal sealed class MusicArtworkCleanupService : IMusicArtworkCleanupService +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IMusicArtworkService _musicArtworkService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for removing the stored artwork files of a music library item. + public MusicArtworkCleanupService(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService) + { + _unitOfWork = unitOfWork; + _musicArtworkService = musicArtworkService; + } + + /// + /// Removes the artwork records and the stored artwork files of the artist identified by , together with the artwork of its albums and tracks. + /// + /// The Id of the artist whose artwork is removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteArtistArtworkAsync(Guid artistId, CancellationToken cancellationToken) + { + // The albums and the tracks of the artist are removed by the database through the cascading foreign keys, so only the artwork of the + // children has to be collected here, and it has to be removed before the artwork of the artist itself, from the innermost children outwards. + Result> getAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false); + if (getAlbumsResult.IsFailure) + return getAlbumsResult.Errors; + + foreach (AlbumEntity album in getAlbumsResult.Value) + { + Result deleteAlbumArtworkResult = await DeleteAlbumArtworkAsync(album.Id, cancellationToken).ConfigureAwait(false); + if (deleteAlbumArtworkResult.IsFailure) + return deleteAlbumArtworkResult.Errors; + } + + return await DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Removes the artwork records and the stored artwork files of the album identified by , together with the artwork of its tracks. + /// + /// The Id of the album whose artwork is removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteAlbumArtworkAsync(Guid albumId, CancellationToken cancellationToken) + { + // The tracks of the album are removed by the database through the cascading foreign keys, so only their artwork has to be removed here, + // before the artwork of the album itself. + Result> getTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false); + if (getTracksResult.IsFailure) + return getTracksResult.Errors; + + foreach (TrackEntity track in getTracksResult.Value) + { + Result deleteTrackArtworkResult = await DeleteTrackArtworkAsync(track.Id, cancellationToken).ConfigureAwait(false); + if (deleteTrackArtworkResult.IsFailure) + return deleteTrackArtworkResult.Errors; + } + + return await DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Removes the artwork records and the stored artwork files of the track identified by . + /// + /// The Id of the track whose artwork is removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public Task> DeleteTrackArtworkAsync(Guid trackId, CancellationToken cancellationToken) + { + return DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken); + } + + /// + /// Removes the artwork records and the stored artwork files of the single music library item identified by and . + /// + /// The type of the music library item whose artwork is removed. + /// The Id of the music library item whose artwork is removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> DeleteOwnerArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken) + { + Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); + if (getArtworkResult.IsFailure) + return getArtworkResult.Errors; + + // The stored files do not cascade from their records either, so every stored file is removed before its record is; the artwork whose file has not been resolved yet has no file to remove. + foreach (MusicArtworkEntity artwork in getArtworkResult.Value) + { + if (string.IsNullOrWhiteSpace(artwork.FileName)) + continue; + Result deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName); + if (deleteStoredArtworkResult.IsFailure) + return deleteStoredArtworkResult.Errors; + } + + return await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs index 8237a549..5f7dfd3f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; @@ -28,6 +29,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks. public class DeleteTrackCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IMusicArtworkCleanupService _musicArtworkCleanupService; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; @@ -36,12 +38,14 @@ public class DeleteTrackCommandHandler : ICommandHandler class. /// /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for removing the artwork of a music library item and of its children. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; + _musicArtworkCleanupService = musicArtworkCleanupService; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; @@ -122,6 +126,12 @@ public class DeleteTrackCommandHandler : ICommandHandler deleteArtworkResult = await _musicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, cancellationToken).ConfigureAwait(false); + if (deleteArtworkResult.IsFailure) + return deleteArtworkResult.Errors; + Result updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs index 17beb518..571372f6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandler.cs @@ -1,7 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; @@ -20,6 +21,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// public class LibraryDeletedDomainEventHandler : IDomainEventHandler { + private readonly IUnitOfWork _unitOfWork; private readonly IEnvironmentContext _environmentContext; private readonly IPathService _pathService; private readonly MediaSettingsDto _mediaSettingsModel; @@ -27,11 +29,13 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler /// Initializes a new instance of the class. /// + /// Injected unit of work for interacting with the data access layer repositories. /// Injected facade service for environment contextual services. /// Injected service for handling file system paths. /// Injected service for retrieving . - public LibraryDeletedDomainEventHandler(IEnvironmentContext environmentContext, IPathService pathService, IOptions mediaSettingsModelOptions) + public LibraryDeletedDomainEventHandler(IUnitOfWork unitOfWork, IEnvironmentContext environmentContext, IPathService pathService, IOptions mediaSettingsModelOptions) { + _unitOfWork = unitOfWork; _environmentContext = environmentContext; _pathService = pathService; _mediaSettingsModel = mediaSettingsModelOptions.Value; @@ -42,47 +46,80 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler /// The domain event to be handled. /// Cancellation token that can be used to stop the execution. - public ValueTask HandleAsync(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken) + public async ValueTask HandleAsync(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken) { - // delete the media library directory in the internal location for media library files - Result libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); - if (libraryPathResult.IsFailure) - throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors); + Guid libraryId = domainEvent.Library.Id.Value; - Result newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value); - if (newLibraryPathIdResult.IsFailure) - throw new EventualConsistencyException(newLibraryPathIdResult.FirstError, newLibraryPathIdResult.Errors); + // The media items of the library and their artwork do not cascade from the library row, because they reference it by a plain id, + // so they are removed first, otherwise they would be orphaned in the database. The artwork is removed before its owners, so that + // its owners are still present when the artwork is looked up. + Result deleteMusicArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (deleteMusicArtworkResult.IsFailure) + throw new EventualConsistencyException(deleteMusicArtworkResult.FirstError, deleteMusicArtworkResult.Errors); - Result deleteLibraryDirectoryResult = _environmentContext.DirectoryProviderService.DeleteDirectory(newLibraryPathIdResult.Value); - if (deleteLibraryDirectoryResult.IsFailure) - throw new EventualConsistencyException(deleteLibraryDirectoryResult.FirstError, deleteLibraryDirectoryResult.Errors); - - return ValueTask.CompletedTask; + // Deleting the artists removes their albums, tracks and their related data, through the cascading foreign keys. + Result deleteArtistsResult = await _unitOfWork.ArtistRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (deleteArtistsResult.IsFailure) + throw new EventualConsistencyException(deleteArtistsResult.FirstError, deleteArtistsResult.Errors); + + // Deleting the books removes their artwork and their related data, through the cascading foreign keys. + Result deleteBooksResult = await _unitOfWork.BookRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (deleteBooksResult.IsFailure) + throw new EventualConsistencyException(deleteBooksResult.FirstError, deleteBooksResult.Errors); + + // The staged music metadata of the library does not cascade from the library row either, so it is removed as well. + Result deleteStagedMusicMetadataResult = await _unitOfWork.MusicLibraryScanItemMetadataRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (deleteStagedMusicMetadataResult.IsFailure) + throw new EventualConsistencyException(deleteStagedMusicMetadataResult.FirstError, deleteStagedMusicMetadataResult.Errors); + + // The cover image of the library is stored under the libraries directory, under a directory named after the library id, + // while the artwork of the media items of the library is stored under the per-media-type directories, under directories + // named after the library, so all of them must be removed when the library is deleted. All the media item files of a library + // live inside these directories, so removing them removes the library's stored media without touching the user's own files. + DeleteLibraryDirectory(_mediaSettingsModel.LibrariesDirectory, libraryId.ToString()); + + Result librarySegmentResult = _pathService.SanitizeSegment($"{domainEvent.Library.Title}-{libraryId}"); + if (librarySegmentResult.IsFailure) + throw new EventualConsistencyException(librarySegmentResult.FirstError, librarySegmentResult.Errors); + DeleteLibraryDirectory(_mediaSettingsModel.BooksDirectory, librarySegmentResult.Value.Name); + DeleteLibraryDirectory(_mediaSettingsModel.MusicDirectory, librarySegmentResult.Value.Name); } /// - /// Gets the file system path of a media library identified by . + /// Deletes the directory of a media library from the internal media location of the provided media type. /// - /// The id of the media library for which to regtrieve the file system path. - /// - /// An containing either the file system path of the media library, or an error message. - /// - private Result GetLibraryPath(Guid libraryId) + /// The name of the media type subdirectory the library directory is stored under. + /// The name of the directory of the media library. + private void DeleteLibraryDirectory(string mediaTypeDirectory, string libraryDirectoryName) { - // root directory for media + // Root directory for media. Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); if (rootPathResult.IsFailure) - return rootPathResult.Errors; + throw new EventualConsistencyException(rootPathResult.FirstError, rootPathResult.Errors); - // libraries directory - Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); - if (librariesPathResult.IsFailure) - return librariesPathResult.Errors; + // Media type directory. + Result mediaTypePathResult = _pathService.CombinePath(rootPathResult.Value, mediaTypeDirectory); + if (mediaTypePathResult.IsFailure) + throw new EventualConsistencyException(mediaTypePathResult.FirstError, mediaTypePathResult.Errors); - // this new particular library' directory - Result libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); + // This particular library's directory. + Result libraryPathResult = _pathService.CombinePath(mediaTypePathResult.Value, libraryDirectoryName); if (libraryPathResult.IsFailure) - return libraryPathResult.Errors; - return libraryPathResult.Value; + throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors); + + Result libraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value); + if (libraryPathIdResult.IsFailure) + throw new EventualConsistencyException(libraryPathIdResult.FirstError, libraryPathIdResult.Errors); + + // The directory only exists when the library actually stored something under this media type, so a missing directory is not an error. + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + throw new EventualConsistencyException(directoryExistsResult.FirstError, directoryExistsResult.Errors); + if (!directoryExistsResult.Value) + return; + + Result deleteLibraryDirectoryResult = _environmentContext.DirectoryProviderService.DeleteDirectory(libraryPathIdResult.Value); + if (deleteLibraryDirectoryResult.IsFailure) + throw new EventualConsistencyException(deleteLibraryDirectoryResult.FirstError, deleteLibraryDirectoryResult.Errors); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index b1490003..9269db51 100644 --- a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -462,6 +462,21 @@ internal sealed class BookRepository : IBookRepository return Result.Updated; } + /// + /// Deletes all the books of the media library identified by , together with their artwork and their related data. + /// + /// The Id of the media library whose books are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + // The artwork and the related data of the books are removed by the database, through the cascading foreign keys. + await _luminaDbContext.Books + .Where(book => book.LibraryId == libraryId) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + return Result.Deleted; + } + /// /// Gets the display names of the author of the books identified by the provided , /// keyed by the Id of the book, or when a book has no author. diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs index ceb8f38e..f9f56768 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs @@ -85,25 +85,84 @@ internal sealed class MusicArtworkRepository : IMusicArtworkRepository /// An representing either a successful operation, or an error. public async Task> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) { - // The artwork table is shared by all the music library item types, so the owners of the artwork of this library are collected per type. - List artistIds = await _luminaDbContext.Artists - .Where(artist => artist.LibraryId == libraryId) - .Select(artist => artist.Id) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List albumIds = await _luminaDbContext.Albums - .Where(album => album.LibraryId == libraryId) - .Select(album => album.Id) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List trackIds = await _luminaDbContext.Tracks - .Where(track => track.LibraryId == libraryId) - .Select(track => track.Id) - .ToListAsync(cancellationToken).ConfigureAwait(false); - + // The artwork table is shared by all the music library item types, so the owner of a piece of artwork is matched by its type against the + // corresponding table, and the database resolves the membership of the owner in the library by a correlated subquery. Collecting the ids + // of every artist, album and track of the library in memory first would make the cost of the operation grow with the size of the library. await _luminaDbContext.MusicArtwork - .Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist && artistIds.Contains(musicArtwork.OwnerId)) - || (musicArtwork.OwnerType == MusicArtworkOwnerType.Album && albumIds.Contains(musicArtwork.OwnerId)) - || (musicArtwork.OwnerType == MusicArtworkOwnerType.Track && trackIds.Contains(musicArtwork.OwnerId))) + .Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist + && _luminaDbContext.Artists.Any(artist => artist.Id == musicArtwork.OwnerId && artist.LibraryId == libraryId)) + || (musicArtwork.OwnerType == MusicArtworkOwnerType.Album + && _luminaDbContext.Albums.Any(album => album.Id == musicArtwork.OwnerId && album.LibraryId == libraryId)) + || (musicArtwork.OwnerType == MusicArtworkOwnerType.Track + && _luminaDbContext.Tracks.Any(track => track.Id == musicArtwork.OwnerId && track.LibraryId == libraryId))) .ExecuteUpdateAsync(setters => setters.SetProperty(musicArtwork => musicArtwork.Status, ArtworkStatus.Pending), cancellationToken).ConfigureAwait(false); return Result.Updated; } + + /// + /// Deletes all the pieces of artwork owned by the artists, albums and tracks of the media library identified by . + /// + /// The Id of the media library whose artwork is deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + // The artwork table is shared by all the music library item types, so the owner of a piece of artwork is matched by its type against the + // corresponding table, and the database resolves the membership of the owner in the library by a correlated subquery. Collecting the ids + // of every artist, album and track of the library in memory first would make the cost of the operation grow with the size of the library. + await _luminaDbContext.MusicArtwork + .Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist + && _luminaDbContext.Artists.Any(artist => artist.Id == musicArtwork.OwnerId && artist.LibraryId == libraryId)) + || (musicArtwork.OwnerType == MusicArtworkOwnerType.Album + && _luminaDbContext.Albums.Any(album => album.Id == musicArtwork.OwnerId && album.LibraryId == libraryId)) + || (musicArtwork.OwnerType == MusicArtworkOwnerType.Track + && _luminaDbContext.Tracks.Any(track => track.Id == musicArtwork.OwnerId && track.LibraryId == libraryId))) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + return Result.Deleted; + } + + /// + /// Stores the cover image of the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// The relative file name of the stored cover image. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpsertCoverAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName, CancellationToken cancellationToken) + { + // The existing cover is matched the same way the callers that resolve it do, by owner and artwork type only, so that a cover stored + // with an ordinal other than zero is replaced in place instead of a second cover row being inserted next to it. + MusicArtworkEntity? existingCover = await _luminaDbContext.MusicArtwork + .FirstOrDefaultAsync(musicArtwork => musicArtwork.OwnerType == ownerType + && musicArtwork.OwnerId == ownerId + && musicArtwork.ArtworkType == ArtworkType.Cover, cancellationToken).ConfigureAwait(false); + + DateTime now = DateTime.UtcNow; + if (existingCover is null) + { + _luminaDbContext.MusicArtwork.Add(new MusicArtworkEntity + { + Id = Guid.NewGuid(), + OwnerType = ownerType, + OwnerId = ownerId, + ArtworkType = ArtworkType.Cover, + Ordinal = 0, + FileName = fileName, + Status = ArtworkStatus.Enriched, + CreatedOnUtc = now, + CreatedBy = Guid.Empty, + // The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null + }); + } + else + { + existingCover.FileName = fileName; + existingCover.Status = ArtworkStatus.Enriched; + existingCover.LastUpdateUtc = now; + } + return Result.Updated; + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepository.cs index f2810e93..9ca1d53d 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicLibraryScanItemMetadataRepository.cs @@ -71,4 +71,18 @@ internal sealed class MusicLibraryScanItemMetadataRepository : IMusicLibraryScan .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); return Result.Deleted; } + + /// + /// Deletes all the staged music metadata items of the media library identified by . + /// + /// The Id of the media library whose staged music metadata is deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + await _luminaDbContext.MusicLibraryScanItemMetadata + .Where(musicMetadata => musicMetadata.LibraryId == libraryId) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + return Result.Deleted; + } } diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs index 2c235bef..b83c9adb 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -442,6 +442,38 @@ public class BookRepositoryTests Assert.Equal(keptContributor.Id, Assert.Single(storedBook.Contributors).Id); } + [Fact] + public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyThatLibrariesBooks() + { + // Arrange + // The delete uses ExecuteDeleteAsync, which is not supported by the in-memory provider, so a real SQLite database is used. + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-deletebylibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity bookOfLibrary = _bookEntityFixture.Create(); + bookOfLibrary.LibraryId = libraryId; + bookOfLibrary.Path = "/books/library.epub"; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.Path = "/books/other.epub"; + context.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + context.ChangeTracker.Clear(); + BookEntity survivor = Assert.Single(await context.Books.AsNoTracking().ToListAsync()); + Assert.Equal(bookOfAnotherLibrary.Id, survivor.Id); + } + /// /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs index e8b9119e..2749e900 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs @@ -5,6 +5,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioL using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -37,6 +38,8 @@ public class DeleteAlbumEndpointTests : IClassFixture @@ -77,6 +80,28 @@ public class DeleteAlbumEndpointTests : IClassFixture album.Id == otherAlbumId)); } + [Fact] + public async Task DeleteAlbum_WhenAlbumHasStoredArtwork_ShouldRemoveTheArtworkOfTheAlbumAndOfItsTracks() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId); + await SeedArtworkAsync(MusicArtworkOwnerType.Album, albumId, "media/music/queen/album.jpg"); + await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/track.jpg"); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + // The artwork of the album and of its tracks does not cascade from the album row, so it is removed together with the album. + Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId)); + Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); + } + [Fact] public async Task DeleteAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem() { @@ -184,6 +209,74 @@ public class DeleteAlbumEndpointTests : IClassFixture /// The Id of the user that owns the library. /// The Id of the seeded library. + /// + /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(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(); + Guid trackId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + AlbumEntity album = _albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: "A Night at the Opera", + tracks: [track], + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + // An artist must keep at least one album, so a sibling album is seeded alongside the deleted one. + AlbumEntity otherAlbum = _albumEntityFixture.Create( + id: Guid.NewGuid(), + 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: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Seeds a piece of stored artwork owned by the music library item identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// The relative file name of the stored artwork. + /// A task representing the asynchronous operation. + private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName)); + await dbContext.SaveChangesAsync(); + } + private async Task SeedLibraryAsync(Guid userId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs index c9d6ba48..2d6c3dbd 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs @@ -1,9 +1,11 @@ #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.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.DeleteArtist; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -35,6 +37,9 @@ public class DeleteArtistEndpointTests : IClassFixture @@ -73,6 +78,33 @@ public class DeleteArtistEndpointTests : IClassFixture artist.Id == artistId)); } + [Fact] + public async Task DeleteArtist_WhenArtistHasStoredArtwork_ShouldRemoveTheArtworkOfTheArtistAndOfItsChildren() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId); + await SeedArtworkAsync(MusicArtworkOwnerType.Artist, artistId, "media/music/queen/artist.jpg"); + await SeedArtworkAsync(MusicArtworkOwnerType.Album, albumId, "media/music/queen/album.jpg"); + await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/track.jpg"); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + // The artist takes its albums and their tracks with it, and the artwork of all of them does not cascade, so it is removed together with the artist. + Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId)); + Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId)); + Assert.Null(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId)); + Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId)); + Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId)); + Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); + } + [Fact] public async Task DeleteArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem() { @@ -163,6 +195,61 @@ public class DeleteArtistEndpointTests : IClassFixture /// The Id of the user that owns the library. /// The Id of the seeded library. + /// + /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(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(); + Guid trackId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + AlbumEntity album = _albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: "A Night at the Opera", + tracks: [track], + 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, trackId); + } + + /// + /// Seeds a piece of stored artwork owned by the music library item identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// The relative file name of the stored artwork. + /// A task representing the asynchronous operation. + private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName)); + await dbContext.SaveChangesAsync(); + } + private async Task SeedLibraryAsync(Guid userId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs index 61f3eca3..6133c9c9 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs @@ -6,12 +6,14 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioL using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; @@ -40,6 +42,7 @@ public class DeleteTrackEndpointTests : IClassFixture @@ -81,6 +84,26 @@ public class DeleteTrackEndpointTests : IClassFixture artist.Id == artistId)); } + [Fact] + public async Task DeleteTrack_WhenTrackHasStoredArtwork_ShouldRemoveItsArtworkRecords() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Bohemian Rhapsody", "/music/queen/bohemian-rhapsody.flac"); + await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/bohemian-rhapsody.jpg"); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + // The artwork of the track does not cascade from the track row, so it is removed together with the track. + Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId)); + } + [Fact] public async Task DeleteTrack_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem() { @@ -229,10 +252,12 @@ public class DeleteTrackEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.Ordinal); } [Fact] @@ -258,8 +283,9 @@ public class DeleteTrackEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Validation", problemDetails!["title"].GetString()); Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); } @@ -272,8 +298,9 @@ public class DeleteTrackEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Validation", problemDetails!["title"].GetString()); Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); } @@ -286,8 +313,9 @@ public class DeleteTrackEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Validation", problemDetails!["title"].GetString()); Assert.Contains("AlbumIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); } @@ -300,11 +328,27 @@ public class DeleteTrackEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Validation", problemDetails!["title"].GetString()); Assert.Contains("TrackIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); } + /// + /// Seeds a piece of stored artwork owned by the music library item identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// The relative file name of the stored artwork. + /// A task representing the asynchronous operation. + private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName)); + await dbContext.SaveChangesAsync(); + } + /// /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. /// diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs index 927ca97b..30a809ea 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs @@ -9,6 +9,7 @@ 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.DeleteAlbum; +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.DeleteAlbum; @@ -35,6 +36,7 @@ public class DeleteAlbumCommandHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IArtistRepository _mockArtistRepository; private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; @@ -55,24 +57,27 @@ public class DeleteAlbumCommandHandlerTests _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockMusicArtworkCleanupService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist update succeeds and saving changes succeeds. + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist update succeeds, the artwork cleanup succeeds and saving changes succeeds. _mockValidator.Validate(Arg.Any()).Returns([]); _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(Result.Success); - _sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + _sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } [Fact] @@ -92,6 +97,13 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); + // The artwork of the album and of its tracks is removed before the album is removed from the artist aggregate, so that no artwork is orphaned. + await _mockMusicArtworkCleanupService.Received(1).DeleteAlbumArtworkAsync(albumId, Arg.Any()); + Received.InOrder(() => + { + _mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, Arg.Any()); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()); + }); await _mockArtistRepository.Received(1).UpdateAsync( Arg.Is(updatedArtist => updatedArtist.Id == artistId && @@ -117,6 +129,7 @@ public class DeleteAlbumCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.AlbumIdCannotBeEmpty, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkCleanupService.DidNotReceive().DeleteAlbumArtworkAsync(Arg.Any(), Arg.Any()); await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -323,6 +336,30 @@ public class DeleteAlbumCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + await _mockMusicArtworkCleanupService.DidNotReceive().DeleteAlbumArtworkAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutUpdatingTheArtist() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + Error error = Error.Failure(description: "Failed to delete the artwork"); + _mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs index 19f1198a..c387ff71 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs @@ -9,6 +9,7 @@ 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.DeleteArtist; +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.DeleteArtist; @@ -33,6 +34,7 @@ public class DeleteArtistCommandHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IArtistRepository _mockArtistRepository; private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; @@ -52,24 +54,27 @@ public class DeleteArtistCommandHandlerTests _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockMusicArtworkCleanupService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist deletion succeeds and saving changes succeeds. + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist deletion succeeds, the artwork cleanup succeeds and saving changes succeeds. _mockValidator.Validate(Arg.Any()).Returns([]); _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); _mockArtistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Deleted); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(Result.Success); - _sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + _sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } [Fact] @@ -89,6 +94,13 @@ public class DeleteArtistCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); + // The artwork of the artist and of its albums and tracks is removed before the artist row, so that no artwork is orphaned. + await _mockMusicArtworkCleanupService.Received(1).DeleteArtistArtworkAsync(artistId, Arg.Any()); + Received.InOrder(() => + { + _mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, Arg.Any()); + _mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any()); + }); await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( @@ -110,6 +122,7 @@ public class DeleteArtistCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Music.ArtistIdCannotBeEmpty, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkCleanupService.DidNotReceive().DeleteArtistArtworkAsync(Arg.Any(), Arg.Any()); await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -259,6 +272,30 @@ public class DeleteArtistCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutDeletingTheArtist() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + Error error = Error.Failure(description: "Failed to delete the artwork"); + _mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenDeleteArtistFails_ShouldReturnErrorWithoutSaving() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupServiceTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupServiceTests.cs new file mode 100644 index 00000000..a6beb96e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkCleanupServiceTests.cs @@ -0,0 +1,324 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkCleanupServiceTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IMusicArtworkService _mockMusicArtworkService; + private readonly MusicArtworkCleanupService _sut; + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkCleanupServiceTests() + { + _mockUnitOfWork = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockMusicArtworkService = Substitute.For(); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + + // Default stubs: every owner has no artwork, deleting the records succeeds, deleting a stored file succeeds. + _mockAlbumRepository.GetByArtistIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockTrackRepository.GetByAlbumIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Result.Deleted); + + _sut = new MusicArtworkCleanupService(_mockUnitOfWork, _mockMusicArtworkService); + } + + [Fact] + public async Task DeleteArtistArtworkAsync_WhenArtistHasAlbumsAndTracks_ShouldRemoveTheArtworkOfTheChildrenBeforeTheArtistArtwork() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid firstAlbumId = Guid.NewGuid(); + Guid secondAlbumId = Guid.NewGuid(); + Guid firstTrackId = Guid.NewGuid(); + Guid secondTrackId = Guid.NewGuid(); + Guid thirdTrackId = Guid.NewGuid(); + AlbumEntity firstAlbum = _albumEntityFixture.Create(id: firstAlbumId, includeTracks: false); + AlbumEntity secondAlbum = _albumEntityFixture.Create(id: secondAlbumId, includeTracks: false); + TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: firstAlbumId); + TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: firstAlbumId); + TrackEntity thirdTrack = _trackEntityFixture.Create(id: thirdTrackId, albumId: secondAlbumId); + MusicArtworkEntity firstTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: firstTrackId, fileName: "/media/music/first-track.jpg"); + MusicArtworkEntity secondTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: secondTrackId, fileName: "/media/music/second-track.jpg"); + MusicArtworkEntity thirdTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: thirdTrackId, fileName: "/media/music/third-track.jpg"); + MusicArtworkEntity firstAlbumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbumId, fileName: "/media/music/first-album.jpg"); + MusicArtworkEntity secondAlbumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: secondAlbumId, fileName: "/media/music/second-album.jpg"); + MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, fileName: "/media/music/artist.jpg"); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>([firstAlbum, secondAlbum])); + _mockTrackRepository.GetByAlbumIdAsync(firstAlbumId, Arg.Any()) + .Returns(Result.From>([firstTrack, secondTrack])); + _mockTrackRepository.GetByAlbumIdAsync(secondAlbumId, Arg.Any()) + .Returns(Result.From>([thirdTrack])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any()) + .Returns(Result.From>([firstTrackArtwork])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any()) + .Returns(Result.From>([secondTrackArtwork])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, thirdTrackId, Arg.Any()) + .Returns(Result.From>([thirdTrackArtwork])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, firstAlbumId, Arg.Any()) + .Returns(Result.From>([firstAlbumArtwork])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, secondAlbumId, Arg.Any()) + .Returns(Result.From>([secondAlbumArtwork])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) + .Returns(Result.From>([artistArtwork])); + + // Act + Result result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstTrackArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondTrackArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(thirdTrackArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstAlbumArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondAlbumArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(artistArtwork.FileName!); + // Every owner of the artwork is removed from the innermost children outwards, so that no artwork is orphaned. + Received.InOrder(() => + { + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any()); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any()); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, firstAlbumId, Arg.Any()); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, thirdTrackId, Arg.Any()); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, secondAlbumId, Arg.Any()); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()); + }); + } + + [Fact] + public async Task DeleteArtistArtworkAsync_WhenGetAlbumsFails_ShouldReturnTheErrorWithoutDeletingAnyArtwork() + { + // Arrange + Guid artistId = Guid.NewGuid(); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); + } + + [Fact] + public async Task DeleteArtistArtworkAsync_WhenAChildArtworkCleanupFails_ShouldReturnTheErrorWithoutDeletingTheArtistArtwork() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>([album])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task DeleteAlbumArtworkAsync_WhenAlbumHasTracks_ShouldRemoveTheArtworkOfTheTracksBeforeTheAlbumArtwork() + { + // Arrange + Guid albumId = Guid.NewGuid(); + Guid firstTrackId = Guid.NewGuid(); + Guid secondTrackId = Guid.NewGuid(); + TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: albumId); + TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: albumId); + MusicArtworkEntity firstTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: firstTrackId, fileName: "/media/music/first-track.jpg"); + MusicArtworkEntity secondTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: secondTrackId, fileName: "/media/music/second-track.jpg"); + MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, fileName: "/media/music/album.jpg"); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([firstTrack, secondTrack])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any()) + .Returns(Result.From>([firstTrackArtwork])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any()) + .Returns(Result.From>([secondTrackArtwork])); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.From>([albumArtwork])); + + // Act + Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstTrackArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondTrackArtwork.FileName!); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(albumArtwork.FileName!); + Received.InOrder(() => + { + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any()); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any()); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()); + }); + } + + [Fact] + public async Task DeleteAlbumArtworkAsync_WhenGetTracksFails_ShouldReturnTheErrorWithoutDeletingAnyArtwork() + { + // Arrange + Guid albumId = Guid.NewGuid(); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task DeleteAlbumArtworkAsync_WhenGetArtworkFails_ShouldReturnTheErrorWithoutDeletingTheRecords() + { + // Arrange + Guid albumId = Guid.NewGuid(); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task DeleteAlbumArtworkAsync_WhenDeletingTheArtworkRecordsFails_ShouldReturnTheError() + { + // Arrange + Guid albumId = Guid.NewGuid(); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task DeleteAlbumArtworkAsync_WhenDeletingAStoredArtworkFileFails_ShouldReturnTheErrorWithoutDeletingTheRecords() + { + // Arrange + Guid albumId = Guid.NewGuid(); + MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, fileName: "/media/music/album.jpg"); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.From>([albumArtwork])); + _mockMusicArtworkService.DeleteStoredArtwork(albumArtwork.FileName!) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task DeleteAlbumArtworkAsync_WhenArtworkHasNoStoredFile_ShouldSkipTheFileDeletionButDeleteTheRecords() + { + // Arrange + Guid albumId = Guid.NewGuid(); + // An artwork whose file has not been resolved yet has no file to remove, but its record still has to be removed. + MusicArtworkEntity unresolvedArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, includeFileName: false); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.From>([unresolvedArtwork])); + + // Act + Result result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()); + } + + [Fact] + public async Task DeleteTrackArtworkAsync_WhenArtworkExists_ShouldDeleteTheStoredFilesAndTheRecords() + { + // Arrange + Guid trackId = Guid.NewGuid(); + MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: trackId, fileName: "/media/music/track.jpg"); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any()) + .Returns(Result.From>([trackArtwork])); + + // Act + Result result = await _sut.DeleteTrackArtworkAsync(trackId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.Received(1).DeleteStoredArtwork(trackArtwork.FileName!); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any()); + } + + [Fact] + public async Task DeleteTrackArtworkAsync_WhenNoArtworkExists_ShouldStillDeleteTheRecords() + { + // Arrange + Guid trackId = Guid.NewGuid(); + + // Act + Result result = await _sut.DeleteTrackArtworkAsync(trackId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs index 4c37e1db..4a6bb5f3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs @@ -8,6 +8,7 @@ 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.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; @@ -33,6 +34,7 @@ public class DeleteTrackCommandHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IArtistRepository _mockArtistRepository; private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; @@ -54,22 +56,25 @@ public class DeleteTrackCommandHandlerTests _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockMusicArtworkCleanupService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist update succeeds and saving changes succeeds. + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist update succeeds, the artwork cleanup succeeds and saving changes succeeds. _mockValidator.Validate(Arg.Any()).Returns([]); _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + _mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(Result.Success); - _sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + _sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } [Fact] @@ -87,6 +92,13 @@ public class DeleteTrackCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); + // The artwork of the track is removed before the track is removed from the artist aggregate, so that no artwork is orphaned. + await _mockMusicArtworkCleanupService.Received(1).DeleteTrackArtworkAsync(trackId, Arg.Any()); + Received.InOrder(() => + { + _mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, Arg.Any()); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()); + }); await _mockArtistRepository.Received(1).UpdateAsync( Arg.Is(updatedArtist => updatedArtist.Id == artistId && @@ -141,6 +153,7 @@ public class DeleteTrackCommandHandlerTests Assert.Equal(DomainErrors.Music.TrackIdCannotBeEmpty, result.FirstError); await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkCleanupService.DidNotReceive().DeleteTrackArtworkAsync(Arg.Any(), Arg.Any()); await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -360,6 +373,28 @@ public class DeleteTrackCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutUpdatingTheArtist() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); + StubArtistAndLibrary(artist, libraryId); + Error error = Error.Failure(description: "Failed to delete the artwork"); + _mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs index 293a41b1..9513bdcd 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs @@ -1,4 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Application.Core.MediaLibrary.Management.Events; using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; @@ -17,6 +20,7 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; @@ -27,6 +31,11 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; [ExcludeFromCodeCoverage] public class LibraryDeletedDomainEventHandlerTests { + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IArtistRepository _mockArtistRepository; + private readonly IBookRepository _mockBookRepository; + private readonly IMusicLibraryScanItemMetadataRepository _mockMusicLibraryScanItemMetadataRepository; private readonly IEnvironmentContext _mockEnvironmentContext; private readonly IDirectoryProviderService _mockDirectoryProviderService; private readonly IPathService _mockPathService; @@ -40,6 +49,20 @@ public class LibraryDeletedDomainEventHandlerTests /// public LibraryDeletedDomainEventHandlerTests() { + _mockUnitOfWork = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockMusicLibraryScanItemMetadataRepository = Substitute.For(); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicLibraryScanItemMetadataRepository); + _mockMusicArtworkRepository.DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockArtistRepository.DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockBookRepository.DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicLibraryScanItemMetadataRepository.DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockEnvironmentContext = Substitute.For(); _mockDirectoryProviderService = Substitute.For(); _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); @@ -48,20 +71,24 @@ public class LibraryDeletedDomainEventHandlerTests MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create( rootDirectory: "Media", librariesDirectory: "Libraries", - booksDirectory: "Books"); + booksDirectory: "Books", + musicDirectory: "Music"); IOptions mediaSettingsOptions = Substitute.For>(); mediaSettingsOptions.Value.Returns(mediaSettings); - // default stubs: all path combinations succeed and the directory is deleted successfully + // default stubs: all path combinations succeed, segments are sanitized to their input, the library directories exist and they are deleted successfully _mockPathService.CombinePath(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => PathSegment.Create(callInfo.ArgAt(0), isDirectory: false, isDrive: false)); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); _mockDirectoryProviderService.DeleteDirectory(Arg.Any()).Returns(Result.Deleted); - _sut = new LibraryDeletedDomainEventHandler(_mockEnvironmentContext, _mockPathService, mediaSettingsOptions); + _sut = new LibraryDeletedDomainEventHandler(_mockUnitOfWork, _mockEnvironmentContext, _mockPathService, mediaSettingsOptions); } [Fact] - public async Task HandleAsync_WhenLibraryIsDeleted_ShouldDeleteLibraryDirectory() + public async Task HandleAsync_WhenLibraryIsDeleted_ShouldDeleteMediaItemsAndLibraryDirectory() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -72,7 +99,11 @@ public class LibraryDeletedDomainEventHandlerTests await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - _mockDirectoryProviderService.Received(1).DeleteDirectory( + await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + _mockDirectoryProviderService.Received(3).DeleteDirectory( Arg.Is(path => path.Path.EndsWith(libraryId.ToString(), StringComparison.Ordinal))); } @@ -112,4 +143,243 @@ public class LibraryDeletedDomainEventHandlerTests Assert.Equal(error, exception.EventualConsistencyError); _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenDeleteMusicArtworkFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingAnythingElse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + Error error = Error.Failure(description: "Failed to delete music artwork"); + _mockMusicArtworkRepository.DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockArtistRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteArtistsFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingAnythingElse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + Error error = Error.Failure(description: "Failed to delete artists"); + _mockArtistRepository.DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + // The artwork is deleted before its owners, so that its owners are still present when the artwork is looked up. + await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteBooksFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingAnythingElse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + Error error = Error.Failure(description: "Failed to delete books"); + _mockBookRepository.DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteStagedMusicMetadataFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingAnythingElse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + Error error = Error.Failure(description: "Failed to delete staged music metadata"); + _mockMusicLibraryScanItemMetadataRepository.DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSanitizeSegmentFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingItemDirectories() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + Error error = Error.Failure(description: "Failed to sanitize segment"); + _mockPathService.SanitizeSegment(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + // Only the libraries directory, deleted before the segment is sanitized, was removed. + _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIsDeleted_ShouldDeleteEachMediaTypeDirectoryAtItsExactPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + string libraryTitle = "My Library"; + Library library = _libraryFixture.Create(id: libraryId, title: libraryTitle); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + string librarySegment = $"{libraryTitle}-{libraryId}"; + string expectedLibrariesPath = string.Concat(AppContext.BaseDirectory, "Media", "Libraries", libraryId.ToString()); + string expectedBooksPath = string.Concat(AppContext.BaseDirectory, "Media", "Books", librarySegment); + string expectedMusicPath = string.Concat(AppContext.BaseDirectory, "Media", "Music", librarySegment); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + _mockPathService.Received(1).SanitizeSegment(librarySegment); + _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is(path => path.Path == expectedLibrariesPath)); + _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is(path => path.Path == expectedBooksPath)); + _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is(path => path.Path == expectedMusicPath)); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDirectoryDoesNotExist_ShouldSkipDeletingIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(false)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + // The media items are still removed, but a directory that does not exist is not an error. + await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDirectoryExistsFails_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + Error error = Error.Failure(description: "Failed to check directory existence"); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCombiningTheMediaTypeDirectoryPathFails_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, title: "My Library"); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + Error error = Error.Failure(description: "Failed to combine the media type directory path"); + // Only the combination of the media type segment of the books directory fails, after the libraries directory was already removed. + _mockPathService.CombinePath(Arg.Any(), "Books").Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + // Only the libraries directory, whose path was combined before the failure, was removed. + _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCombiningTheLibraryDirectoryPathFails_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + string libraryTitle = "My Library"; + Library library = _libraryFixture.Create(id: libraryId, title: libraryTitle); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + string librarySegment = $"{libraryTitle}-{libraryId}"; + Error error = Error.Failure(description: "Failed to combine the library directory path"); + // Only the combination of the leaf library segment of the books directory fails. + _mockPathService.CombinePath(Arg.Is(path => path.EndsWith("Books", StringComparison.Ordinal)), librarySegment).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + // Only the libraries directory, whose path was combined before the failure, was removed. + _mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCreatingTheLibraryPathIdFails_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, title: "My Library"); + LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library); + // The combined leaf path of the libraries directory is blank, so the path value object cannot be created from it. + _mockPathService.CombinePath(Arg.Any(), Arg.Is(libraryId.ToString())).Returns(Result.From(" ")); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, exception.EventualConsistencyError); + _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); + } }