Cleans up the artwork and the stored media of deleted music library items and libraries.

This commit is contained in:
BinaryAlley committed 2026-10-13 13:26:26 +03:00
1 parent 9d82f283e4
commit 4f43bf352b
23 files changed
+1390 -74

No files matched your search

@@ -123,4 +123,12 @@ public interface IBookRepository : IRepository<BookEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the display names of the authors of the books, keyed by book Id, or an error.</returns>
Task<Result<IReadOnlyDictionary<Guid, string?>>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection<Guid> bookIds, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the books of the media library identified by <paramref name="libraryId"/>, together with their artwork and their related data.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -78,4 +78,12 @@ public interface IArtistRepository : IRepository<ArtistEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the artists of the media library identified by <paramref name="libraryId"/>, together with their albums and tracks and their related data.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artists are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -46,4 +46,23 @@ public interface IMusicArtworkRepository : IRepository<MusicArtworkEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the pieces of artwork owned by the artists, albums and tracks of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Stores the cover image of the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>,
/// replacing the file of its existing cover, or adding a new cover artwork when it has none.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored cover image.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> UpsertCoverAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName, CancellationToken cancellationToken);
}
@@ -32,4 +32,12 @@ public interface IMusicLibraryScanItemMetadataRepository : IRepository<MusicLibr
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByScanIdAsync(Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the staged music metadata items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose staged music metadata is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -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<IMediaLibraryItemDeletionStrategy, BooksMediaLibraryItemDeletionStrategy>();
services.AddScoped<IMediaLibraryItemDeletionStrategy, MusicMediaLibraryItemDeletionStrategy>();
services.AddScoped<IMusicArtworkCleanupService, MusicArtworkCleanupService>();
foreach (var registration in handlerRegistrations)
{
@@ -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<DeleteAlbumCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkCleanupService _musicArtworkCleanupService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteAlbumCommand> _validator;
@@ -36,12 +38,14 @@ public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Res
/// Initializes a new instance of the <see cref="DeleteAlbumCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkCleanupService">Injected service for removing the artwork of a music library item and of its children.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteAlbumCommand> validator)
public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteAlbumCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
@@ -115,6 +119,12 @@ public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Res
if (removeAlbumResult.IsFailure)
return removeAlbumResult.Errors;
// The artwork of the album and of its tracks does not cascade from the album row, because the artwork table is shared by all the music
// library item types, so it is removed first, while the album and its tracks are still present.
Result<Deleted> deleteArtworkResult = await _musicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, cancellationToken).ConfigureAwait(false);
if (deleteArtworkResult.IsFailure)
return deleteArtworkResult.Errors;
Result<Updated> updateResult = await _unitOfWork.ArtistRepository
.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
@@ -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<DeleteArtistCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkCleanupService _musicArtworkCleanupService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteArtistCommand> _validator;
@@ -32,12 +34,14 @@ public class DeleteArtistCommandHandler : ICommandHandler<DeleteArtistCommand, R
/// Initializes a new instance of the <see cref="DeleteArtistCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkCleanupService">Injected service for removing the artwork of a music library item and of its children.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteArtistCommand> validator)
public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteArtistCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
@@ -92,6 +96,12 @@ public class DeleteArtistCommandHandler : ICommandHandler<DeleteArtistCommand, R
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// The artwork of the artist and of its albums and tracks does not cascade from the artist row, because the artwork table is shared by all
// the music library item types, so it is removed first, while the artist and its children are still present.
Result<Deleted> deleteArtworkResult = await _musicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtworkResult.IsFailure)
return deleteArtworkResult.Errors;
Result<Deleted> deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistResult.IsFailure)
return deleteArtistResult.Errors;
@@ -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;
/// <summary>
/// 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.
/// </summary>
public interface IMusicArtworkCleanupService
{
/// <summary>
/// Removes the artwork records and the stored artwork files of the artist identified by <paramref name="artistId"/>, together with the artwork of its albums and tracks.
/// </summary>
/// <param name="artistId">The Id of the artist whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteArtistArtworkAsync(Guid artistId, CancellationToken cancellationToken);
/// <summary>
/// Removes the artwork records and the stored artwork files of the album identified by <paramref name="albumId"/>, together with the artwork of its tracks.
/// </summary>
/// <param name="albumId">The Id of the album whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteAlbumArtworkAsync(Guid albumId, CancellationToken cancellationToken);
/// <summary>
/// Removes the artwork records and the stored artwork files of the track identified by <paramref name="trackId"/>.
/// </summary>
/// <param name="trackId">The Id of the track whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Deleted>> DeleteTrackArtworkAsync(Guid trackId, CancellationToken cancellationToken);
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal sealed class MusicArtworkCleanupService : IMusicArtworkCleanupService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkService _musicArtworkService;
/// <summary>
/// Initializes a new instance of the <see cref="MusicArtworkCleanupService"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkService">Injected service for removing the stored artwork files of a music library item.</param>
public MusicArtworkCleanupService(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService)
{
_unitOfWork = unitOfWork;
_musicArtworkService = musicArtworkService;
}
/// <summary>
/// Removes the artwork records and the stored artwork files of the artist identified by <paramref name="artistId"/>, together with the artwork of its albums and tracks.
/// </summary>
/// <param name="artistId">The Id of the artist whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> 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<IReadOnlyList<AlbumEntity>> getAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (getAlbumsResult.IsFailure)
return getAlbumsResult.Errors;
foreach (AlbumEntity album in getAlbumsResult.Value)
{
Result<Deleted> deleteAlbumArtworkResult = await DeleteAlbumArtworkAsync(album.Id, cancellationToken).ConfigureAwait(false);
if (deleteAlbumArtworkResult.IsFailure)
return deleteAlbumArtworkResult.Errors;
}
return await DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Removes the artwork records and the stored artwork files of the album identified by <paramref name="albumId"/>, together with the artwork of its tracks.
/// </summary>
/// <param name="albumId">The Id of the album whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> 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<IReadOnlyList<TrackEntity>> getTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (getTracksResult.IsFailure)
return getTracksResult.Errors;
foreach (TrackEntity track in getTracksResult.Value)
{
Result<Deleted> deleteTrackArtworkResult = await DeleteTrackArtworkAsync(track.Id, cancellationToken).ConfigureAwait(false);
if (deleteTrackArtworkResult.IsFailure)
return deleteTrackArtworkResult.Errors;
}
return await DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Removes the artwork records and the stored artwork files of the track identified by <paramref name="trackId"/>.
/// </summary>
/// <param name="trackId">The Id of the track whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Task<Result<Deleted>> DeleteTrackArtworkAsync(Guid trackId, CancellationToken cancellationToken)
{
return DeleteOwnerArtworkAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken);
}
/// <summary>
/// Removes the artwork records and the stored artwork files of the single music library item identified by <paramref name="ownerType"/> and <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item whose artwork is removed.</param>
/// <param name="ownerId">The Id of the music library item whose artwork is removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Deleted>> DeleteOwnerArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken)
{
Result<IReadOnlyList<MusicArtworkEntity>> 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<Deleted> deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName);
if (deleteStoredArtworkResult.IsFailure)
return deleteStoredArtworkResult.Errors;
}
return await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
}
}
@@ -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<DeleteTrackCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkCleanupService _musicArtworkCleanupService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteTrackCommand> _validator;
@@ -36,12 +38,14 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
/// Initializes a new instance of the <see cref="DeleteTrackCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="musicArtworkCleanupService">Injected service for removing the artwork of a music library item and of its children.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteTrackCommand> validator)
public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteTrackCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
@@ -122,6 +126,12 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
if (removeTrackResult.IsFailure)
return removeTrackResult.Errors;
// The artwork of the track does not cascade from the track row, because the artwork table is shared by all the music library item
// types, so it is removed first, while the track is still present.
Result<Deleted> deleteArtworkResult = await _musicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, cancellationToken).ConfigureAwait(false);
if (deleteArtworkResult.IsFailure)
return deleteArtworkResult.Errors;
Result<Updated> updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
@@ -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;
/// </summary>
public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDeletedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IEnvironmentContext _environmentContext;
private readonly IPathService _pathService;
private readonly MediaSettingsDto _mediaSettingsModel;
@@ -27,11 +29,13 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDelet
/// <summary>
/// Initializes a new instance of the <see cref="LibraryDeletedDomainEventHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsDto"/>.</param>
public LibraryDeletedDomainEventHandler(IEnvironmentContext environmentContext, IPathService pathService, IOptions<MediaSettingsDto> mediaSettingsModelOptions)
public LibraryDeletedDomainEventHandler(IUnitOfWork unitOfWork, IEnvironmentContext environmentContext, IPathService pathService, IOptions<MediaSettingsDto> mediaSettingsModelOptions)
{
_unitOfWork = unitOfWork;
_environmentContext = environmentContext;
_pathService = pathService;
_mediaSettingsModel = mediaSettingsModelOptions.Value;
@@ -42,47 +46,80 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDelet
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
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<string> libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value);
if (libraryPathResult.IsFailure)
throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors);
Guid libraryId = domainEvent.Library.Id.Value;
Result<FileSystemPathId> 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<Deleted> deleteMusicArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (deleteMusicArtworkResult.IsFailure)
throw new EventualConsistencyException(deleteMusicArtworkResult.FirstError, deleteMusicArtworkResult.Errors);
Result<Deleted> 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<Deleted> 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<Deleted> 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<Deleted> 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<PathSegment> 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);
}
/// <summary>
/// Gets the file system path of a media library identified by <paramref name="libraryId"/>.
/// Deletes the directory of a media library from the internal media location of the provided media type.
/// </summary>
/// <param name="libraryId">The id of the media library for which to regtrieve the file system path.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the file system path of the media library, or an error message.
/// </returns>
private Result<string> GetLibraryPath(Guid libraryId)
/// <param name="mediaTypeDirectory">The name of the media type subdirectory the library directory is stored under.</param>
/// <param name="libraryDirectoryName">The name of the directory of the media library.</param>
private void DeleteLibraryDirectory(string mediaTypeDirectory, string libraryDirectoryName)
{
// root directory for media
// Root directory for media.
Result<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory);
if (rootPathResult.IsFailure)
return rootPathResult.Errors;
throw new EventualConsistencyException(rootPathResult.FirstError, rootPathResult.Errors);
// libraries directory
Result<string> librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory);
if (librariesPathResult.IsFailure)
return librariesPathResult.Errors;
// Media type directory.
Result<string> mediaTypePathResult = _pathService.CombinePath(rootPathResult.Value, mediaTypeDirectory);
if (mediaTypePathResult.IsFailure)
throw new EventualConsistencyException(mediaTypePathResult.FirstError, mediaTypePathResult.Errors);
// this new particular library' directory
Result<string> libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString());
// This particular library's directory.
Result<string> libraryPathResult = _pathService.CombinePath(mediaTypePathResult.Value, libraryDirectoryName);
if (libraryPathResult.IsFailure)
return libraryPathResult.Errors;
return libraryPathResult.Value;
throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors);
Result<FileSystemPathId> 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<bool> directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value);
if (directoryExistsResult.IsFailure)
throw new EventualConsistencyException(directoryExistsResult.FirstError, directoryExistsResult.Errors);
if (!directoryExistsResult.Value)
return;
Result<Deleted> deleteLibraryDirectoryResult = _environmentContext.DirectoryProviderService.DeleteDirectory(libraryPathIdResult.Value);
if (deleteLibraryDirectoryResult.IsFailure)
throw new EventualConsistencyException(deleteLibraryDirectoryResult.FirstError, deleteLibraryDirectoryResult.Errors);
}
}
@@ -462,6 +462,21 @@ internal sealed class BookRepository : IBookRepository
return Result.Updated;
}
/// <summary>
/// Deletes all the books of the media library identified by <paramref name="libraryId"/>, together with their artwork and their related data.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> 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;
}
/// <summary>
/// Gets the display names of the author of the books identified by the provided <paramref name="bookIds"/>,
/// keyed by the Id of the book, or <see langword="null"/> when a book has no author.
@@ -85,25 +85,84 @@ internal sealed class MusicArtworkRepository : IMusicArtworkRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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<Guid> artistIds = await _luminaDbContext.Artists
.Where(artist => artist.LibraryId == libraryId)
.Select(artist => artist.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<Guid> albumIds = await _luminaDbContext.Albums
.Where(album => album.LibraryId == libraryId)
.Select(album => album.Id)
.ToListAsync(cancellationToken).ConfigureAwait(false);
List<Guid> 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;
}
/// <summary>
/// Deletes all the pieces of artwork owned by the artists, albums and tracks of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose artwork is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> 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;
}
/// <summary>
/// Stores the cover image of the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored cover image.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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;
}
}
@@ -71,4 +71,18 @@ internal sealed class MusicLibraryScanItemMetadataRepository : IMusicLibraryScan
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted;
}
/// <summary>
/// Deletes all the staged music metadata items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose staged music metadata is deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
await _luminaDbContext.MusicLibraryScanItemMetadata
.Where(musicMetadata => musicMetadata.LibraryId == libraryId)
.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
return Result.Deleted;
}
}
@@ -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<LuminaDbContext>().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<Deleted> 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);
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
@@ -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<AuthenticatedLuminaApiFact
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -77,6 +80,28 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => 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<LuminaDbContext>();
// 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<AuthenticatedLuminaApiFact
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
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<LuminaDbContext>();
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);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
@@ -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<AuthenticatedLuminaApiFac
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -73,6 +78,33 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => 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<LuminaDbContext>();
// 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<AuthenticatedLuminaApiFac
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
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<LuminaDbContext>();
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);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
@@ -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<AuthenticatedLuminaApiFact
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -81,6 +84,26 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => 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<LuminaDbContext>();
// 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<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<AuthenticatedLuminaApiFact
// The route value is kept as a raw string, so the unparseable Id reaches the command validator, which reports a clean validation error instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("TrackIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
@@ -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<DeleteAlbumCommand> _mockValidator;
@@ -55,24 +57,27 @@ public class DeleteAlbumCommandHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockMusicArtworkCleanupService = Substitute.For<IMusicArtworkCleanupService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<DeleteAlbumCommand>>();
_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<DeleteAlbumCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.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<CancellationToken>());
Received.InOrder(() =>
{
_mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, Arg.Any<CancellationToken>());
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
});
await _mockArtistRepository.Received(1).UpdateAsync(
Arg.Is<ArtistEntity>(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<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkCleanupService.DidNotReceive().DeleteAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -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<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(error);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -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<DeleteArtistCommand> _mockValidator;
@@ -52,24 +54,27 @@ public class DeleteArtistCommandHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockMusicArtworkCleanupService = Substitute.For<IMusicArtworkCleanupService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<DeleteArtistCommand>>();
_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<DeleteArtistCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtistRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.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<CancellationToken>());
Received.InOrder(() =>
{
_mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, Arg.Any<CancellationToken>());
_mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
});
await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
@@ -110,6 +122,7 @@ public class DeleteArtistCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkCleanupService.DidNotReceive().DeleteArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -259,6 +272,30 @@ public class DeleteArtistCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
Error error = Error.Failure(description: "Failed to delete the artwork");
_mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteArtistFails_ShouldReturnErrorWithoutSaving()
{
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicArtworkCleanupService"/> class.
/// </summary>
[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();
/// <summary>
/// Initializes a new instance of the <see cref="MusicArtworkCleanupServiceTests"/> class.
/// </summary>
public MusicArtworkCleanupServiceTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
_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<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([]));
_mockTrackRepository.GetByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([]));
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>()).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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([firstAlbum, secondAlbum]));
_mockTrackRepository.GetByAlbumIdAsync(firstAlbumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([firstTrack, secondTrack]));
_mockTrackRepository.GetByAlbumIdAsync(secondAlbumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([thirdTrack]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([firstTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([secondTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, thirdTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([thirdTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, firstAlbumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([firstAlbumArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, secondAlbumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([secondAlbumArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([artistArtwork]));
// Act
Result<Deleted> 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<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, firstAlbumId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, thirdTrackId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, secondAlbumId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>());
});
}
[Fact]
public async Task DeleteArtistArtworkAsync_WhenGetAlbumsFails_ShouldReturnTheErrorWithoutDeletingAnyArtwork()
{
// Arrange
Guid artistId = Guid.NewGuid();
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([firstTrack, secondTrack]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([firstTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([secondTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([albumArtwork]));
// Act
Result<Deleted> 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<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
});
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenGetTracksFails_ShouldReturnTheErrorWithoutDeletingAnyArtwork()
{
// Arrange
Guid albumId = Guid.NewGuid();
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenGetArtworkFails_ShouldReturnTheErrorWithoutDeletingTheRecords()
{
// Arrange
Guid albumId = Guid.NewGuid();
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenDeletingTheArtworkRecordsFails_ShouldReturnTheError()
{
// Arrange
Guid albumId = Guid.NewGuid();
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([albumArtwork]));
_mockMusicArtworkService.DeleteStoredArtwork(albumArtwork.FileName!)
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> 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<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([unresolvedArtwork]));
// Act
Result<Deleted> result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([trackArtwork]));
// Act
Result<Deleted> 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<CancellationToken>());
}
[Fact]
public async Task DeleteTrackArtworkAsync_WhenNoArtworkExists_ShouldStillDeleteTheRecords()
{
// Arrange
Guid trackId = Guid.NewGuid();
// Act
Result<Deleted> result = await _sut.DeleteTrackArtworkAsync(trackId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any<CancellationToken>());
}
}
@@ -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<DeleteTrackCommand> _mockValidator;
@@ -54,22 +56,25 @@ public class DeleteTrackCommandHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockMusicArtworkCleanupService = Substitute.For<IMusicArtworkCleanupService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<DeleteTrackCommand>>();
_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<DeleteTrackCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.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<CancellationToken>());
Received.InOrder(() =>
{
_mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, Arg.Any<CancellationToken>());
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
});
await _mockArtistRepository.Received(1).UpdateAsync(
Arg.Is<ArtistEntity>(updatedArtist =>
updatedArtist.Id == artistId &&
@@ -141,6 +153,7 @@ public class DeleteTrackCommandHandlerTests
Assert.Equal(DomainErrors.Music.TrackIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkCleanupService.DidNotReceive().DeleteTrackArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -360,6 +373,28 @@ public class DeleteTrackCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(error);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving()
{
@@ -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
/// </summary>
public LibraryDeletedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMusicLibraryScanItemMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicLibraryScanItemMetadataRepository);
_mockMusicArtworkRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockArtistRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockBookRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockMusicLibraryScanItemMetadataRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_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<MediaSettingsDto> mediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
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<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo => PathSegment.Create(callInfo.ArgAt<string>(0), isDirectory: false, isDrive: false));
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockDirectoryProviderService.DeleteDirectory(Arg.Any<FileSystemPathId>()).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<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockDirectoryProviderService.Received(3).DeleteDirectory(
Arg.Is<FileSystemPathId>(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<FileSystemPathId>());
}
[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<Guid>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockArtistRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[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<Guid>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _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<CancellationToken>());
await _mockBookRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[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<Guid>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[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<Guid>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[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<string>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
// Only the libraries directory, deleted before the segment is sanitized, was removed.
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[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<FileSystemPathId>(path => path.Path == expectedLibrariesPath));
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is<FileSystemPathId>(path => path.Path == expectedBooksPath));
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is<FileSystemPathId>(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<FileSystemPathId>()).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<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[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<FileSystemPathId>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[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<string>(), "Books").Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _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<FileSystemPathId>());
}
[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<string>(path => path.EndsWith("Books", StringComparison.Ordinal)), librarySegment).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _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<FileSystemPathId>());
}
[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<string>(), Arg.Is(libraryId.ToString())).Returns(Result.From(" "));
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, exception.EventualConsistencyError);
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
}