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;
}
}