Adds deletion and restore for music library items.

This commit is contained in:
BinaryAlley committed 2026-11-15 18:53:10 +02:00
1 parent 98515dc5e8
commit f9ad8b2fc5
224 files changed
+22384 -1360

No files matched your search

@@ -231,6 +231,17 @@ public class AlbumEntity : IStorageEntity, IAuditableEntity
/// </summary>
public string? MetadataProvider { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the album was deleted by the user and is waiting to be restored or permanently removed.
/// A deleted album is kept out of every catalogue read and is not materialized again by scans, so that an automatic scan never undoes the deletion.
/// </summary>
public bool IsDeleted { get; set; }
/// <summary>
/// Gets or sets the date and time when the album was deleted, or <see langword="null"/> when the album is not deleted.
/// </summary>
public DateTime? DeletedOnUtc { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -150,6 +150,17 @@ public class ArtistEntity : IStorageEntity, IAuditableEntity
/// </summary>
public string? MetadataProvider { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the artist was deleted by the user and is waiting to be restored or permanently removed.
/// A deleted artist is kept out of every catalogue read and is not materialized again by scans, so that an automatic scan never undoes the deletion.
/// </summary>
public bool IsDeleted { get; set; }
/// <summary>
/// Gets or sets the date and time when the artist was deleted, or <see langword="null"/> when the artist is not deleted.
/// </summary>
public DateTime? DeletedOnUtc { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -291,6 +291,17 @@ public class TrackEntity : IStorageEntity, IAuditableEntity
/// </summary>
public string? MetadataProvider { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the track was deleted by the user and is waiting to be restored or permanently removed.
/// A deleted track is kept out of every catalogue read and is not materialized again by scans, so that an automatic scan never undoes the deletion.
/// </summary>
public bool IsDeleted { get; set; }
/// <summary>
/// Gets or sets the date and time when the track was deleted, or <see langword="null"/> when the track is not deleted.
/// </summary>
public DateTime? DeletedOnUtc { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -24,13 +24,61 @@ public interface IAlbumRepository : IRepository<AlbumEntity>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets all the albums of the artist identified by <paramref name="artistId"/>.
/// Gets the albums of the artist identified by <paramref name="artistId"/> that are not soft deleted.
/// </summary>
/// <param name="artistId">The Id of the artist whose albums are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="AlbumEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<AlbumEntity>>> GetByArtistIdAsync(Guid artistId, CancellationToken cancellationToken);
/// <summary>
/// Gets all the albums of the artist identified by <paramref name="artistId"/>, whether they are soft deleted or not.
/// </summary>
/// <param name="artistId">The Id of the artist whose albums are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="AlbumEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<AlbumEntity>>> GetByArtistIdIncludingDeletedAsync(Guid artistId, CancellationToken cancellationToken);
/// <summary>
/// Gets the album identified by <paramref name="id"/>, whether it is soft deleted or not, without loading its navigation properties.
/// </summary>
/// <param name="id">The Id of the album to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="AlbumEntity"/>, or an error.</returns>
Task<Result<AlbumEntity?>> GetIncludingDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Gets the soft deleted album identified by <paramref name="id"/>, when its artist is not soft deleted.
/// </summary>
/// <param name="id">The Id of the soft deleted album to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted <see cref="AlbumEntity"/>, <see langword="null"/> when the album does not exist, is not soft deleted, or its artist is soft deleted, or an error.</returns>
Task<Result<AlbumEntity?>> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Gets the soft deleted albums of the media library identified by <paramref name="libraryId"/>, whose artist is not soft deleted.
/// </summary>
/// <param name="libraryId">The Id of the media library whose soft deleted albums are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted albums, or an error.</returns>
Task<Result<IReadOnlyList<AlbumEntity>>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Soft deletes the album identified by <paramref name="id"/>, without removing its stored metadata or artwork, when another visible album of its artist remains.
/// </summary>
/// <param name="id">The Id of the album to soft 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<Updated>> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Restores the soft deleted album identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the album to restore.</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>> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Gets the lightweight read models of the albums of the artist identified by <paramref name="artistId"/>, projecting only the fields needed to display the albums in a card-based grid or a list.
/// </summary>
@@ -86,4 +86,36 @@ 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<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets the soft deleted artist identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the soft deleted artist to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted <see cref="ArtistEntity"/>, <see langword="null"/> when the artist does not exist or is not soft deleted, or an error.</returns>
Task<Result<ArtistEntity?>> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Gets the soft deleted artists of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose soft deleted artists are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted artists, or an error.</returns>
Task<Result<IReadOnlyList<ArtistEntity>>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Soft deletes the artist identified by <paramref name="id"/>, without removing its stored metadata or artwork.
/// </summary>
/// <param name="id">The Id of the artist to soft 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<Updated>> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Restores the soft deleted artist identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the artist to restore.</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>> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
}
@@ -33,13 +33,21 @@ public interface ITrackRepository : IRepository<TrackEntity>,
Task<Result<IReadOnlyCollection<string>>> GetExistingPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken);
/// <summary>
/// Gets all the tracks of the album identified by <paramref name="albumId"/>.
/// Gets the tracks of the album identified by <paramref name="albumId"/> that are not soft deleted.
/// </summary>
/// <param name="albumId">The Id of the album whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="TrackEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<TrackEntity>>> GetByAlbumIdAsync(Guid albumId, CancellationToken cancellationToken);
/// <summary>
/// Gets all the tracks of the album identified by <paramref name="albumId"/>, whether they are soft deleted or not.
/// </summary>
/// <param name="albumId">The Id of the album whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="TrackEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<TrackEntity>>> GetByAlbumIdIncludingDeletedAsync(Guid albumId, CancellationToken cancellationToken);
/// <summary>
/// Gets the lightweight read models of the tracks of the album identified by <paramref name="albumId"/>, projecting only the fields needed to display the tracks of an album.
/// </summary>
@@ -146,4 +154,36 @@ public interface ITrackRepository : IRepository<TrackEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the existing tracks, or an error.</returns>
Task<Result<IReadOnlyList<TrackEntity>>> GetByIdsAsync(IReadOnlyCollection<Guid> trackIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken);
/// <summary>
/// Gets the soft deleted track identified by <paramref name="id"/>, when its album and artist are not soft deleted.
/// </summary>
/// <param name="id">The Id of the soft deleted track to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted <see cref="TrackEntity"/>, <see langword="null"/> when the track does not exist, is not soft deleted, or its album or artist is soft deleted, or an error.</returns>
Task<Result<TrackEntity?>> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Gets the soft deleted tracks of the media library identified by <paramref name="libraryId"/>, whose album and artist are not soft deleted.
/// </summary>
/// <param name="libraryId">The Id of the media library whose soft deleted tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted tracks, or an error.</returns>
Task<Result<IReadOnlyList<TrackEntity>>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Soft deletes the track identified by <paramref name="id"/>, without removing its stored metadata or artwork.
/// </summary>
/// <param name="id">The Id of the track to soft 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<Updated>> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Restores the soft deleted track identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the track to restore.</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>> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
}
@@ -1,6 +1,5 @@
#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;
@@ -45,7 +44,6 @@ public static class ApplicationLayerServices
services.AddScoped<IMediaLibraryItemDeletionStrategy, BooksMediaLibraryItemDeletionStrategy>();
services.AddScoped<IMediaLibraryItemDeletionStrategy, MusicMediaLibraryItemDeletionStrategy>();
services.AddScoped<IMusicArtworkCleanupService, MusicArtworkCleanupService>();
foreach (var registration in handlerRegistrations)
{
@@ -228,6 +228,25 @@ public static class AlbumEntityMapping
artwork ?? []);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="DeletedAlbumResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="deletedOnUtc">The date and time when the album was deleted.</param>
/// <param name="coverPath">The optional path of the image representing the album.</param>
/// <returns>The converted response entity.</returns>
public static DeletedAlbumResponse ToResponse(this AlbumEntity repositoryEntity, DateTime deletedOnUtc, string? coverPath = null)
{
return new DeletedAlbumResponse(
repositoryEntity.Id,
repositoryEntity.LibraryId,
repositoryEntity.ArtistId,
repositoryEntity.Artist?.Name ?? string.Empty,
repositoryEntity.Title,
deletedOnUtc,
coverPath);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="AlbumResponse"/>.
/// </summary>
@@ -183,6 +183,23 @@ public static class ArtistEntityMapping
coverPath);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="DeletedArtistResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="deletedOnUtc">The date and time when the artist was deleted.</param>
/// <param name="coverPath">The optional path of the image representing the artist.</param>
/// <returns>The converted response entity.</returns>
public static DeletedArtistResponse ToResponse(this ArtistEntity repositoryEntity, DateTime deletedOnUtc, string? coverPath = null)
{
return new DeletedArtistResponse(
repositoryEntity.Id,
repositoryEntity.LibraryId,
repositoryEntity.Name,
deletedOnUtc,
coverPath);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="ArtistResponse"/>.
/// </summary>
@@ -293,6 +293,26 @@ public static class TrackEntityMapping
repositoryEntity.Container);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="DeletedTrackResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="deletedOnUtc">The date and time when the track was deleted.</param>
/// <returns>The converted response entity.</returns>
public static DeletedTrackResponse ToResponse(this TrackEntity repositoryEntity, DateTime deletedOnUtc)
{
return new DeletedTrackResponse(
repositoryEntity.Id,
repositoryEntity.LibraryId,
repositoryEntity.Album?.ArtistId ?? Guid.Empty,
repositoryEntity.Album?.Artist?.Name ?? string.Empty,
repositoryEntity.AlbumId,
repositoryEntity.Album?.Title ?? string.Empty,
repositoryEntity.Title,
repositoryEntity.Path,
deletedOnUtc);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="TrackResponse"/>.
/// </summary>
@@ -8,7 +8,6 @@ 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;
@@ -29,7 +28,6 @@ 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;
@@ -38,14 +36,12 @@ 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, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteAlbumCommand> validator)
public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteAlbumCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
@@ -74,7 +70,7 @@ public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Res
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
// An album is a child of the artist aggregate, so the whole aggregate is loaded and the album is removed within it.
// An album is a child of the artist aggregate, so the whole aggregate is loaded and the album is looked up within it.
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository
.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
@@ -94,10 +90,6 @@ public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Res
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
if (existingAlbum is null)
return DomainErrors.Music.AlbumNotFound;
// An album can only belong to a library that exists, so a client can never delete an album of a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository
.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -106,29 +98,25 @@ public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Res
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// The write path goes through the aggregate root: an album is a child entity of the artist aggregate, unlike Book and Artist,
// which are aggregate roots and are deleted directly through their own repositories. This difference is intentional.
Result<Artist> artistResult = existingArtist.ToDomainEntity();
if (artistResult.IsFailure)
return artistResult.Errors;
// The album is an entity inside the artist aggregate, so it is referenced by object, not by id; the aggregate member is located here and passed through.
Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId);
if (domainAlbum is null)
return DomainErrors.Music.AlbumNotFound;
Result<Deleted> removeAlbumResult = artistResult.Value.RemoveAlbum(domainAlbum);
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)
return updateResult.Errors;
Result<bool> canRemoveAlbumResult = artistResult.Value.CanRemoveAlbum(domainAlbum);
if (canRemoveAlbumResult.IsFailure)
return canRemoveAlbumResult.Errors;
// The album is soft deleted, so its metadata, artwork and track paths stay available until the user restores it or the files disappear
// from disk. The tracks of the album are not deleted themselves, so restoring the album brings back the tracks that were not deleted on their own.
// The write re-checks the last-album condition because this snapshot can be stale.
Result<Updated> deleteAlbumResult = await _unitOfWork.AlbumRepository.SoftDeleteByIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (deleteAlbumResult.IsFailure)
return deleteAlbumResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
/// <summary>
/// Command for restoring a deleted album by its Id.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this album belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album to restore, taken from the route.</param>
[DebuggerDisplay("AlbumId: {AlbumId}")]
public record RestoreAlbumCommand(
string? LibraryId,
string? ArtistId,
string? AlbumId
) : ICommand;
@@ -0,0 +1,97 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
/// <summary>
/// Handler for the command to restore a deleted album by its Id.
/// </summary>
public class RestoreAlbumCommandHandler : ICommandHandler<RestoreAlbumCommand, Result<Updated>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<RestoreAlbumCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreAlbumCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</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 RestoreAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<RestoreAlbumCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to restore a deleted album by its Id.
/// </summary>
/// <param name="command">The command to be handled.</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>> HandleAsync(RestoreAlbumCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
// A deleted album whose artist is also deleted is not restorable on its own, so the repository reports it as missing until the artist is restored.
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetSoftDeletedByIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return DomainErrors.Music.AlbumNotFound;
AlbumEntity existingAlbum = getAlbumResult.Value;
// Resource scoping: the album must belong to the artist and library named by the route, so that an album can never be restored through
// another library's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere.
if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
return DomainErrors.Music.AlbumNotFound;
// Admins can restore the albums of all libraries; for everyone else, only the albums of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<Updated> restoreAlbumResult = await _unitOfWork.AlbumRepository.RestoreSoftDeletedByIdAsync(existingAlbum.Id, cancellationToken).ConfigureAwait(false);
if (restoreAlbumResult.IsFailure)
return restoreAlbumResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Updated;
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
/// <summary>
/// Validates the needed validation rules for <see cref="RestoreAlbumCommand"/>.
/// </summary>
public class RestoreAlbumCommandValidator : AbstractValidator<RestoreAlbumCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RestoreAlbumCommandValidator"/> class.
/// </summary>
public RestoreAlbumCommandValidator()
{
// Validates the identifier of the media library that owns the album, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the artist the album belongs to, taken from the route.
RuleFor(command => command.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
RuleFor(command => command.ArtistId)
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
// Validates the identifier of the deleted album, taken from the route.
RuleFor(command => command.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
RuleFor(command => command.AlbumId)
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
.When(command => command.AlbumId is not null && command.AlbumId.Length > 0)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
}
}
@@ -121,13 +121,14 @@ public class UpdateAlbumCoverCommandHandler : ICommandHandler<UpdateAlbumCoverCo
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault();
string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName)
string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName, existingAlbum.ArtistId)
?? (existingAlbum.ReleaseTypes.Count > 0 ? existingAlbum.ReleaseTypes[0].ReleaseType.ToString() : null);
Result<string> storeArtworkResult = await _musicArtworkService.SaveAlbumArtworkAsync(
existingAlbum.LibraryId,
existingAlbum.Id,
libraryName,
existingAlbum.ArtistId,
artistName,
existingAlbum.Title,
command.Cover!,
@@ -164,19 +165,21 @@ public class UpdateAlbumCoverCommandHandler : ICommandHandler<UpdateAlbumCoverCo
/// </summary>
/// <param name="coverRelativePath">The relative path of the existing cover image of the album, or <see langword="null"/> when the album has no cover.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="artistId">The Id of the artist of the album.</param>
/// <returns>The name of the on-disk release type directory, or <see langword="null"/> when the album does not use one.</returns>
private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName)
private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName, Guid artistId)
{
if (string.IsNullOrWhiteSpace(coverRelativePath))
return null;
// The path is media/music/{library}/{artist}[/{releaseType}]/{album}/{file}, so the segment right before the album directory is the release
// type directory when the album uses one, and the artist directory otherwise. An artist whose name happens to match a release type, like
// "Live", must not be mistaken for one, so the segment is only accepted as a release type when it is not the directory of the artist.
// The path is media/music/{libraryName}-{libraryId}/{artistName}-{artistId}[/{releaseType}]/{albumTitle}-{albumId}/{file}, so the segment
// right before the album directory is the release type directory when the album uses one, and the artist directory otherwise. An artist
// whose name happens to match a release type, like "Live", must not be mistaken for one, so the segment is only accepted as a release type
// when it is not the directory of the artist.
string[] segments = coverRelativePath.Split(_pathService.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 3)
return null;
string candidate = segments[^3];
if (IsArtistDirectory(candidate, artistName))
if (IsArtistDirectory(candidate, artistName, artistId))
return null;
return Enum.TryParse(candidate, ignoreCase: true, out MusicReleaseType releaseType) && Enum.IsDefined(releaseType) ? candidate : null;
}
@@ -186,12 +189,12 @@ public class UpdateAlbumCoverCommandHandler : ICommandHandler<UpdateAlbumCoverCo
/// </summary>
/// <param name="pathSegment">The path segment to be checked.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="artistId">The Id of the artist of the album.</param>
/// <returns><see langword="true"/> when the segment is the artwork directory of the artist, <see langword="false"/> otherwise.</returns>
private bool IsArtistDirectory(string pathSegment, string artistName)
private bool IsArtistDirectory(string pathSegment, string artistName, Guid artistId)
{
if (string.IsNullOrWhiteSpace(artistName))
return false;
Result<PathSegment> artistSegmentResult = _pathService.SanitizeSegment(artistName);
string resolvedArtistName = string.IsNullOrWhiteSpace(artistName) ? "Unknown" : artistName;
Result<PathSegment> artistSegmentResult = _pathService.SanitizeCompositeSegment(resolvedArtistName, artistId.ToString());
return artistSegmentResult.IsSuccess
&& string.Equals(pathSegment, artistSegmentResult.Value.Name, StringComparison.OrdinalIgnoreCase);
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
/// <summary>
/// Query for getting the deleted albums of a media library.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library whose deleted albums are retrieved, taken from the route.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetDeletedAlbumsQuery(
string? LibraryId
) : IQuery;
@@ -0,0 +1,95 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
/// <summary>
/// Handler for the query to get the deleted albums of a media library.
/// </summary>
public class GetDeletedAlbumsQueryHandler : IQueryHandler<GetDeletedAlbumsQuery, Result<IReadOnlyList<DeletedAlbumResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetDeletedAlbumsQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedAlbumsQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</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 GetDeletedAlbumsQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetDeletedAlbumsQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the deleted albums of a media library.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the deleted albums, or an error.</returns>
public async Task<Result<IReadOnlyList<DeletedAlbumResponse>>> HandleAsync(GetDeletedAlbumsQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the library id of the route is a non-empty Guid before this point.
Guid libraryId = Guid.Parse(query.LibraryId!);
// Admins can see all libraries; for everyone else, only the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<AlbumEntity>> getDeletedAlbumsResult = await _unitOfWork.AlbumRepository.GetSoftDeletedByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getDeletedAlbumsResult.IsFailure)
return getDeletedAlbumsResult.Errors;
IReadOnlyList<AlbumEntity> deletedAlbums = getDeletedAlbumsResult.Value;
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository
.GetByOwnersAsync(MusicArtworkOwnerType.Album, [.. deletedAlbums.Select(album => album.Id)], cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
// A cover row can exist before its file is resolved, so rows without a stored file name are skipped instead of hiding a resolved cover.
Dictionary<Guid, string> coverPaths = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover && !string.IsNullOrWhiteSpace(artwork.FileName))
.GroupBy(artwork => artwork.OwnerId)
.ToDictionary(group => group.Key, group => group.Select(artwork => artwork.FileName!).First());
return Result.From<IReadOnlyList<DeletedAlbumResponse>>(
[.. deletedAlbums.Select(album => album.ToResponse(album.DeletedOnUtc ?? album.CreatedOnUtc, coverPaths.GetValueOrDefault(album.Id)))]);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
/// <summary>
/// Validates the needed validation rules for <see cref="GetDeletedAlbumsQuery"/>.
/// </summary>
public class GetDeletedAlbumsQueryValidator : AbstractValidator<GetDeletedAlbumsQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedAlbumsQueryValidator"/> class.
/// </summary>
public GetDeletedAlbumsQueryValidator()
{
// Validates the identifier of the media library whose deleted albums are retrieved, taken from the route.
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -7,7 +7,6 @@ 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;
@@ -25,7 +24,6 @@ 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;
@@ -34,14 +32,12 @@ 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, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteArtistCommand> validator)
public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteArtistCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
@@ -96,13 +92,9 @@ 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);
// The artist is soft deleted, so its metadata, artwork and paths stay available until the user restores it or the files disappear from disk.
// Keeping the row is also what makes the deletion survive an automatic scan, because the scan treats its track paths as already catalogued.
Result<Updated> deleteArtistResult = await _unitOfWork.ArtistRepository.SoftDeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistResult.IsFailure)
return deleteArtistResult.Errors;
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
/// <summary>
/// Command for restoring a deleted artist by its Id.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this artist belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist to restore, taken from the route.</param>
[DebuggerDisplay("ArtistId: {ArtistId}")]
public record RestoreArtistCommand(
string? LibraryId,
string? ArtistId
) : ICommand;
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
/// <summary>
/// Handler for the command to restore a deleted artist by its Id.
/// </summary>
public class RestoreArtistCommandHandler : ICommandHandler<RestoreArtistCommand, Result<Updated>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<RestoreArtistCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreArtistCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</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 RestoreArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<RestoreArtistCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to restore a deleted artist by its Id.
/// </summary>
/// <param name="command">The command to be handled.</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>> HandleAsync(RestoreArtistCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetSoftDeletedByIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
if (getArtistResult.Value is null)
return DomainErrors.Music.ArtistNotFound;
ArtistEntity existingArtist = getArtistResult.Value;
// Resource scoping: the artist must belong to the library named by the route, so that an artist can never be restored through another
// library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library.
if (existingArtist.LibraryId != libraryId)
return DomainErrors.Music.ArtistNotFound;
// Admins can restore the artists of all libraries; for everyone else, only the artists of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// The name of a visible artist is unique within a library, so an artist can only be restored while no visible artist took over its name.
// The lookup only considers visible artists, so it can never return the deleted artist itself.
Result<ArtistEntity?> getArtistByNameResult = await _unitOfWork.ArtistRepository.GetByNameAsync(existingArtist.LibraryId, existingArtist.Name, cancellationToken).ConfigureAwait(false);
if (getArtistByNameResult.IsFailure)
return getArtistByNameResult.Errors;
if (getArtistByNameResult.Value is not null)
return DomainErrors.Music.ArtistAlreadyExists;
Result<Updated> restoreArtistResult = await _unitOfWork.ArtistRepository.RestoreSoftDeletedByIdAsync(existingArtist.Id, cancellationToken).ConfigureAwait(false);
if (restoreArtistResult.IsFailure)
return restoreArtistResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Updated;
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
/// <summary>
/// Validates the needed validation rules for <see cref="RestoreArtistCommand"/>.
/// </summary>
public class RestoreArtistCommandValidator : AbstractValidator<RestoreArtistCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RestoreArtistCommandValidator"/> class.
/// </summary>
public RestoreArtistCommandValidator()
{
// Validates the identifier of the media library that owns the artist, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the deleted artist, taken from the route.
RuleFor(command => command.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
RuleFor(command => command.ArtistId)
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
}
}
@@ -113,6 +113,7 @@ public class UpdateArtistCoverCommandHandler : ICommandHandler<UpdateArtistCover
Result<string> storeArtworkResult = await _musicArtworkService.SaveArtistArtworkAsync(
existingArtist.LibraryId,
libraryName,
existingArtist.Id,
existingArtist.Name,
command.Cover!,
command.FileName!,
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
/// <summary>
/// Query for getting the deleted artists of a media library.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library whose deleted artists are retrieved, taken from the route.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetDeletedArtistsQuery(
string? LibraryId
) : IQuery;
@@ -0,0 +1,95 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
/// <summary>
/// Handler for the query to get the deleted artists of a media library.
/// </summary>
public class GetDeletedArtistsQueryHandler : IQueryHandler<GetDeletedArtistsQuery, Result<IReadOnlyList<DeletedArtistResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetDeletedArtistsQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedArtistsQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</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 GetDeletedArtistsQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetDeletedArtistsQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the deleted artists of a media library.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the deleted artists, or an error.</returns>
public async Task<Result<IReadOnlyList<DeletedArtistResponse>>> HandleAsync(GetDeletedArtistsQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the library id of the route is a non-empty Guid before this point.
Guid libraryId = Guid.Parse(query.LibraryId!);
// Admins can see all libraries; for everyone else, only the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<ArtistEntity>> getDeletedArtistsResult = await _unitOfWork.ArtistRepository.GetSoftDeletedByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getDeletedArtistsResult.IsFailure)
return getDeletedArtistsResult.Errors;
IReadOnlyList<ArtistEntity> deletedArtists = getDeletedArtistsResult.Value;
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository
.GetByOwnersAsync(MusicArtworkOwnerType.Artist, [.. deletedArtists.Select(artist => artist.Id)], cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
// A cover row can exist before its file is resolved, so rows without a stored file name are skipped instead of hiding a resolved cover.
Dictionary<Guid, string> coverPaths = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover && !string.IsNullOrWhiteSpace(artwork.FileName))
.GroupBy(artwork => artwork.OwnerId)
.ToDictionary(group => group.Key, group => group.Select(artwork => artwork.FileName!).First());
return Result.From<IReadOnlyList<DeletedArtistResponse>>(
[.. deletedArtists.Select(artist => artist.ToResponse(artist.DeletedOnUtc ?? artist.CreatedOnUtc, coverPaths.GetValueOrDefault(artist.Id)))]);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
/// <summary>
/// Validates the needed validation rules for <see cref="GetDeletedArtistsQuery"/>.
/// </summary>
public class GetDeletedArtistsQueryValidator : AbstractValidator<GetDeletedArtistsQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedArtistsQueryValidator"/> class.
/// </summary>
public GetDeletedArtistsQueryValidator()
{
// Validates the identifier of the media library whose deleted artists are retrieved, taken from the route.
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,38 +0,0 @@
#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);
}
@@ -20,13 +20,14 @@ public interface IMusicArtworkService
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist of the album.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <param name="artwork">The artwork to store.</param>
/// <param name="releaseTypeName">The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When <see langword="null"/>, no release type segment is added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken);
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken);
/// <summary>
/// Stores the uploaded <paramref name="artwork"/> of the album into the internal media directory, and returns the relative path of the stored artwork.
@@ -34,6 +35,7 @@ public interface IMusicArtworkService
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist of the album.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
@@ -41,7 +43,7 @@ public interface IMusicArtworkService
/// <param name="releaseTypeName">The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When <see langword="null"/>, no release type segment is added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken);
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken);
/// <summary>
/// Deletes the stored artwork of the album from the internal media directory.
@@ -49,43 +51,47 @@ public interface IMusicArtworkService
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist of the album.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <param name="releaseTypeName">The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Result<Deleted> DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null);
Result<Deleted> DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, string? releaseTypeName = null);
/// <summary>
/// Stores the <paramref name="artwork"/> of the artist into the internal media directory, and returns the relative path of the stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="artistName">The name of the artist.</param>
/// <param name="artwork">The artwork to store.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken);
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, Guid artistId, string artistName, ArtworkDto artwork, CancellationToken cancellationToken);
/// <summary>
/// Stores the uploaded <paramref name="artwork"/> of the artist into the internal media directory, and returns the relative path of the stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="artistName">The name of the artist.</param>
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
/// <param name="fileName">The name of the uploaded artwork file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken);
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, Guid artistId, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken);
/// <summary>
/// Deletes the stored artwork of the artist from the internal media directory.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="artistName">The name of the artist.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Result<Deleted> DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName);
Result<Deleted> DeleteArtistArtwork(Guid libraryId, string libraryName, Guid artistId, string artistName);
/// <summary>
/// Deletes the stored artwork file at <paramref name="artworkRelativePath"/> from the internal media directory, when it still exists.
@@ -1,119 +0,0 @@
#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);
}
}
@@ -7,14 +7,9 @@ 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.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;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -29,7 +24,6 @@ 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;
@@ -38,14 +32,12 @@ 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, IMusicArtworkCleanupService musicArtworkCleanupService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteTrackCommand> validator)
public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteTrackCommand> validator)
{
_unitOfWork = unitOfWork;
_musicArtworkCleanupService = musicArtworkCleanupService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
@@ -75,9 +67,9 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
Guid albumId = Guid.Parse(command.AlbumId!);
Guid trackId = Guid.Parse(command.TrackId!);
// A track is a child of the artist aggregate, so the whole aggregate is loaded and the track is removed within it.
// Only the library of the artist is needed to scope the delete, so the artist row is read without its aggregate graph and without tracking.
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository
.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
if (getArtistResult.Value is null)
@@ -95,13 +87,6 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
if (existingAlbum is null)
return DomainErrors.Music.AlbumNotFound;
TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == trackId);
if (existingTrack is null)
return DomainErrors.Music.TrackNotFound;
// A track can only belong to a library that exists, so a client can never delete a track of a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository
.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -110,31 +95,25 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// The write path goes through the aggregate root: a track is a child entity of the artist aggregate, unlike Book and Artist,
// which are aggregate roots and are deleted directly through their own repositories. This difference is intentional.
Result<Artist> artistResult = existingArtist.ToDomainEntity();
if (artistResult.IsFailure)
return artistResult.Errors;
// The album and the track are entities inside the artist aggregate, so they are referenced by object, not by id; the aggregate members are located here and passed through.
Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId);
if (domainAlbum is null)
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository
.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null || getAlbumResult.Value.ArtistId != artistId || getAlbumResult.Value.LibraryId != libraryId)
return DomainErrors.Music.AlbumNotFound;
Track? domainTrack = domainAlbum.Tracks.FirstOrDefault(track => track.Id.Value == trackId);
if (domainTrack is null)
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository
.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null || getTrackResult.Value.AlbumId != albumId || getTrackResult.Value.LibraryId != libraryId)
return DomainErrors.Music.TrackNotFound;
Result<Deleted> removeTrackResult = artistResult.Value.RemoveTrackFromAlbum(domainAlbum, domainTrack);
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;
// The track is soft deleted, so its metadata, artwork and path stay available until the user restores it or the file disappears from disk.
// Keeping the row is also what makes the deletion survive an automatic scan, because the scan treats its path as already catalogued.
Result<Updated> deleteTrackResult = await _unitOfWork.TrackRepository.SoftDeleteByIdAsync(trackId, cancellationToken).ConfigureAwait(false);
if (deleteTrackResult.IsFailure)
return deleteTrackResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
/// <summary>
/// Command for restoring a deleted track by its Id.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this track belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist the album of the track belongs to, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route.</param>
/// <param name="TrackId">The unique identifier of the track to restore, taken from the route.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record RestoreTrackCommand(
string? LibraryId,
string? ArtistId,
string? AlbumId,
string? TrackId
) : ICommand;
@@ -0,0 +1,106 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
/// <summary>
/// Handler for the command to restore a deleted track by its Id.
/// </summary>
public class RestoreTrackCommandHandler : ICommandHandler<RestoreTrackCommand, Result<Updated>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<RestoreTrackCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreTrackCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</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 RestoreTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<RestoreTrackCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to restore a deleted track by its Id.
/// </summary>
/// <param name="command">The command to be handled.</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>> HandleAsync(RestoreTrackCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
Guid trackId = Guid.Parse(command.TrackId!);
// A deleted track whose album or artist is also deleted is not restorable on its own, so the repository reports it as missing until
// the album and the artist are restored.
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetSoftDeletedByIdAsync(trackId, cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null)
return DomainErrors.Music.TrackNotFound;
TrackEntity existingTrack = getTrackResult.Value;
// Resource scoping: the track must belong to the album, the artist and the library named by the route, so that a track can never be
// restored through another library's route; the mismatch is reported as not found, without disclosing that the track exists elsewhere.
if (existingTrack.LibraryId != libraryId || existingTrack.AlbumId != albumId)
return DomainErrors.Music.TrackNotFound;
// Admins can restore the tracks of all libraries; for everyone else, only the tracks of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingTrack.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository
.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null || getAlbumResult.Value.ArtistId != artistId)
return DomainErrors.Music.TrackNotFound;
Result<Updated> restoreTrackResult = await _unitOfWork.TrackRepository.RestoreSoftDeletedByIdAsync(existingTrack.Id, cancellationToken).ConfigureAwait(false);
if (restoreTrackResult.IsFailure)
return restoreTrackResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Updated;
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
/// <summary>
/// Validates the needed validation rules for <see cref="RestoreTrackCommand"/>.
/// </summary>
public class RestoreTrackCommandValidator : AbstractValidator<RestoreTrackCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RestoreTrackCommandValidator"/> class.
/// </summary>
public RestoreTrackCommandValidator()
{
// Validates the identifier of the media library that owns the track, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the artist the album of the track belongs to, taken from the route.
RuleFor(command => command.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
RuleFor(command => command.ArtistId)
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
// Validates the identifier of the album the track belongs to, taken from the route.
RuleFor(command => command.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
RuleFor(command => command.AlbumId)
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
.When(command => command.AlbumId is not null && command.AlbumId.Length > 0)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
// Validates the identifier of the deleted track, taken from the route.
RuleFor(command => command.TrackId)
.NotEmpty()
.WithError(Errors.Music.TrackIdCannotBeEmpty);
RuleFor(command => command.TrackId)
.Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty)
.When(command => command.TrackId is not null && command.TrackId.Length > 0)
.WithError(Errors.Music.TrackIdCannotBeEmpty);
}
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
/// <summary>
/// Query for getting the deleted tracks of a media library.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library whose deleted tracks are retrieved, taken from the route.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetDeletedTracksQuery(
string? LibraryId
) : IQuery;
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
/// <summary>
/// Handler for the query to get the deleted tracks of a media library.
/// </summary>
public class GetDeletedTracksQueryHandler : IQueryHandler<GetDeletedTracksQuery, Result<IReadOnlyList<DeletedTrackResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetDeletedTracksQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedTracksQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</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 GetDeletedTracksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetDeletedTracksQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the deleted tracks of a media library.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the deleted tracks, or an error.</returns>
public async Task<Result<IReadOnlyList<DeletedTrackResponse>>> HandleAsync(GetDeletedTracksQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the library id of the route is a non-empty Guid before this point.
Guid libraryId = Guid.Parse(query.LibraryId!);
// Admins can see all libraries; for everyone else, only the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<TrackEntity>> getDeletedTracksResult = await _unitOfWork.TrackRepository.GetSoftDeletedByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getDeletedTracksResult.IsFailure)
return getDeletedTracksResult.Errors;
return Result.From<IReadOnlyList<DeletedTrackResponse>>(
[.. getDeletedTracksResult.Value.Select(track => track.ToResponse(track.DeletedOnUtc ?? track.CreatedOnUtc))]);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
/// <summary>
/// Validates the needed validation rules for <see cref="GetDeletedTracksQuery"/>.
/// </summary>
public class GetDeletedTracksQueryValidator : AbstractValidator<GetDeletedTracksQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedTracksQueryValidator"/> class.
/// </summary>
public GetDeletedTracksQueryValidator()
{
// Validates the identifier of the media library whose deleted tracks are retrieved, taken from the route.
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,9 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -20,6 +22,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Deletion;
internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMusicArtworkService _musicArtworkService;
private readonly ILogger<MusicMediaLibraryItemDeletionStrategy> _logger;
/// <summary>
/// The media library type that this deletion strategy supports.
@@ -30,9 +34,13 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
/// 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)
/// <param name="musicArtworkService">Injected service for deleting the stored artwork files of the music library items.</param>
/// <param name="logger">Injected logger used to report the issues encountered while deleting the media library item.</param>
public MusicMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, ILogger<MusicMediaLibraryItemDeletionStrategy> logger)
{
_unitOfWork = unitOfWork;
_musicArtworkService = musicArtworkService;
_logger = logger;
}
/// <summary>
@@ -46,6 +54,7 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
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.
// Soft deleted tracks are included on purpose: when their file disappears from disk, they must be removed permanently too.
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByPathAsync(libraryId, path, cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
@@ -57,7 +66,7 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
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);
Result<Deleted> deleteTrackArtworkResult = await DeleteStoredArtworkAndRowsAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken).ConfigureAwait(false);
if (deleteTrackArtworkResult.IsFailure)
return deleteTrackArtworkResult.Errors;
@@ -65,8 +74,8 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
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);
// Load the album the deleted track belonged to, whether the album itself is soft deleted or not, to determine whether it is left with no children.
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetIncludingDeletedByIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
AlbumEntity? album = getAlbumResult.Value;
@@ -75,13 +84,14 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
Guid artistId = album.ArtistId;
Result<IReadOnlyList<TrackEntity>> getRemainingTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false);
// Soft deleted tracks are counted as well, because their files still exist and the album must survive until the last one of them disappears.
Result<IReadOnlyList<TrackEntity>> getRemainingTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdIncludingDeletedAsync(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);
Result<Deleted> deleteAlbumArtworkResult = await DeleteStoredArtworkAndRowsAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
if (deleteAlbumArtworkResult.IsFailure)
return deleteAlbumArtworkResult.Errors;
@@ -89,13 +99,14 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
if (deleteAlbumResult.IsFailure)
return deleteAlbumResult.Errors;
Result<IReadOnlyList<AlbumEntity>> getRemainingAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false);
// Soft deleted albums are counted as well, because their tracks still exist and the artist must survive until the last one of them disappears.
Result<IReadOnlyList<AlbumEntity>> getRemainingAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdIncludingDeletedAsync(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);
Result<Deleted> deleteArtistArtworkResult = await DeleteStoredArtworkAndRowsAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistArtworkResult.IsFailure)
return deleteArtistArtworkResult.Errors;
@@ -108,6 +119,35 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
return await SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the stored artwork files of the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>,
/// and then deletes the artwork rows of that item.
/// </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="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>> DeleteStoredArtworkAndRowsAsync(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 are deleted best-effort, since a missing or locked file must not prevent the permanent removal of the media library item.
foreach (MusicArtworkEntity artwork in getArtworkResult.Value)
{
if (string.IsNullOrWhiteSpace(artwork.FileName))
continue;
Result<Deleted> deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName);
if (deleteStoredArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored {OwnerType} artwork at '{ArtworkPath}' of the music library item with Id '{OwnerId}', the file might remain orphaned.", ownerType, artwork.FileName, ownerId);
}
return await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Persists the changes made to the storage medium.
/// </summary>
@@ -78,7 +78,7 @@ public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDelet
// 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}");
Result<PathSegment> librarySegmentResult = _pathService.SanitizeCompositeSegment(domainEvent.Library.Title, libraryId.ToString());
if (librarySegmentResult.IsFailure)
throw new EventualConsistencyException(librarySegmentResult.FirstError, librarySegmentResult.Errors);
DeleteLibraryDirectory(_mediaSettingsModel.BooksDirectory, librarySegmentResult.Value.Name);