Adds the media library item deletion strategies and their domain event handler integration

This commit is contained in:
BinaryAlley committed 2026-10-09 01:23:00 +03:00
1 parent 35ac1dbdcb
commit b7db29eee5
7 files changed
+811 -113

No files matched your search

@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Deletion;
/// <summary>
/// Deletion strategy for the media library items of the books media library type. The book stored at the deleted path is removed, together with its stored artwork.
/// </summary>
internal sealed class BooksMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
private readonly ILogger<BooksMediaLibraryItemDeletionStrategy> _logger;
/// <summary>
/// The media library type that this deletion strategy supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Book;
/// <summary>
/// Initializes a new instance of the <see cref="BooksMediaLibraryItemDeletionStrategy"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="bookArtworkService">Injected service for storing the artwork of the books.</param>
/// <param name="logger">Injected logger used to report the issues encountered while deleting the media library item.</param>
public BooksMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger<BooksMediaLibraryItemDeletionStrategy> logger)
{
_unitOfWork = unitOfWork;
_bookArtworkService = bookArtworkService;
_logger = logger;
}
/// <summary>
/// Deletes the book stored at the provided <paramref name="path"/> in the media library identified by <paramref name="libraryId"/>, together with its stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book is deleted.</param>
/// <param name="path">The file system path of the book to delete.</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<Success>> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken)
{
// Load the book stored at the deleted path, which might have been already removed.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, path, cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
BookEntity? book = getBookResult.Value;
if (book is null)
return Result.Success;
// Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
return getLibraryResult.IsFailure ? getLibraryResult.Errors : Errors.Library.LibraryNotFound;
LibraryEntity library = getLibraryResult.Value;
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await _unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
return getAuthorsResult.Errors;
string authorName = getAuthorsResult.Value.TryGetValue(book.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title);
if (deleteArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path);
// Delete the book, whose stored artwork and participations are removed by the database cascade.
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false);
if (deleteBookResult.IsFailure)
return deleteBookResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Success;
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Deletion;
/// <summary>
/// Interface defining the strategy used to delete a media library item that is no longer present in the media library scan snapshot, for a specific media library type.
/// </summary>
public interface IMediaLibraryItemDeletionStrategy
{
/// <summary>
/// The media library type that this deletion strategy supports.
/// </summary>
LibraryType SupportedLibraryType { get; }
/// <summary>
/// Deletes the media library item stored at the provided <paramref name="path"/> in the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose item is deleted.</param>
/// <param name="path">The file system path of the media library item to delete.</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<Success>> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken);
}
@@ -0,0 +1,121 @@
#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 Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Deletion;
/// <summary>
/// Deletion strategy for the media library items of the music media library type. The track stored at the deleted path is removed, together with its stored artwork,
/// and the album and the artist that are left with no children after the removal are removed as well.
/// </summary>
internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// The media library type that this deletion strategy supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Music;
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaLibraryItemDeletionStrategy"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public MusicMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Deletes the track stored at the provided <paramref name="path"/> in the media library identified by <paramref name="libraryId"/>, together with its stored artwork,
/// and the album and the artist that are left with no children after the removal.
/// </summary>
/// <param name="libraryId">The Id of the media library whose track is deleted.</param>
/// <param name="path">The file system path of the track to delete.</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<Success>> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken)
{
// Load the track stored at the deleted path, which might have been already removed.
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByPathAsync(libraryId, path, cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
TrackEntity? track = getTrackResult.Value;
if (track is null)
return Result.Success;
Guid trackId = track.Id;
Guid albumId = track.AlbumId;
// Delete the stored artwork of the track, which has no cascade relationship because the artwork table is shared by all the music library item types.
Result<Deleted> deleteTrackArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken).ConfigureAwait(false);
if (deleteTrackArtworkResult.IsFailure)
return deleteTrackArtworkResult.Errors;
Result<Deleted> deleteTrackResult = await _unitOfWork.TrackRepository.DeleteByIdAsync(trackId, cancellationToken).ConfigureAwait(false);
if (deleteTrackResult.IsFailure)
return deleteTrackResult.Errors;
// Load the album the deleted track belonged to, to determine whether it is left with no children.
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
AlbumEntity? album = getAlbumResult.Value;
if (album is null)
return await SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Guid artistId = album.ArtistId;
Result<IReadOnlyList<TrackEntity>> getRemainingTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (getRemainingTracksResult.IsFailure)
return getRemainingTracksResult.Errors;
// The deleted track is still tracked by the change tracker until the changes are saved, so it is excluded explicitly.
if (getRemainingTracksResult.Value.All(remainingTrack => remainingTrack.Id == trackId))
{
Result<Deleted> deleteAlbumArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
if (deleteAlbumArtworkResult.IsFailure)
return deleteAlbumArtworkResult.Errors;
Result<Deleted> deleteAlbumResult = await _unitOfWork.AlbumRepository.DeleteByIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (deleteAlbumResult.IsFailure)
return deleteAlbumResult.Errors;
Result<IReadOnlyList<AlbumEntity>> getRemainingAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (getRemainingAlbumsResult.IsFailure)
return getRemainingAlbumsResult.Errors;
// The deleted album is still tracked by the change tracker until the changes are saved, so it is excluded explicitly.
if (getRemainingAlbumsResult.Value.All(remainingAlbum => remainingAlbum.Id == albumId))
{
Result<Deleted> deleteArtistArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistArtworkResult.IsFailure)
return deleteArtistArtworkResult.Errors;
Result<Deleted> deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistResult.IsFailure)
return deleteArtistResult.Errors;
}
}
return await SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Persists the changes made to the storage medium.
/// </summary>
/// <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<Success>> SaveChangesAsync(CancellationToken cancellationToken)
{
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return saveChangesResult.IsFailure ? saveChangesResult.Errors : Result.Success;
}
}
@@ -1,15 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.Management.Deletion;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -18,24 +20,24 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the domain event raised when a media library item is no longer present in the media library scan snapshot.
/// The book stored at the deleted path is removed, together with its stored artwork.
/// The media library item stored at the deleted path is removed by the deletion strategy of the media library type it belongs to.
/// </summary>
public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<LibraryMediaItemDeletedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
private readonly IEnumerable<IMediaLibraryItemDeletionStrategy> _mediaLibraryItemDeletionStrategies;
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMediaItemDeletedDomainEventHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="bookArtworkService">Injected service for storing the artwork of the books.</param>
/// <param name="mediaLibraryItemDeletionStrategies">Injected deletion strategies, one for each supported media library type.</param>
/// <param name="logger">Injected logger used to report the issues encountered while deleting the media library item.</param>
public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger<LibraryMediaItemDeletedDomainEventHandler> logger)
public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IEnumerable<IMediaLibraryItemDeletionStrategy> mediaLibraryItemDeletionStrategies, ILogger<LibraryMediaItemDeletedDomainEventHandler> logger)
{
_unitOfWork = unitOfWork;
_bookArtworkService = bookArtworkService;
_mediaLibraryItemDeletionStrategies = mediaLibraryItemDeletionStrategies;
_logger = logger;
}
@@ -48,36 +50,23 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<Lib
{
Guid libraryId = domainEvent.LibraryId.Value;
// Load the book stored at the deleted path, which might have been already removed.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
throw new EventualConsistencyException(getBookResult.FirstError, getBookResult.Errors);
BookEntity? book = getBookResult.Value;
if (book is null)
return;
// Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed.
// Load the media library, whose type determines the deletion strategy to use.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
if (getLibraryResult.IsFailure)
throw new EventualConsistencyException(getLibraryResult.FirstError, getLibraryResult.Errors);
LibraryEntity library = getLibraryResult.Value;
if (getLibraryResult.Value is null)
throw new EventualConsistencyException(Errors.Library.LibraryNotFound);
LibraryType libraryType = getLibraryResult.Value.LibraryType;
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await _unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
throw new EventualConsistencyException(getAuthorsResult.FirstError, getAuthorsResult.Errors);
string authorName = getAuthorsResult.Value.TryGetValue(book.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
IMediaLibraryItemDeletionStrategy? deletionStrategy = _mediaLibraryItemDeletionStrategies.FirstOrDefault(strategy => strategy.SupportedLibraryType == libraryType);
if (deletionStrategy is null)
{
_logger.LogWarning("No deletion strategy exists for media library type '{LibraryType}', the item at path '{ItemPath}' was not deleted.", libraryType, domainEvent.Path);
return;
}
Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title);
if (deleteArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path);
// Delete the book, whose stored artwork and participations are removed by the database cascade.
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false);
if (deleteBookResult.IsFailure)
throw new EventualConsistencyException(deleteBookResult.FirstError, deleteBookResult.Errors);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
Result<Success> deleteItemResult = await deletionStrategy.DeleteItemAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false);
if (deleteItemResult.IsFailure)
throw new EventualConsistencyException(deleteItemResult.FirstError, deleteItemResult.Errors);
}
}