Refactors the book, artist, and album slices across the stack

This commit is contained in:
BinaryAlley committed 2026-09-17 13:30:48 -07:00
1 parent 8aaf9fe64e
commit ea6eb9f796
439 files changed
+28235 -3156

No files matched your search

@@ -0,0 +1,44 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
/// <summary>
/// Command for adding an album to an artist.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this album belongs to, taken from the route.</param>
/// <param name="ArtistId">The Id of the artist the album belongs to, taken from the route.</param>
/// <param name="Metadata">The album metadata of the album.</param>
/// <param name="MediaFormat">The physical or digital medium of the album, if applicable.</param>
/// <param name="Barcode">The barcode of the album, if applicable.</param>
/// <param name="CatalogNumber">The catalog number of the album, if applicable.</param>
/// <param name="MusicBrainzReleaseId">The MusicBrainz identifier of the release, if applicable.</param>
/// <param name="MusicBrainzReleaseGroupId">The MusicBrainz identifier of the release group, if applicable.</param>
/// <param name="MusicBrainzReleaseArtistId">The MusicBrainz identifier of the release artist, if applicable.</param>
/// <param name="Contributors">The list of media contributors that performed on the album.</param>
/// <param name="Ratings">The list of ratings for this album.</param>
/// <param name="Tracks">The list of tracks of the album.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record AddAlbumCommand(
string? LibraryId,
string? ArtistId,
AlbumMetadataDto? Metadata,
MusicMediaFormat? MediaFormat,
string? Barcode,
string? CatalogNumber,
Guid? MusicBrainzReleaseId,
Guid? MusicBrainzReleaseGroupId,
Guid? MusicBrainzReleaseArtistId,
List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings,
List<AddTrackCommand>? Tracks
) : ICommand;
@@ -0,0 +1,193 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using System;
using System.Collections.Generic;
using System.Linq;
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.AddAlbum;
/// <summary>
/// Handler for the command to add an album to an artist.
/// </summary>
public class AddAlbumCommandHandler : ICommandHandler<AddAlbumCommand, Result<AlbumResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<AddAlbumCommand> _validator;
private readonly IPathService _pathService;
/// <summary>
/// Initializes a new instance of the <see cref="AddAlbumCommandHandler"/> 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>
/// <param name="pathService">Injected service for file system path related functionality.</param>
public AddAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<AddAlbumCommand> validator, IPathService pathService)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
_pathService = pathService;
}
/// <summary>
/// Handles the command to add an album to an artist.
/// </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}"/> containing either a successfully created <see cref="AlbumResponse"/>, or an error message.
/// </returns>
public async Task<Result<AlbumResponse>> HandleAsync(AddAlbumCommand 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!);
// Admins can add albums to the artists of all libraries; for everyone else, only to the artists of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// An album can only belong to a library that exists, so a client can never register an entry that points to a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: 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 album must belong to an artist of the library named by the route, so that an album can never be added 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;
// An album's tracks are only readable if they are stored inside one of the content locations of their library, so a client can never
// register an entry that points the reading pipeline at an arbitrary file of the host.
if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command))
return DomainErrors.Music.TrackPathMustBeWithinLibraryContentLocations;
// Media contributors are referenced by Id and are never created implicitly by adding an album, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
Result<Album> createAlbumResult = command.ToDomainEntity();
if (createAlbumResult.IsFailure)
return createAlbumResult.Errors;
AlbumEntity persistenceAlbum = createAlbumResult.Value.ToRepositoryEntity(artistId, libraryId);
Result<Created> insertAlbumResult = await _unitOfWork.AlbumRepository.InsertAsync(persistenceAlbum, cancellationToken).ConfigureAwait(false);
if (insertAlbumResult.IsFailure)
return insertAlbumResult.Errors;
// The pre-insert checks handle the common cases; a concurrent request could still persist an album with the same identity between them
// and the save, in which case the persistence medium reports the unique constraint violation as a conflict.
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Returns the album as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the database applied on save.
Result<AlbumEntity?> getPersistedAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(createAlbumResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedAlbumResult.IsFailure)
return getPersistedAlbumResult.Errors;
if (getPersistedAlbumResult.Value is null)
return DomainErrors.Music.AlbumNotFound;
return getPersistedAlbumResult.Value.ToResponse();
}
/// <summary>
/// Determines whether every track path referenced by <paramref name="command"/> is stored inside one of the content locations of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library that owns the album.</param>
/// <param name="command">The command carrying the referenced tracks.</param>
/// <returns><see langword="true"/> when every referenced track path is within a content location of the library; otherwise, <see langword="false"/>.</returns>
private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, AddAlbumCommand command)
{
foreach (AddTrackCommand track in command.Tracks!)
if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path!, contentLocation.Path)))
return false;
return true;
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(AddAlbumCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. CollectContributorIds(command).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return DomainErrors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
/// <summary>
/// Collects the unique identifiers of every media contributor referenced by <paramref name="command"/>, be it directly on the album,
/// or indirectly through one of its tracks.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <returns>The collected media contributor identifiers.</returns>
private static IEnumerable<Guid> CollectContributorIds(AddAlbumCommand command)
{
foreach (MediaContributorReferenceDto contributor in command.Contributors!)
yield return contributor.ContributorId;
foreach (AddTrackCommand track in command.Tracks!)
foreach (MediaContributorReferenceDto contributor in track.Contributors!)
yield return contributor.ContributorId;
}
}
@@ -0,0 +1,510 @@
#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.AddAlbum;
/// <summary>
/// Validates the needed validation rules for <see cref="AddAlbumCommand"/>.
/// </summary>
public class AddAlbumCommandValidator : AbstractValidator<AddAlbumCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddAlbumCommandValidator"/> class.
/// </summary>
public AddAlbumCommandValidator()
{
// 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 is added 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 metadata of the album: title, lengths, release type and status, disc and track counts, release information, languages, genres and tags.
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Music.AlbumTitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
metadata.RuleFor(m => m!.ReleaseType)
.IsInEnum()
.When(m => m!.ReleaseType is not null)
.WithError(Errors.Music.UnknownMusicReleaseType);
metadata.RuleFor(m => m!.ReleaseStatus)
.IsInEnum()
.When(m => m!.ReleaseStatus is not null)
.WithError(Errors.Music.UnknownMusicReleaseStatus);
metadata.RuleFor(m => m!.TotalDiscs)
.GreaterThan(0)
.When(m => m!.TotalDiscs.HasValue)
.WithError(Errors.Music.TotalDiscsMustBeGreaterThanZero);
metadata.RuleFor(m => m!.TotalTracks)
.GreaterThan(0)
.When(m => m!.TotalTracks.HasValue)
.WithError(Errors.Music.TotalTracksMustBeGreaterThanZero);
metadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
metadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
metadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
metadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
});
// Validates the physical characteristics of the album: format and catalog number.
RuleFor(command => command.MediaFormat)
.IsInEnum()
.When(command => command.MediaFormat is not null)
.WithError(Errors.Music.UnknownMusicMediaFormat);
RuleFor(command => command.CatalogNumber)
.MaximumLength(50)
.When(command => command.CatalogNumber is not null)
.WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong);
RuleFor(command => command.MusicBrainzReleaseId)
.Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty)
.When(command => command.MusicBrainzReleaseId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
RuleFor(command => command.MusicBrainzReleaseGroupId)
.Must(musicBrainzReleaseGroupId => musicBrainzReleaseGroupId != Guid.Empty)
.When(command => command.MusicBrainzReleaseGroupId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
RuleFor(command => command.MusicBrainzReleaseArtistId)
.Must(musicBrainzReleaseArtistId => musicBrainzReleaseArtistId != Guid.Empty)
.When(command => command.MusicBrainzReleaseArtistId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the ratings of the album.
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
RuleForEach(command => command.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
// Validates the media contributors that performed on the album.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the tracks of the album.
RuleFor(command => command.Tracks)
.NotNull()
.WithError(Errors.Music.TracksListCannotBeNull);
RuleForEach(command => command.Tracks)
.ChildRules(track =>
{
// Validates the file system path of the track.
track.RuleFor(t => t!.Path)
.NotEmpty()
.WithError(Errors.Music.TrackPathCannotBeEmpty)
.MaximumLength(2048)
.WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong);
// Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags.
track.RuleFor(t => t!.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(trackMetadata =>
{
trackMetadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
trackMetadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
trackMetadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
});
// Validates the ordering and performance characteristics of the track.
track.RuleFor(t => t!.TrackNumber)
.GreaterThan(0)
.When(t => t!.TrackNumber.HasValue)
.WithError(Errors.Music.TrackNumberMustBeGreaterThanZero);
track.RuleFor(t => t!.DiscNumber)
.GreaterThan(0)
.When(t => t!.DiscNumber.HasValue)
.WithError(Errors.Music.DiscNumberMustBeGreaterThanZero);
track.RuleFor(t => t!.Script)
.MaximumLength(50)
.When(t => t!.Script is not null)
.WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong);
track.RuleFor(t => t!.Key)
.IsInEnum()
.When(t => t!.Key is not null)
.WithError(Errors.Music.UnknownMusicKey);
track.RuleFor(t => t!.Bpm)
.GreaterThan(0)
.When(t => t!.Bpm.HasValue)
.WithError(Errors.Music.BpmMustBeGreaterThanZero);
track.RuleFor(t => t!.Work)
.MaximumLength(255)
.When(t => t!.Work is not null)
.WithError(Errors.Music.WorkMustBeMaximum255CharactersLong);
// Validates the media contributors that performed on the track.
track.RuleFor(t => t!.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
track.RuleForEach(t => t!.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the moods and the ISRC codes of the track.
track.RuleForEach(t => t!.Moods)
.ChildRules(mood =>
mood.RuleFor(m => m.Name)
.NotEmpty()
.WithError(Errors.Metadata.MoodNameCannotBeEmpty));
track.RuleForEach(t => t!.Isrcs)
.ChildRules(isrc =>
isrc.RuleFor(i => i.Value)
.NotEmpty()
.WithError(Errors.Music.IsrcValueCannotBeEmpty));
// Validates the ratings of the track.
track.RuleFor(t => t!.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
track.RuleForEach(t => t!.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
});
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
/// <summary>
/// Command for deleting an album by its Id.
/// </summary>
/// <param name="AlbumId">The unique identifier of the album to delete.</param>
[DebuggerDisplay("AlbumId: {AlbumId}")]
public record DeleteAlbumCommand(
Guid AlbumId
) : ICommand;
@@ -0,0 +1,84 @@
#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.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
/// <summary>
/// Handler for the command to delete an album by its Id.
/// </summary>
public class DeleteAlbumCommandHandler : ICommandHandler<DeleteAlbumCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteAlbumCommand> _validator;
/// <summary>
/// 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="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteAlbumCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete an 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<Deleted>> HandleAsync(DeleteAlbumCommand 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;
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(command.AlbumId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return Errors.Music.AlbumNotFound;
// Admins can delete 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(getAlbumResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<Deleted> deleteAlbumResult = await _unitOfWork.AlbumRepository.DeleteByIdAsync(command.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;
return deleteAlbumResult;
}
}
@@ -0,0 +1,26 @@
#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.DeleteAlbum;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteAlbumCommand"/>.
/// </summary>
public class DeleteAlbumCommandValidator : AbstractValidator<DeleteAlbumCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteAlbumCommandValidator"/> class.
/// </summary>
public DeleteAlbumCommandValidator()
{
RuleFor(command => command.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty)
.Must(albumId => albumId != Guid.Empty)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
/// <summary>
/// Command for updating an album.
/// </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 this album belongs to, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album, taken from the route.</param>
/// <param name="Metadata">The album metadata of the album.</param>
/// <param name="MediaFormat">The physical or digital medium of the album, if applicable.</param>
/// <param name="Barcode">The barcode of the album, if applicable.</param>
/// <param name="CatalogNumber">The catalog number of the album, if applicable.</param>
/// <param name="MusicBrainzReleaseId">The MusicBrainz identifier of the release, if applicable.</param>
/// <param name="MusicBrainzReleaseGroupId">The MusicBrainz identifier of the release group, if applicable.</param>
/// <param name="MusicBrainzReleaseArtistId">The MusicBrainz identifier of the release artist, if applicable.</param>
/// <param name="Contributors">The list of media contributors that performed on the album.</param>
/// <param name="Ratings">The list of ratings for this album.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateAlbumCommand(
string? LibraryId,
string? ArtistId,
string? AlbumId,
AlbumMetadataDto? Metadata,
MusicMediaFormat? MediaFormat,
string? Barcode,
string? CatalogNumber,
Guid? MusicBrainzReleaseId,
Guid? MusicBrainzReleaseGroupId,
Guid? MusicBrainzReleaseArtistId,
List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings
) : ICommand;
@@ -0,0 +1,171 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
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.Commands.UpdateAlbum;
/// <summary>
/// Handler for the command to update an album.
/// </summary>
public class UpdateAlbumCommandHandler : ICommandHandler<UpdateAlbumCommand, Result<AlbumResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateAlbumCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCommandHandler"/> 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 UpdateAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateAlbumCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update an album.
/// </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}"/> containing either a successfully updated <see cref="AlbumResponse"/>, or an error message.
/// </returns>
public async Task<Result<AlbumResponse>> HandleAsync(UpdateAlbumCommand 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!);
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return Errors.Music.AlbumNotFound;
AlbumEntity existingAlbum = getAlbumResult.Value;
// Resource scoping: the album must belong to the library and the artist named by the route, so that an album can never be edited
// through another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere.
if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
return Errors.Music.AlbumNotFound;
// Admins can update 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;
// An album can only belong to a library that exists, so a client can never update 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);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return Errors.Library.LibraryNotFound;
// Media contributors are referenced by Id and are never created implicitly by editing an album, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
Result<Album> updateAlbumResult = command.ToDomainEntity(existingAlbum);
if (updateAlbumResult.IsFailure)
return updateAlbumResult.Errors;
// Map the updated domain album onto a fresh repository entity, ready for the repository to replace the stored data.
AlbumEntity persistenceAlbum = updateAlbumResult.Value.ToRepositoryEntity(existingAlbum.ArtistId, existingAlbum.LibraryId);
Result<Updated> updateResult = await _unitOfWork.AlbumRepository.UpdateAsync(persistenceAlbum, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// The repository merges the fresh entity into the tracked stored album and the audit interceptor stamps the update columns, so the
// stored album carries the persisted values, including the audit ones.
return existingAlbum.ToResponse();
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(UpdateAlbumCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. CollectContributorIds(command).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return Errors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
/// <summary>
/// Collects the unique identifiers of every media contributor referenced by <paramref name="command"/>.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <returns>The collected media contributor identifiers.</returns>
private static IEnumerable<Guid> CollectContributorIds(UpdateAlbumCommand command)
{
foreach (MediaContributorReferenceDto contributor in command.Contributors!)
yield return contributor.ContributorId;
}
}
@@ -0,0 +1,278 @@
#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.UpdateAlbum;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateAlbumCommand"/>.
/// </summary>
public class UpdateAlbumCommandValidator : AbstractValidator<UpdateAlbumCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCommandValidator"/> class.
/// </summary>
public UpdateAlbumCommandValidator()
{
// 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 that owns the album, 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, 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 metadata of the album: title, lengths, release information, release type and status, disc and track counts, languages, genres and tags.
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Music.AlbumTitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
metadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
metadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
metadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
metadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.ReleaseType)
.IsInEnum()
.When(m => m!.ReleaseType is not null)
.WithError(Errors.Music.UnknownMusicReleaseType);
metadata.RuleFor(m => m!.ReleaseStatus)
.IsInEnum()
.When(m => m!.ReleaseStatus is not null)
.WithError(Errors.Music.UnknownMusicReleaseStatus);
metadata.RuleFor(m => m!.TotalDiscs)
.GreaterThan(0)
.When(m => m!.TotalDiscs.HasValue)
.WithError(Errors.Music.TotalDiscsMustBeGreaterThanZero);
metadata.RuleFor(m => m!.TotalTracks)
.GreaterThan(0)
.When(m => m!.TotalTracks.HasValue)
.WithError(Errors.Music.TotalTracksMustBeGreaterThanZero);
});
// Validates the physical characteristics of the album: format and catalog number.
RuleFor(command => command.MediaFormat)
.IsInEnum()
.When(command => command.MediaFormat is not null)
.WithError(Errors.Music.UnknownMusicMediaFormat);
RuleFor(command => command.CatalogNumber)
.MaximumLength(50)
.When(command => command.CatalogNumber is not null)
.WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong);
RuleFor(command => command.MusicBrainzReleaseId)
.Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty)
.When(command => command.MusicBrainzReleaseId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
RuleFor(command => command.MusicBrainzReleaseGroupId)
.Must(musicBrainzReleaseGroupId => musicBrainzReleaseGroupId != Guid.Empty)
.When(command => command.MusicBrainzReleaseGroupId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
RuleFor(command => command.MusicBrainzReleaseArtistId)
.Must(musicBrainzReleaseArtistId => musicBrainzReleaseArtistId != Guid.Empty)
.When(command => command.MusicBrainzReleaseArtistId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the media contributors that performed on the album.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the ratings of the album.
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
RuleForEach(command => command.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
/// <summary>
/// Query for getting an album by its Id.
/// </summary>
/// <param name="AlbumId">The unique identifier of the album to get.</param>
[DebuggerDisplay("AlbumId: {AlbumId}")]
public record GetAlbumQuery(
Guid AlbumId
) : IQuery;
@@ -0,0 +1,82 @@
#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;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
/// <summary>
/// Handler for the query to get an album by its Id.
/// </summary>
public class GetAlbumQueryHandler : IQueryHandler<GetAlbumQuery, Result<AlbumResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetAlbumQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumQueryHandler"/> 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 GetAlbumQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetAlbumQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get an album by its Id.
/// </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 a successfully retrieved <see cref="AlbumResponse"/>, or an error message.
/// </returns>
public async Task<Result<AlbumResponse>> HandleAsync(GetAlbumQuery 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;
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(query.AlbumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return Errors.Music.AlbumNotFound;
// Admins can see 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(getAlbumResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
return getAlbumResult.Value.ToResponse();
}
}
@@ -0,0 +1,26 @@
#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.GetAlbum;
/// <summary>
/// Validates the needed validation rules for <see cref="GetAlbumQuery"/>.
/// </summary>
public class GetAlbumQueryValidator : AbstractValidator<GetAlbumQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumQueryValidator"/> class.
/// </summary>
public GetAlbumQueryValidator()
{
RuleFor(query => query.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty)
.Must(albumId => albumId != Guid.Empty)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
/// <summary>
/// Query for getting all the tracks of an album.
/// </summary>
/// <param name="AlbumId">The unique identifier of the album whose tracks are retrieved.</param>
[DebuggerDisplay("AlbumId: {AlbumId}")]
public record GetAlbumTracksQuery(
Guid AlbumId
) : IQuery;
@@ -0,0 +1,83 @@
#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;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
/// <summary>
/// Handler for the query to get all the tracks of an album.
/// </summary>
public class GetAlbumTracksQueryHandler : IQueryHandler<GetAlbumTracksQuery, Result<IReadOnlyList<TrackResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetAlbumTracksQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumTracksQueryHandler"/> 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 GetAlbumTracksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetAlbumTracksQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get all the tracks of an album.
/// </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 a collection of <see cref="TrackResponse"/>, or an error message.
/// </returns>
public async Task<Result<IReadOnlyList<TrackResponse>>> HandleAsync(GetAlbumTracksQuery 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;
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(query.AlbumId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return Errors.Music.AlbumNotFound;
// Admins can see the tracks of the albums of all libraries; for everyone else, only of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getAlbumResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<TrackEntity>> getTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(query.AlbumId, cancellationToken).ConfigureAwait(false);
return getTracksResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -0,0 +1,26 @@
#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.GetAlbumTracks;
/// <summary>
/// Validates the needed validation rules for <see cref="GetAlbumTracksQuery"/>.
/// </summary>
public class GetAlbumTracksQueryValidator : AbstractValidator<GetAlbumTracksQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumTracksQueryValidator"/> class.
/// </summary>
public GetAlbumTracksQueryValidator()
{
RuleFor(query => query.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty)
.Must(albumId => albumId != Guid.Empty)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
}
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
/// <summary>
/// Query for getting the lightweight read models of all the tracks of an album.
/// </summary>
/// <param name="AlbumId">The unique identifier of the album whose tracks are retrieved.</param>
/// <param name="CurrentPage">The page of results to retrieve.</param>
/// <param name="PerPage">The maximum number of tracks to retrieve per page.</param>
[DebuggerDisplay("AlbumId: {AlbumId}")]
public record GetAlbumTracksLiteQuery(
Guid AlbumId,
int? CurrentPage,
int? PerPage
) : IQuery;
@@ -0,0 +1,91 @@
#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.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Application.Common.DTO.Pagination;
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.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
/// <summary>
/// Handler for the query to get the lightweight read models of all the tracks of an album.
/// </summary>
public class GetAlbumTracksLiteQueryHandler : IQueryHandler<GetAlbumTracksLiteQuery, Result<PaginatedResponse<TrackLiteResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetAlbumTracksLiteQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteQueryHandler"/> 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 GetAlbumTracksLiteQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetAlbumTracksLiteQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the lightweight read models of all the tracks of an album.
/// </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 a paginated collection of <see cref="TrackLiteResponse"/>, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<TrackLiteResponse>>> HandleAsync(GetAlbumTracksLiteQuery 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;
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(query.AlbumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return Errors.Music.AlbumNotFound;
// Admins can see the tracks of the albums of all libraries; for everyone else, only of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getAlbumResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
PaginationDataDto paginationData = new()
{
CurrentPage = query.CurrentPage ?? 1,
PerPage = query.PerPage ?? 200
};
Result<PaginatedResultDto<TrackLiteRow>> getTracksResult = await _unitOfWork.TrackRepository.GetTracksLiteByAlbumIdAsync(query.AlbumId, paginationData, cancellationToken).ConfigureAwait(false);
return getTracksResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -0,0 +1,26 @@
#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.GetAlbumTracksLite;
/// <summary>
/// Validates the needed validation rules for <see cref="GetAlbumTracksLiteQuery"/>.
/// </summary>
public class GetAlbumTracksLiteQueryValidator : AbstractValidator<GetAlbumTracksLiteQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteQueryValidator"/> class.
/// </summary>
public GetAlbumTracksLiteQueryValidator()
{
RuleFor(query => query.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty)
.Must(albumId => albumId != Guid.Empty)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
using Lumina.Contracts.DTO.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist;
/// <summary>
/// Command for adding an artist, together with the albums of the artist and the tracks of those albums.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this artist belongs to, taken from the route.</param>
/// <param name="Name">The name of the artist.</param>
/// <param name="Website">The website of the artist, if applicable.</param>
/// <param name="MusicBrainzArtistId">The MusicBrainz identifier of the artist, if applicable.</param>
/// <param name="Contributors">The list of media contributors that make up the artist.</param>
/// <param name="Albums">The list of albums of the artist, each with its own list of tracks.</param>
[DebuggerDisplay("Name: {Name}")]
public record AddArtistCommand(
string? LibraryId,
string? Name,
string? Website,
Guid? MusicBrainzArtistId,
List<MediaContributorReferenceDto>? Contributors,
List<AddAlbumCommand>? Albums
) : ICommand;
@@ -0,0 +1,189 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.DTO.MediaContributors;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using System;
using System.Collections.Generic;
using System.Linq;
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.AddArtist;
/// <summary>
/// Handler for the command to add an artist.
/// </summary>
public class AddArtistCommandHandler : ICommandHandler<AddArtistCommand, Result<ArtistResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<AddArtistCommand> _validator;
private readonly IPathService _pathService;
/// <summary>
/// Initializes a new instance of the <see cref="AddArtistCommandHandler"/> 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>
/// <param name="pathService">Injected service for file system path related functionality.</param>
public AddArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<AddArtistCommand> validator, IPathService pathService)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
_pathService = pathService;
}
/// <summary>
/// Handles the command to add an artist.
/// </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}"/> containing either a successfully created <see cref="ArtistResponse"/>, or an error message.
/// </returns>
public async Task<Result<ArtistResponse>> HandleAsync(AddArtistCommand 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 library id of the route is a non-empty Guid before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
// Admins can add artists to all libraries; for everyone else, only to the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// An artist can only belong to a library that exists, so a client can never register an entry that points to a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// An artist's tracks are only readable if they are stored inside one of the content locations of their library, so a client can never
// register an entry that points the reading pipeline at an arbitrary file of the host.
if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command))
return DomainErrors.Music.TrackPathMustBeWithinLibraryContentLocations;
// Media contributors are referenced by Id and are never created implicitly by adding an artist, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
// Convert the command to a domain aggregate to enforce invariants, then persist it in the repository.
Result<Artist> createArtistResult = command.ToDomainEntity(libraryId);
if (createArtistResult.IsFailure)
return createArtistResult.Errors;
// Persists the whole aggregate, artist, albums, tracks and their contributors, in a single transaction.
Result<Created> insertArtistResult = await _unitOfWork.ArtistRepository.InsertAsync(createArtistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (insertArtistResult.IsFailure)
return insertArtistResult.Errors;
// The pre-insert checks handle the common cases; a concurrent request could still persist an artist with the same identity between them
// and the save, in which case the persistence medium reports the unique constraint violation as a conflict.
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Returns the artist as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the database applied on save.
Result<ArtistEntity?> getPersistedArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(createArtistResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedArtistResult.IsFailure)
return getPersistedArtistResult.Errors;
if (getPersistedArtistResult.Value is null)
return DomainErrors.Music.ArtistNotFound;
return getPersistedArtistResult.Value.ToResponse();
}
/// <summary>
/// Determines whether every track path referenced by <paramref name="command"/> is stored inside one of the content locations of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library that owns the artist.</param>
/// <param name="command">The command carrying the referenced tracks.</param>
/// <returns><see langword="true"/> when every referenced track path is within a content location of the library; otherwise, <see langword="false"/>.</returns>
private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, AddArtistCommand command)
{
foreach (AddAlbumCommand album in command.Albums!)
foreach (AddTrackCommand track in album.Tracks!)
if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path!, contentLocation.Path)))
return false;
return true;
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(AddArtistCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. CollectContributorIds(command).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return DomainErrors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
/// <summary>
/// Collects the unique identifiers of every media contributor referenced by <paramref name="command"/>, be it directly on the artist,
/// or indirectly through one of its albums or the tracks of those albums.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <returns>The collected media contributor identifiers.</returns>
private static IEnumerable<Guid> CollectContributorIds(AddArtistCommand command)
{
foreach (MediaContributorReferenceDto contributor in command.Contributors!)
yield return contributor.ContributorId;
foreach (AddAlbumCommand album in command.Albums!)
{
foreach (MediaContributorReferenceDto contributor in album.Contributors!)
yield return contributor.ContributorId;
foreach (AddTrackCommand track in album.Tracks!)
foreach (MediaContributorReferenceDto contributor in track.Contributors!)
yield return contributor.ContributorId;
}
}
}
@@ -0,0 +1,547 @@
#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.AddArtist;
/// <summary>
/// Validates the needed validation rules for <see cref="AddArtistCommand"/>.
/// </summary>
public class AddArtistCommandValidator : AbstractValidator<AddArtistCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddArtistCommandValidator"/> class.
/// </summary>
public AddArtistCommandValidator()
{
// Validates the identifier of the media library that will own 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 identifying details of the artist.
RuleFor(command => command.Name)
.NotNull()
.NotEmpty()
.WithError(Errors.Music.ArtistNameCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong);
RuleFor(command => command.Website)
.MaximumLength(2048)
.When(command => command.Website is not null)
.WithError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong);
RuleFor(command => command.MusicBrainzArtistId)
.Must(musicBrainzArtistId => musicBrainzArtistId != Guid.Empty)
.When(command => command.MusicBrainzArtistId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the media contributors that make up the artist.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates each album created together with the artist, when the request carries albums.
RuleFor(command => command.Albums)
.NotNull()
.WithError(Errors.Music.AlbumsListCannotBeNull);
RuleForEach(command => command.Albums)
.ChildRules(album =>
{
// Validates the metadata of the album: title, lengths, release type and status, and disc and track counts.
album.RuleFor(a => a!.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Music.AlbumTitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
metadata.RuleFor(m => m!.ReleaseType)
.IsInEnum()
.When(m => m!.ReleaseType is not null)
.WithError(Errors.Music.UnknownMusicReleaseType);
metadata.RuleFor(m => m!.ReleaseStatus)
.IsInEnum()
.When(m => m!.ReleaseStatus is not null)
.WithError(Errors.Music.UnknownMusicReleaseStatus);
metadata.RuleFor(m => m!.TotalDiscs)
.GreaterThan(0)
.When(m => m!.TotalDiscs.HasValue)
.WithError(Errors.Music.TotalDiscsMustBeGreaterThanZero);
metadata.RuleFor(m => m!.TotalTracks)
.GreaterThan(0)
.When(m => m!.TotalTracks.HasValue)
.WithError(Errors.Music.TotalTracksMustBeGreaterThanZero);
metadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
metadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
metadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
metadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
});
// Validates the physical characteristics of the album: format and catalog number.
album.RuleFor(a => a!.MediaFormat)
.IsInEnum()
.When(a => a!.MediaFormat is not null)
.WithError(Errors.Music.UnknownMusicMediaFormat);
album.RuleFor(a => a!.CatalogNumber)
.MaximumLength(50)
.When(a => a!.CatalogNumber is not null)
.WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong);
// Validates the MusicBrainz identifiers of the album.
album.RuleFor(a => a!.MusicBrainzReleaseId)
.Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty)
.When(a => a!.MusicBrainzReleaseId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
album.RuleFor(a => a!.MusicBrainzReleaseGroupId)
.Must(musicBrainzReleaseGroupId => musicBrainzReleaseGroupId != Guid.Empty)
.When(a => a!.MusicBrainzReleaseGroupId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
album.RuleFor(a => a!.MusicBrainzReleaseArtistId)
.Must(musicBrainzReleaseArtistId => musicBrainzReleaseArtistId != Guid.Empty)
.When(a => a!.MusicBrainzReleaseArtistId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the media contributors that performed on the album.
album.RuleFor(a => a!.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
album.RuleForEach(a => a!.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the ratings of the album.
album.RuleFor(a => a!.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
album.RuleForEach(a => a!.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
// Validates the tracks of the album.
album.RuleFor(a => a!.Tracks)
.NotNull()
.WithError(Errors.Music.TracksListCannotBeNull);
album.RuleForEach(a => a!.Tracks)
.ChildRules(track =>
{
// Validates the file system path of the track.
track.RuleFor(t => t!.Path)
.NotEmpty()
.WithError(Errors.Music.TrackPathCannotBeEmpty)
.MaximumLength(2048)
.WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong);
// Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags.
track.RuleFor(t => t!.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(trackMetadata =>
{
trackMetadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
trackMetadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
trackMetadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
});
// Validates the ordering and performance characteristics of the track.
track.RuleFor(t => t!.TrackNumber)
.GreaterThan(0)
.When(t => t!.TrackNumber.HasValue)
.WithError(Errors.Music.TrackNumberMustBeGreaterThanZero);
track.RuleFor(t => t!.DiscNumber)
.GreaterThan(0)
.When(t => t!.DiscNumber.HasValue)
.WithError(Errors.Music.DiscNumberMustBeGreaterThanZero);
track.RuleFor(t => t!.Script)
.MaximumLength(50)
.When(t => t!.Script is not null)
.WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong);
track.RuleFor(t => t!.Key)
.IsInEnum()
.When(t => t!.Key is not null)
.WithError(Errors.Music.UnknownMusicKey);
track.RuleFor(t => t!.Bpm)
.GreaterThan(0)
.When(t => t!.Bpm.HasValue)
.WithError(Errors.Music.BpmMustBeGreaterThanZero);
track.RuleFor(t => t!.Work)
.MaximumLength(255)
.When(t => t!.Work is not null)
.WithError(Errors.Music.WorkMustBeMaximum255CharactersLong);
// Validates the media contributors that performed on the track.
track.RuleFor(t => t!.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
track.RuleForEach(t => t!.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the moods and the ISRC codes of the track.
track.RuleForEach(t => t!.Moods)
.ChildRules(mood =>
mood.RuleFor(m => m.Name)
.NotEmpty()
.WithError(Errors.Metadata.MoodNameCannotBeEmpty));
track.RuleForEach(t => t!.Isrcs)
.ChildRules(isrc =>
isrc.RuleFor(i => i.Value)
.NotEmpty()
.WithError(Errors.Music.IsrcValueCannotBeEmpty));
// Validates the ratings of the track.
track.RuleFor(t => t!.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
track.RuleForEach(t => t!.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
});
});
}
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist;
/// <summary>
/// Command for deleting an 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 delete, taken from the route.</param>
[DebuggerDisplay("ArtistId: {ArtistId}")]
public record DeleteArtistCommand(
string? LibraryId,
string? ArtistId
) : ICommand;
@@ -0,0 +1,105 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.DeleteArtist;
/// <summary>
/// Handler for the command to delete an artist by its Id.
/// </summary>
public class DeleteArtistCommandHandler : ICommandHandler<DeleteArtistCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteArtistCommand> _validator;
/// <summary>
/// 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="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteArtistCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete an 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<Deleted>> HandleAsync(DeleteArtistCommand 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!);
// 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: false, shouldTrackEntities: false, cancellationToken: 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 deleted 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 delete 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;
// An artist can only belong to a library that exists, so a client can never delete an artist of a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
Result<Deleted> deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistResult.IsFailure)
return deleteArtistResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return deleteArtistResult;
}
}
@@ -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.DeleteArtist;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteArtistCommand"/>.
/// </summary>
public class DeleteArtistCommandValidator : AbstractValidator<DeleteArtistCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteArtistCommandValidator"/> class.
/// </summary>
public DeleteArtistCommandValidator()
{
// 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 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);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
using Lumina.Contracts.DTO.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist;
/// <summary>
/// Command for updating an existing artist.
/// </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, taken from the route.</param>
/// <param name="Name">The name of the artist.</param>
/// <param name="Website">The website of the artist, if applicable.</param>
/// <param name="MusicBrainzArtistId">The MusicBrainz identifier of the artist, if applicable.</param>
/// <param name="Contributors">The list of media contributors that make up the artist.</param>
/// <param name="Albums">The list of albums of the artist, each with its own list of tracks.</param>
[DebuggerDisplay("Name: {Name}")]
public record UpdateArtistCommand(
string? LibraryId,
string? ArtistId,
string? Name,
string? Website,
Guid? MusicBrainzArtistId,
List<MediaContributorReferenceDto>? Contributors,
List<AddAlbumCommand>? Albums
) : ICommand;
@@ -0,0 +1,203 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.DTO.MediaContributors;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using System;
using System.Collections.Generic;
using System.Linq;
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.UpdateArtist;
/// <summary>
/// Handler for the command to update an artist.
/// </summary>
public class UpdateArtistCommandHandler : ICommandHandler<UpdateArtistCommand, Result<ArtistResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateArtistCommand> _validator;
private readonly IPathService _pathService;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCommandHandler"/> 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>
/// <param name="pathService">Injected service for file system path related functionality.</param>
public UpdateArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateArtistCommand> validator, IPathService pathService)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
_pathService = pathService;
}
/// <summary>
/// Handles the command to update an artist.
/// </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}"/> containing either a successfully updated <see cref="ArtistResponse"/>, or an error message.
/// </returns>
public async Task<Result<ArtistResponse>> HandleAsync(UpdateArtistCommand 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!);
// Get the existing artist with all its related data.
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, cancellationToken: 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 edited 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 update 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;
// An artist can only belong to a library that exists, so a client can never update an artist that points to a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// An artist's tracks are only readable if they are stored inside one of the content locations of their library, so a client can never
// edit an entry to point the reading pipeline at an arbitrary file of the host.
if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command))
return DomainErrors.Music.TrackPathMustBeWithinLibraryContentLocations;
// Media contributors are referenced by Id and are never created implicitly by editing an artist, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
// Convert the command to a domain aggregate to enforce invariants, preserving the identity and creation metadata of the stored artist.
Result<Artist> updateArtistResult = command.ToDomainEntity(existingArtist);
if (updateArtistResult.IsFailure)
return updateArtistResult.Errors;
// Map the updated domain artist onto a fresh repository entity, ready for the repository to replace the stored data.
ArtistEntity updatedArtist = updateArtistResult.Value.ToRepositoryEntity();
Result<Updated> updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(updatedArtist, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Returns the artist as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save.
Result<ArtistEntity?> getPersistedArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(existingArtist.Id, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedArtistResult.IsFailure)
return getPersistedArtistResult.Errors;
if (getPersistedArtistResult.Value is null)
return DomainErrors.Music.ArtistNotFound;
return getPersistedArtistResult.Value.ToResponse();
}
/// <summary>
/// Determines whether every track path referenced by <paramref name="command"/> is stored inside one of the content locations of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library that owns the artist.</param>
/// <param name="command">The command carrying the referenced tracks.</param>
/// <returns><see langword="true"/> when every referenced track path is within a content location of the library; otherwise, <see langword="false"/>.</returns>
private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, UpdateArtistCommand command)
{
foreach (AddAlbumCommand album in command.Albums!)
foreach (AddTrackCommand track in album.Tracks!)
if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path!, contentLocation.Path)))
return false;
return true;
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(UpdateArtistCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. CollectContributorIds(command).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return DomainErrors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
/// <summary>
/// Collects the unique identifiers of every media contributor referenced by <paramref name="command"/>, be it directly on the artist,
/// or indirectly through one of its albums or the tracks of those albums.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <returns>The collected media contributor identifiers.</returns>
private static IEnumerable<Guid> CollectContributorIds(UpdateArtistCommand command)
{
foreach (MediaContributorReferenceDto contributor in command.Contributors!)
yield return contributor.ContributorId;
foreach (AddAlbumCommand album in command.Albums!)
{
foreach (MediaContributorReferenceDto contributor in album.Contributors!)
yield return contributor.ContributorId;
foreach (AddTrackCommand track in album.Tracks!)
foreach (MediaContributorReferenceDto contributor in track.Contributors!)
yield return contributor.ContributorId;
}
}
}
@@ -0,0 +1,557 @@
#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.UpdateArtist;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateArtistCommand"/>.
/// </summary>
public class UpdateArtistCommandValidator : AbstractValidator<UpdateArtistCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCommandValidator"/> class.
/// </summary>
public UpdateArtistCommandValidator()
{
// 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 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);
// Validates the identifying details of the artist.
RuleFor(command => command.Name)
.NotNull()
.NotEmpty()
.WithError(Errors.Music.ArtistNameCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong);
RuleFor(command => command.Website)
.MaximumLength(2048)
.When(command => command.Website is not null)
.WithError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong);
RuleFor(command => command.MusicBrainzArtistId)
.Must(musicBrainzArtistId => musicBrainzArtistId != Guid.Empty)
.When(command => command.MusicBrainzArtistId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the media contributors that make up the artist.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates each album updated together with the artist, when the request carries albums.
RuleFor(command => command.Albums)
.NotNull()
.WithError(Errors.Music.AlbumsListCannotBeNull);
RuleForEach(command => command.Albums)
.ChildRules(album =>
{
// Validates the metadata of the album: title, lengths, release type and status, and disc and track counts.
album.RuleFor(a => a!.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Music.AlbumTitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
metadata.RuleFor(m => m!.ReleaseType)
.IsInEnum()
.When(m => m!.ReleaseType is not null)
.WithError(Errors.Music.UnknownMusicReleaseType);
metadata.RuleFor(m => m!.ReleaseStatus)
.IsInEnum()
.When(m => m!.ReleaseStatus is not null)
.WithError(Errors.Music.UnknownMusicReleaseStatus);
metadata.RuleFor(m => m!.TotalDiscs)
.GreaterThan(0)
.When(m => m!.TotalDiscs.HasValue)
.WithError(Errors.Music.TotalDiscsMustBeGreaterThanZero);
metadata.RuleFor(m => m!.TotalTracks)
.GreaterThan(0)
.When(m => m!.TotalTracks.HasValue)
.WithError(Errors.Music.TotalTracksMustBeGreaterThanZero);
metadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
metadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
metadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
metadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
});
// Validates the physical characteristics of the album: format and catalog number.
album.RuleFor(a => a!.MediaFormat)
.IsInEnum()
.When(a => a!.MediaFormat is not null)
.WithError(Errors.Music.UnknownMusicMediaFormat);
album.RuleFor(a => a!.CatalogNumber)
.MaximumLength(50)
.When(a => a!.CatalogNumber is not null)
.WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong);
// Validates the MusicBrainz identifiers of the album.
album.RuleFor(a => a!.MusicBrainzReleaseId)
.Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty)
.When(a => a!.MusicBrainzReleaseId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
album.RuleFor(a => a!.MusicBrainzReleaseGroupId)
.Must(musicBrainzReleaseGroupId => musicBrainzReleaseGroupId != Guid.Empty)
.When(a => a!.MusicBrainzReleaseGroupId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
album.RuleFor(a => a!.MusicBrainzReleaseArtistId)
.Must(musicBrainzReleaseArtistId => musicBrainzReleaseArtistId != Guid.Empty)
.When(a => a!.MusicBrainzReleaseArtistId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the media contributors that performed on the album.
album.RuleFor(a => a!.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
album.RuleForEach(a => a!.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the ratings of the album.
album.RuleFor(a => a!.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
album.RuleForEach(a => a!.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
// Validates the tracks of the album.
album.RuleFor(a => a!.Tracks)
.NotNull()
.WithError(Errors.Music.TracksListCannotBeNull);
album.RuleForEach(a => a!.Tracks)
.ChildRules(track =>
{
// Validates the file system path of the track.
track.RuleFor(t => t!.Path)
.NotEmpty()
.WithError(Errors.Music.TrackPathCannotBeEmpty)
.MaximumLength(2048)
.WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong);
// Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags.
track.RuleFor(t => t!.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(trackMetadata =>
{
trackMetadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
trackMetadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
trackMetadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
});
// Validates the ordering and performance characteristics of the track.
track.RuleFor(t => t!.TrackNumber)
.GreaterThan(0)
.When(t => t!.TrackNumber.HasValue)
.WithError(Errors.Music.TrackNumberMustBeGreaterThanZero);
track.RuleFor(t => t!.DiscNumber)
.GreaterThan(0)
.When(t => t!.DiscNumber.HasValue)
.WithError(Errors.Music.DiscNumberMustBeGreaterThanZero);
track.RuleFor(t => t!.Script)
.MaximumLength(50)
.When(t => t!.Script is not null)
.WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong);
track.RuleFor(t => t!.Key)
.IsInEnum()
.When(t => t!.Key is not null)
.WithError(Errors.Music.UnknownMusicKey);
track.RuleFor(t => t!.Bpm)
.GreaterThan(0)
.When(t => t!.Bpm.HasValue)
.WithError(Errors.Music.BpmMustBeGreaterThanZero);
track.RuleFor(t => t!.Work)
.MaximumLength(255)
.When(t => t!.Work is not null)
.WithError(Errors.Music.WorkMustBeMaximum255CharactersLong);
// Validates the media contributors that performed on the track.
track.RuleFor(t => t!.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
track.RuleForEach(t => t!.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the moods and the ISRC codes of the track.
track.RuleForEach(t => t!.Moods)
.ChildRules(mood =>
mood.RuleFor(m => m.Name)
.NotEmpty()
.WithError(Errors.Metadata.MoodNameCannotBeEmpty));
track.RuleForEach(t => t!.Isrcs)
.ChildRules(isrc =>
isrc.RuleFor(i => i.Value)
.NotEmpty()
.WithError(Errors.Music.IsrcValueCannotBeEmpty));
// Validates the ratings of the track.
track.RuleFor(t => t!.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
track.RuleForEach(t => t!.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
});
});
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist;
/// <summary>
/// Query for getting an artist by its Id.
/// </summary>
/// <param name="ArtistId">The unique identifier of the artist to get.</param>
[DebuggerDisplay("ArtistId: {ArtistId}")]
public record GetArtistQuery(
Guid ArtistId
) : IQuery;
@@ -0,0 +1,82 @@
#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;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist;
/// <summary>
/// Handler for the query to get an artist by its Id.
/// </summary>
public class GetArtistQueryHandler : IQueryHandler<GetArtistQuery, Result<ArtistResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetArtistQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistQueryHandler"/> 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 GetArtistQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetArtistQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get an artist by its Id.
/// </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 a successfully retrieved <see cref="ArtistResponse"/>, or an error message.
/// </returns>
public async Task<Result<ArtistResponse>> HandleAsync(GetArtistQuery 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;
// Admins can see all artists; for everyone else, only the artists of the libraries they own.
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(query.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
if (getArtistResult.Value is null)
return Errors.Music.ArtistNotFound;
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getArtistResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
return getArtistResult.Value.ToResponse();
}
}
@@ -0,0 +1,26 @@
#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.GetArtist;
/// <summary>
/// Validates the needed validation rules for <see cref="GetArtistQuery"/>.
/// </summary>
public class GetArtistQueryValidator : AbstractValidator<GetArtistQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistQueryValidator"/> class.
/// </summary>
public GetArtistQueryValidator()
{
RuleFor(query => query.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums;
/// <summary>
/// Query for getting all the albums of an artist.
/// </summary>
/// <param name="ArtistId">The unique identifier of the artist whose albums are retrieved.</param>
[DebuggerDisplay("ArtistId: {ArtistId}")]
public record GetArtistAlbumsQuery(
Guid ArtistId
) : IQuery;
@@ -0,0 +1,83 @@
#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;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums;
/// <summary>
/// Handler for the query to get all the albums of an artist.
/// </summary>
public class GetArtistAlbumsQueryHandler : IQueryHandler<GetArtistAlbumsQuery, Result<IReadOnlyList<AlbumResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetArtistAlbumsQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsQueryHandler"/> 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 GetArtistAlbumsQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetArtistAlbumsQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get all the albums of an artist.
/// </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 a collection of <see cref="AlbumResponse"/>, or an error message.
/// </returns>
public async Task<Result<IReadOnlyList<AlbumResponse>>> HandleAsync(GetArtistAlbumsQuery 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;
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(query.ArtistId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
if (getArtistResult.Value is null)
return Errors.Music.ArtistNotFound;
// Admins can see the albums of the artists of all libraries; for everyone else, only of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getArtistResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<AlbumEntity>> getAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(query.ArtistId, cancellationToken).ConfigureAwait(false);
return getAlbumsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -0,0 +1,26 @@
#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.GetArtistAlbums;
/// <summary>
/// Validates the needed validation rules for <see cref="GetArtistAlbumsQuery"/>.
/// </summary>
public class GetArtistAlbumsQueryValidator : AbstractValidator<GetArtistAlbumsQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsQueryValidator"/> class.
/// </summary>
public GetArtistAlbumsQueryValidator()
{
RuleFor(query => query.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty)
.Must(artistId => artistId != Guid.Empty)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
}
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite;
/// <summary>
/// Query for getting the lightweight read models of all the albums of an artist.
/// </summary>
/// <param name="ArtistId">The unique identifier of the artist whose albums are retrieved.</param>
/// <param name="CurrentPage">The page of results to retrieve.</param>
/// <param name="PerPage">The maximum number of albums to retrieve per page.</param>
[DebuggerDisplay("ArtistId: {ArtistId}")]
public record GetArtistAlbumsLiteQuery(
Guid ArtistId,
int? CurrentPage,
int? PerPage
) : IQuery;
@@ -0,0 +1,91 @@
#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.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Application.Common.DTO.Pagination;
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.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite;
/// <summary>
/// Handler for the query to get the lightweight read models of all the albums of an artist.
/// </summary>
public class GetArtistAlbumsLiteQueryHandler : IQueryHandler<GetArtistAlbumsLiteQuery, Result<PaginatedResponse<AlbumLiteResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetArtistAlbumsLiteQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsLiteQueryHandler"/> 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 GetArtistAlbumsLiteQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetArtistAlbumsLiteQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the lightweight read models of all the albums of an artist.
/// </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 a paginated collection of <see cref="AlbumLiteResponse"/>, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<AlbumLiteResponse>>> HandleAsync(GetArtistAlbumsLiteQuery 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;
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(query.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
if (getArtistResult.Value is null)
return Errors.Music.ArtistNotFound;
// Admins can see the albums of the artists of all libraries; for everyone else, only of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getArtistResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
PaginationDataDto paginationData = new()
{
CurrentPage = query.CurrentPage ?? 1,
PerPage = query.PerPage ?? 200
};
Result<PaginatedResultDto<AlbumLiteRow>> getAlbumsResult = await _unitOfWork.AlbumRepository.GetAlbumsLiteByArtistIdAsync(query.ArtistId, paginationData, cancellationToken).ConfigureAwait(false);
return getAlbumsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -0,0 +1,26 @@
#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.GetArtistAlbumsLite;
/// <summary>
/// Validates the needed validation rules for <see cref="GetArtistAlbumsLiteQuery"/>.
/// </summary>
public class GetArtistAlbumsLiteQueryValidator : AbstractValidator<GetArtistAlbumsLiteQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsLiteQueryValidator"/> class.
/// </summary>
public GetArtistAlbumsLiteQueryValidator()
{
RuleFor(query => query.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty)
.Must(artistId => artistId != Guid.Empty)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists;
/// <summary>
/// Query for getting all the artists of a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose artists are retrieved.</param>
/// <param name="CurrentPage">The page of results to retrieve.</param>
/// <param name="PerPage">The maximum number of artists to retrieve per page.</param>
/// <param name="SearchTerm">The search term used to filter the artists by name.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetArtistsQuery(
Guid LibraryId,
int? CurrentPage,
int? PerPage,
string? SearchTerm
) : IQuery;
@@ -0,0 +1,92 @@
#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.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
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;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists;
/// <summary>
/// Handler for the query to get all the artists of a media library.
/// </summary>
public class GetArtistsQueryHandler : IQueryHandler<GetArtistsQuery, Result<PaginatedResponse<ArtistResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetArtistsQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsQueryHandler"/> 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 GetArtistsQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetArtistsQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get all the 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 a paginated collection of <see cref="ArtistResponse"/>, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<ArtistResponse>>> HandleAsync(GetArtistsQuery 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;
// Admins can see 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(query.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
PaginationDataDto paginationData = new()
{
CurrentPage = query.CurrentPage ?? 1,
PerPage = query.PerPage ?? 200
};
LibraryFilterDto libraryFilter = new()
{
LibraryId = query.LibraryId,
SearchTerm = query.SearchTerm
};
Result<PaginatedResultDto<ArtistEntity>> getArtistsResult = await _unitOfWork.ArtistRepository
.GetAllAsync(paginationData, filterModel: libraryFilter, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
return getArtistsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -0,0 +1,26 @@
#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.GetArtists;
/// <summary>
/// Validates the needed validation rules for <see cref="GetArtistsQuery"/>.
/// </summary>
public class GetArtistsQueryValidator : AbstractValidator<GetArtistsQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsQueryValidator"/> class.
/// </summary>
public GetArtistsQueryValidator()
{
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(libraryId => libraryId != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite;
/// <summary>
/// Query for getting the lightweight read models of all the artists of a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose artists are retrieved.</param>
/// <param name="CurrentPage">The page of results to retrieve.</param>
/// <param name="PerPage">The maximum number of artists to retrieve per page.</param>
/// <param name="SearchTerm">The search term used to filter the artists by name.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetArtistsLiteQuery(
Guid LibraryId,
int? CurrentPage,
int? PerPage,
string? SearchTerm
) : IQuery;
@@ -0,0 +1,92 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Application.Common.DTO.Pagination;
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.Common;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite;
/// <summary>
/// Handler for the query to get the lightweight read models of all the artists of a media library.
/// </summary>
public class GetArtistsLiteQueryHandler : IQueryHandler<GetArtistsLiteQuery, Result<PaginatedResponse<ArtistLiteResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetArtistsLiteQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsLiteQueryHandler"/> 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 GetArtistsLiteQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetArtistsLiteQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the lightweight read models of all the 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 a paginated collection of <see cref="ArtistLiteResponse"/>, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<ArtistLiteResponse>>> HandleAsync(GetArtistsLiteQuery 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;
// Admins can see 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(query.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
PaginationDataDto paginationData = new()
{
CurrentPage = query.CurrentPage ?? 1,
PerPage = query.PerPage ?? 200
};
LibraryFilterDto filter = new()
{
LibraryId = query.LibraryId,
SearchTerm = query.SearchTerm
};
Result<PaginatedResultDto<ArtistLiteRow>> getArtistsResult = await _unitOfWork.ArtistRepository.GetAllLiteAsync(
paginationData,
filterModel: filter,
cancellationToken: cancellationToken).ConfigureAwait(false);
return getArtistsResult.Match(value => Result.From(value.ToResponses()), errors => errors);
}
}
@@ -0,0 +1,26 @@
#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.GetArtistsLite;
/// <summary>
/// Validates the needed validation rules for <see cref="GetArtistsLiteQuery"/>.
/// </summary>
public class GetArtistsLiteQueryValidator : AbstractValidator<GetArtistsLiteQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsLiteQueryValidator"/> class.
/// </summary>
public GetArtistsLiteQueryValidator()
{
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(libraryId => libraryId != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
/// <summary>
/// Command for adding a track to an album.
/// </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 this track belongs to, taken from the route.</param>
/// <param name="AlbumId">The Id of the album the track belongs to, taken from the route.</param>
/// <param name="Path">The file system path of the track.</param>
/// <param name="Metadata">The audio metadata of the track.</param>
/// <param name="TrackNumber">The number of the track on its disc.</param>
/// <param name="DiscNumber">The number of the disc the track belongs to, if applicable.</param>
/// <param name="Script">The script used by the language of the track, if applicable.</param>
/// <param name="Key">The musical key of the track, if applicable.</param>
/// <param name="Bpm">The tempo of the track in beats per minute, if applicable.</param>
/// <param name="Work">The title of the work the track is a recording of, if applicable.</param>
/// <param name="MusicBrainzRecordingId">The MusicBrainz identifier of the recording, if applicable.</param>
/// <param name="MusicBrainzTrackId">The MusicBrainz identifier of the track, if applicable.</param>
/// <param name="MusicBrainzWorkId">The MusicBrainz identifier of the work, if applicable.</param>
/// <param name="Moods">The list of moods of the track.</param>
/// <param name="Isrcs">The list of ISRC of the track.</param>
/// <param name="Contributors">The list of media contributors that performed on the track.</param>
/// <param name="Ratings">The list of ratings for this track.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record AddTrackCommand(
string? LibraryId,
string? ArtistId,
string? AlbumId,
string? Path,
AudioMetadataDto? Metadata,
int? TrackNumber,
int? DiscNumber,
string? Script,
MusicKey? Key,
int? Bpm,
string? Work,
Guid? MusicBrainzRecordingId,
Guid? MusicBrainzTrackId,
Guid? MusicBrainzWorkId,
List<MoodDto>? Moods,
List<IsrcDto>? Isrcs,
List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings
) : ICommand;
@@ -0,0 +1,193 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
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.Commands.AddTrack;
/// <summary>
/// Handler for the command to add a track to an album.
/// </summary>
public class AddTrackCommandHandler : ICommandHandler<AddTrackCommand, Result<TrackResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<AddTrackCommand> _validator;
private readonly IPathService _pathService;
/// <summary>
/// Initializes a new instance of the <see cref="AddTrackCommandHandler"/> 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>
/// <param name="pathService">Injected service for file system path related functionality.</param>
public AddTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<AddTrackCommand> validator, IPathService pathService)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
_pathService = pathService;
}
/// <summary>
/// Handles the command to add a track to an album.
/// </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}"/> containing either a successfully created <see cref="TrackResponse"/>, or an error message.
/// </returns>
public async Task<Result<TrackResponse>> HandleAsync(AddTrackCommand 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!);
// Admins can add tracks to the albums of all libraries; for everyone else, only to the albums of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// A track can only belong to a library that exists, so a client can never register an entry that points to a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return Errors.Library.LibraryNotFound;
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return Errors.Music.AlbumNotFound;
// Resource scoping: the track must belong to an album of the artist and library named by the route, so that a track can never be added
// through another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere.
if (getAlbumResult.Value.LibraryId != libraryId || getAlbumResult.Value.ArtistId != artistId)
return Errors.Music.AlbumNotFound;
// A track is only readable if it is stored inside one of the content locations of its library, so a client can never register an entry
// that points the reading pipeline at an arbitrary file of the host.
if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command))
return Errors.Music.TrackPathMustBeWithinLibraryContentLocations;
// Media contributors are referenced by Id and are never created implicitly by adding a track, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
Result<Track> createTrackResult = command.ToDomainEntity();
if (createTrackResult.IsFailure)
return createTrackResult.Errors;
TrackEntity persistenceTrack = createTrackResult.Value.ToRepositoryEntity(albumId, libraryId);
Result<Created> insertTrackResult = await _unitOfWork.TrackRepository.InsertAsync(persistenceTrack, cancellationToken).ConfigureAwait(false);
if (insertTrackResult.IsFailure)
return insertTrackResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Returns the track as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the database applied on save.
Result<TrackEntity?> getPersistedTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(persistenceTrack.Id, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedTrackResult.IsFailure)
return getPersistedTrackResult.Errors;
if (getPersistedTrackResult.Value is null)
return Errors.Music.TrackNotFound;
return getPersistedTrackResult.Value.ToResponse();
}
/// <summary>
/// Determines whether the track path referenced by <paramref name="command"/> is stored inside one of the content locations of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library that owns the track.</param>
/// <param name="command">The command carrying the referenced track.</param>
/// <returns><see langword="true"/> when the referenced track path is within a content location of the library; otherwise, <see langword="false"/>.</returns>
private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, AddTrackCommand command)
{
return library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path));
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(AddTrackCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. CollectContributorIds(command).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return Errors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
/// <summary>
/// Collects the unique identifiers of every media contributor referenced by <paramref name="command"/>.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <returns>The collected media contributor identifiers.</returns>
private static IEnumerable<Guid> CollectContributorIds(AddTrackCommand command)
{
foreach (MediaContributorReferenceDto contributor in command.Contributors!)
yield return contributor.ContributorId;
}
}
@@ -0,0 +1,284 @@
#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.AddTrack;
/// <summary>
/// Validates the needed validation rules for <see cref="AddTrackCommand"/>.
/// </summary>
public class AddTrackCommandValidator : AbstractValidator<AddTrackCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddTrackCommandValidator"/> class.
/// </summary>
public AddTrackCommandValidator()
{
// 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 that owns the track, 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 is added 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);
RuleFor(command => command.Path)
.NotEmpty()
.WithError(Errors.Music.TrackPathCannotBeEmpty)
.MaximumLength(2048)
.WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong);
// Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags.
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(trackMetadata =>
{
trackMetadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
trackMetadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
trackMetadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
});
RuleFor(command => command.MusicBrainzRecordingId)
.Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty)
.When(command => command.MusicBrainzRecordingId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
RuleFor(command => command.MusicBrainzTrackId)
.Must(musicBrainzTrackId => musicBrainzTrackId != Guid.Empty)
.When(command => command.MusicBrainzTrackId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
RuleFor(command => command.MusicBrainzWorkId)
.Must(musicBrainzWorkId => musicBrainzWorkId != Guid.Empty)
.When(command => command.MusicBrainzWorkId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the ordering and performance characteristics of the track.
RuleFor(command => command.TrackNumber)
.GreaterThan(0)
.When(command => command.TrackNumber.HasValue)
.WithError(Errors.Music.TrackNumberMustBeGreaterThanZero);
RuleFor(command => command.DiscNumber)
.GreaterThan(0)
.When(command => command.DiscNumber.HasValue)
.WithError(Errors.Music.DiscNumberMustBeGreaterThanZero);
RuleFor(command => command.Script)
.MaximumLength(50)
.When(command => command.Script is not null)
.WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong);
RuleFor(command => command.Key)
.IsInEnum()
.When(command => command.Key is not null)
.WithError(Errors.Music.UnknownMusicKey);
RuleFor(command => command.Bpm)
.GreaterThan(0)
.When(command => command.Bpm.HasValue)
.WithError(Errors.Music.BpmMustBeGreaterThanZero);
RuleFor(command => command.Work)
.MaximumLength(255)
.When(command => command.Work is not null)
.WithError(Errors.Music.WorkMustBeMaximum255CharactersLong);
// Validates the media contributors that performed on the track.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the ratings of the track.
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
RuleForEach(command => command.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
/// <summary>
/// Command for deleting a track by its Id.
/// </summary>
/// <param name="TrackId">The unique identifier of the track to delete.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record DeleteTrackCommand(
Guid TrackId
) : ICommand;
@@ -0,0 +1,84 @@
#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.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
/// <summary>
/// Handler for the command to delete a track by its Id.
/// </summary>
public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteTrackCommand> _validator;
/// <summary>
/// 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="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<DeleteTrackCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete a 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<Deleted>> HandleAsync(DeleteTrackCommand 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;
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(command.TrackId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null)
return Errors.Music.TrackNotFound;
// Admins can delete 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(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<Deleted> deleteTrackResult = await _unitOfWork.TrackRepository.DeleteByIdAsync(command.TrackId, cancellationToken).ConfigureAwait(false);
if (deleteTrackResult.IsFailure)
return deleteTrackResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return deleteTrackResult;
}
}
@@ -0,0 +1,26 @@
#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.DeleteTrack;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteTrackCommand"/>.
/// </summary>
public class DeleteTrackCommandValidator : AbstractValidator<DeleteTrackCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteTrackCommandValidator"/> class.
/// </summary>
public DeleteTrackCommandValidator()
{
RuleFor(command => command.TrackId)
.NotEmpty()
.WithError(Errors.Music.TrackIdCannotBeEmpty)
.Must(trackId => trackId != Guid.Empty)
.WithError(Errors.Music.TrackIdCannotBeEmpty);
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack;
/// <summary>
/// Command for updating a track.
/// </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 this track belongs to, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album this track belongs to, taken from the route.</param>
/// <param name="TrackId">The unique identifier of the track, taken from the route.</param>
/// <param name="Path">The file system path of the track.</param>
/// <param name="Metadata">The audio metadata of the track.</param>
/// <param name="TrackNumber">The number of the track on its disc.</param>
/// <param name="DiscNumber">The number of the disc the track belongs to, if applicable.</param>
/// <param name="Script">The script used by the language of the track, if applicable.</param>
/// <param name="Key">The musical key of the track, if applicable.</param>
/// <param name="Bpm">The tempo of the track in beats per minute, if applicable.</param>
/// <param name="Work">The title of the work the track is a recording of, if applicable.</param>
/// <param name="MusicBrainzRecordingId">The MusicBrainz identifier of the recording, if applicable.</param>
/// <param name="MusicBrainzTrackId">The MusicBrainz identifier of the track, if applicable.</param>
/// <param name="MusicBrainzWorkId">The MusicBrainz identifier of the work, if applicable.</param>
/// <param name="Ratings">The list of ratings for this track.</param>
/// <param name="Moods">The list of moods of the track.</param>
/// <param name="Isrcs">The list of ISRC of the track.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateTrackCommand(
string? LibraryId,
string? ArtistId,
string? AlbumId,
string? TrackId,
string? Path,
AudioMetadataDto? Metadata,
int? TrackNumber,
int? DiscNumber,
string? Script,
MusicKey? Key,
int? Bpm,
string? Work,
Guid? MusicBrainzRecordingId,
Guid? MusicBrainzTrackId,
Guid? MusicBrainzWorkId,
List<AudioRatingDto>? Ratings,
List<MoodDto>? Moods,
List<IsrcDto>? Isrcs
) : ICommand;
@@ -0,0 +1,150 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack;
/// <summary>
/// Handler for the command to update a track.
/// </summary>
public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Result<TrackResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateTrackCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateTrackCommandHandler"/> 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 UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateTrackCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update a track.
/// </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}"/> containing either a successfully updated <see cref="TrackResponse"/>, or an error message.
/// </returns>
public async Task<Result<TrackResponse>> HandleAsync(UpdateTrackCommand 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!);
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(trackId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null)
return Errors.Music.TrackNotFound;
TrackEntity existingTrack = getTrackResult.Value;
// Resource scoping: the track must belong to the library and the album named by the route, so that a track can never be edited
// through another library's or album's route; the mismatch is reported as not found, without disclosing that the track exists elsewhere.
if (existingTrack.LibraryId != libraryId || existingTrack.AlbumId != albumId)
return Errors.Music.TrackNotFound;
// Admins can update 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;
// The track must also belong to the artist named by the route, which is stored on the album of the track.
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null || getAlbumResult.Value.ArtistId != artistId)
return Errors.Music.TrackNotFound;
// A track can only belong to a library that exists, so a client can never update 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);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return Errors.Library.LibraryNotFound;
List<AudioRating> domainRatings = [];
List<Error> domainRatingsErrors = [];
foreach (AudioRatingDto rating in command.Ratings ?? [])
{
Result<AudioRating> ratingResult = rating.ToDomainEntity();
if (ratingResult.IsFailure)
domainRatingsErrors.AddRange(ratingResult.Errors);
else
domainRatings.Add(ratingResult.Value);
}
if (domainRatingsErrors.Count > 0)
return domainRatingsErrors;
Result<Track> updatedTrackResult = command.ToDomainEntity(TrackId.Create(existingTrack.Id), existingTrack.LibraryId, domainRatings);
if (updatedTrackResult.IsFailure)
return updatedTrackResult.Errors;
// Map the updated domain track onto a fresh repository entity, ready for the repository to replace the stored data.
TrackEntity persistenceTrack = updatedTrackResult.Value.ToRepositoryEntity(existingTrack.AlbumId, existingTrack.LibraryId);
Result<Updated> updateResult = await _unitOfWork.TrackRepository.UpdateAsync(persistenceTrack, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// The repository merges the fresh entity into the tracked stored track and the audit interceptor stamps the update columns, so the
// stored track carries the persisted values, including the audit ones.
return existingTrack.ToResponse();
}
}
@@ -0,0 +1,275 @@
#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.UpdateTrack;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateTrackCommand"/>.
/// </summary>
public class UpdateTrackCommandValidator : AbstractValidator<UpdateTrackCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateTrackCommandValidator"/> class.
/// </summary>
public UpdateTrackCommandValidator()
{
// 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 that owns the track, 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 that owns the track, 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 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);
RuleFor(command => command.Path)
.NotEmpty()
.WithError(Errors.Music.TrackPathCannotBeEmpty)
.MaximumLength(2048)
.WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong);
// Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags.
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(trackMetadata =>
{
trackMetadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
trackMetadata.RuleFor(m => m!.Description)
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
trackMetadata.RuleFor(m => m!.ReleaseInfo)
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
trackMetadata.RuleFor(m => m!.Genres)
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Genres)
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
trackMetadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
trackMetadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
});
RuleFor(command => command.MusicBrainzRecordingId)
.Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty)
.When(command => command.MusicBrainzRecordingId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
RuleFor(command => command.MusicBrainzTrackId)
.Must(musicBrainzTrackId => musicBrainzTrackId != Guid.Empty)
.When(command => command.MusicBrainzTrackId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
RuleFor(command => command.MusicBrainzWorkId)
.Must(musicBrainzWorkId => musicBrainzWorkId != Guid.Empty)
.When(command => command.MusicBrainzWorkId.HasValue)
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the ordering and performance characteristics of the track.
RuleFor(command => command.TrackNumber)
.GreaterThan(0)
.When(command => command.TrackNumber.HasValue)
.WithError(Errors.Music.TrackNumberMustBeGreaterThanZero);
RuleFor(command => command.DiscNumber)
.GreaterThan(0)
.When(command => command.DiscNumber.HasValue)
.WithError(Errors.Music.DiscNumberMustBeGreaterThanZero);
RuleFor(command => command.Script)
.MaximumLength(50)
.When(command => command.Script is not null)
.WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong);
RuleFor(command => command.Key)
.IsInEnum()
.When(command => command.Key is not null)
.WithError(Errors.Music.UnknownMusicKey);
RuleFor(command => command.Bpm)
.GreaterThan(0)
.When(command => command.Bpm.HasValue)
.WithError(Errors.Music.BpmMustBeGreaterThanZero);
RuleFor(command => command.Work)
.MaximumLength(255)
.When(command => command.Work is not null)
.WithError(Errors.Music.WorkMustBeMaximum255CharactersLong);
// Validates the ratings of the track.
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
RuleForEach(command => command.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
/// <summary>
/// Query for getting a track by its Id.
/// </summary>
/// <param name="TrackId">The unique identifier of the track to get.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record GetTrackQuery(
Guid TrackId
) : IQuery;
@@ -0,0 +1,82 @@
#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;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Errors;
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;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
/// <summary>
/// Handler for the query to get a track by its Id.
/// </summary>
public class GetTrackQueryHandler : IQueryHandler<GetTrackQuery, Result<TrackResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetTrackQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackQueryHandler"/> 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 GetTrackQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetTrackQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get a track by its Id.
/// </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 a successfully retrieved <see cref="TrackResponse"/>, or an error message.
/// </returns>
public async Task<Result<TrackResponse>> HandleAsync(GetTrackQuery 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;
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(query.TrackId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null)
return Errors.Music.TrackNotFound;
// Admins can see 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(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
return getTrackResult.Value.ToResponse();
}
}
@@ -0,0 +1,26 @@
#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.GetTrack;
/// <summary>
/// Validates the needed validation rules for <see cref="GetTrackQuery"/>.
/// </summary>
public class GetTrackQueryValidator : AbstractValidator<GetTrackQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackQueryValidator"/> class.
/// </summary>
public GetTrackQueryValidator()
{
RuleFor(query => query.TrackId)
.NotEmpty()
.WithError(Errors.Music.TrackIdCannotBeEmpty)
.Must(trackId => trackId != Guid.Empty)
.WithError(Errors.Music.TrackIdCannotBeEmpty);
}
}
@@ -31,12 +31,12 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <param name="BarnesAndNobleId">The Barnes & Noble ID of the book, if applicable.</param>
/// <param name="AppleBooksId">The Apple Books ID of the book, if applicable.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book.</param>
/// <param name="Contributors">The list of media contributors that contributed to this book.</param>
/// <param name="Ratings">The list of ratings for this book.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record AddBookCommand(
string? LibraryId,
string Path,
string? Path,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
@@ -88,7 +88,7 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
if (!getLibraryResult.Value.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path, contentLocation.Path)))
if (!getLibraryResult.Value.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path)))
return DomainErrors.WrittenContent.BookPathMustBeWithinLibraryContentLocations;
// Media contributors are referenced by Id and are never created implicitly by adding a book, so each one must already exist.
@@ -126,8 +126,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
metadata.RuleFor(m => m!.Tags)
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
metadata.RuleForEach(m => m!.Tags)
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
@@ -156,7 +155,8 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty().WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
@@ -291,7 +291,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
// Validates the media contributors that contributed to the book.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.WrittenContent.ContributorsListCannotBeNull);
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
@@ -31,7 +31,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <param name="BarnesAndNobleId">The Barnes & Noble ID of the book, if applicable.</param>
/// <param name="AppleBooksId">The Apple Books ID of the book, if applicable.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book.</param>
/// <param name="Contributors">The list of media contributors that contributed to this book.</param>
/// <param name="Ratings">The list of ratings for this book.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateBookCommand(
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -90,6 +91,13 @@ public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Resul
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// A book can only belong to a library that exists, so a client can never update a book that points to a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// Media contributors are referenced by Id and are never created implicitly by editing a book, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
@@ -103,13 +111,6 @@ public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Resul
// Map the updated domain book onto a fresh repository entity, ready for the repository to replace the stored data.
BookEntity updatedBook = updateBookResult.Value.ToRepositoryEntity();
// The enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that the repository
// replaces the stored data with; without this, the stored artwork would be cleared.
updatedBook.MetadataStatus = existingBook.MetadataStatus;
updatedBook.LastMetadataUpdateUtc = existingBook.LastMetadataUpdateUtc;
updatedBook.MetadataProvider = existingBook.MetadataProvider;
updatedBook.BookArtwork = existingBook.BookArtwork;
Result<Updated> updateResult = await _unitOfWork.BookRepository.UpdateAsync(updatedBook, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
@@ -246,19 +246,17 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
RuleFor(command => command.GoogleBooksId)
.Length(12)
.When(command => command.GoogleBooksId is not null)
.WithError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong)
.Matches(@"^[A-Za-z0-9_-]{12}$")
.When(command => command.GoogleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat);
.WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat)
.When(command => command.GoogleBooksId is not null);
RuleFor(command => command.BarnesAndNobleId)
.Length(10)
.When(command => command.BarnesAndNobleId is not null)
.WithError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong)
.Matches(@"^\d{10}$")
.When(command => command.BarnesAndNobleId is not null)
.WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat);
.WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat)
.When(command => command.BarnesAndNobleId is not null);
RuleFor(command => command.AppleBooksId)
.Matches(@"^id\d+$")
@@ -295,7 +293,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
// Validates the media contributors that contributed to the book.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.WrittenContent.ContributorsListCannotBeNull);
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
using System.IO;
#endregion
@@ -10,12 +9,14 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Command for updating the cover image of an existing book.
/// </summary>
/// <param name="BookId">The Id of the book whose cover image is updated.</param>
/// <param name="LibraryId">The unique identifier of the media library this book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book whose cover image is updated, taken from the route.</param>
/// <param name="Cover">The stream of the uploaded cover image file.</param>
/// <param name="FileName">The name of the uploaded cover image file.</param>
[DebuggerDisplay("BookId: {BookId} FileName: {FileName}")]
public record UpdateBookCoverCommand(
Guid BookId,
string? LibraryId,
string? BookId,
Stream? Cover,
string? FileName
) : ICommand;
@@ -8,9 +8,10 @@ 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.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
@@ -27,7 +28,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Handler for the command to update the cover image of an existing book.
/// </summary>
public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverCommand, Result<string>>
public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverCommand, Result<UpdateBookCoverResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
@@ -58,9 +59,9 @@ public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverComm
/// <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}"/> containing either the relative path of the stored cover image, or an error message.
/// An <see cref="Result{TValue}"/> containing either the response carrying the relative path of the stored cover image, or an error message.
/// </returns>
public async Task<Result<string>> HandleAsync(UpdateBookCoverCommand command, CancellationToken cancellationToken)
public async Task<Result<UpdateBookCoverResponse>> HandleAsync(UpdateBookCoverCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
@@ -72,14 +73,23 @@ public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverComm
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 bookId = Guid.Parse(command.BookId!);
// Get the existing book with its artwork.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.BookId, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
BookEntity existingBook = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be edited through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (existingBook.LibraryId != libraryId)
return DomainErrors.WrittenContent.BookNotFound;
// Admins can update the books of all libraries; for everyone else, only the books of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
@@ -87,13 +97,16 @@ public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverComm
return ApplicationErrors.Authorization.NotAuthorized;
// The artwork is stored under the library and author segments, so their names are resolved to keep the location consistent with the scanned artwork.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
string libraryName = getLibraryResult.Value.Title;
string authorName = await GetAuthorNameAsync(existingBook, cancellationToken).ConfigureAwait(false);
Result<string> authorNameResult = await GetAuthorNameAsync(existingBook, cancellationToken).ConfigureAwait(false);
if (authorNameResult.IsFailure)
return authorNameResult.Errors;
string authorName = authorNameResult.Value;
Result<string> storeArtworkResult = await _bookArtworkService.SaveBookArtworkAsync(
existingBook.LibraryId,
@@ -107,35 +120,17 @@ public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverComm
if (storeArtworkResult.IsFailure)
return storeArtworkResult.Errors;
// Update the stored cover artwork of the book with the newly stored image.
BookArtworkEntity? coverArtwork = existingBook.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover);
if (coverArtwork is null)
{
existingBook.BookArtwork.Add(new BookArtworkEntity
{
Id = Guid.NewGuid(),
BookId = existingBook.Id,
ArtworkType = ArtworkType.Cover,
Ordinal = 0,
FileName = storeArtworkResult.Value,
Status = ArtworkStatus.Enriched,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = userId,
UpdatedBy = null
});
}
else
{
coverArtwork.FileName = storeArtworkResult.Value;
coverArtwork.Status = ArtworkStatus.Enriched;
coverArtwork.LastUpdateUtc = DateTime.UtcNow;
coverArtwork.UpdatedOnUtc = DateTime.UtcNow;
coverArtwork.UpdatedBy = userId;
}
// Map the newly stored cover image onto the artwork of the book, replacing the existing cover or adding a new one.
BookArtworkEntity? existingCover = existingBook.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover);
BookArtworkEntity coverArtwork = command.ToRepositoryEntity(existingCover, bookId, storeArtworkResult.Value, userId);
if (existingCover is null)
existingBook.Artwork.Add(coverArtwork);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return storeArtworkResult.Value;
return new UpdateBookCoverResponse(storeArtworkResult.Value);
}
/// <summary>
@@ -143,19 +138,21 @@ public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverComm
/// </summary>
/// <param name="book">The book whose author is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The display name of the author of the book, or an empty string.</returns>
private async Task<string> GetAuthorNameAsync(BookEntity book, CancellationToken cancellationToken)
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the display name of the author of the book, or an error when the referenced media contributors could not be retrieved.
/// </returns>
private async Task<Result<string>> GetAuthorNameAsync(BookEntity book, CancellationToken cancellationToken)
{
IReadOnlyCollection<Guid> authorIds = [.. book.BookContributors
.Where(participation => participation.RoleCategory == MediaContributorRoleCategory.Author)
IReadOnlyCollection<Guid> authorIds = [.. book.Contributors
.Where(participation => participation.Role == MediaContributorRole.Author)
.Select(participation => participation.MediaContributorId)
.Distinct()];
if (authorIds.Count == 0)
return string.Empty;
return Result.From(string.Empty);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(authorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return string.Empty;
return getContributorsResult.Value.Select(contributor => contributor.DisplayName).FirstOrDefault() ?? string.Empty;
return getContributorsResult.Errors;
return Result.From(getContributorsResult.Value.Select(contributor => contributor.DisplayName).FirstOrDefault() ?? string.Empty);
}
}
@@ -17,14 +17,34 @@ public class UpdateBookCoverCommandValidator : AbstractValidator<UpdateBookCover
/// </summary>
public UpdateBookCoverCommandValidator()
{
// Validates the identifier of the media library the book belongs to, 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 book whose cover image is updated, taken from the route.
RuleFor(command => command.BookId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(command => command.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(command => command.BookId is not null && command.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
// Validates the uploaded cover image.
RuleFor(command => command.Cover)
.NotNull()
.WithError(Errors.WrittenContent.BookCoverCannotBeNull);
RuleFor(command => command.FileName)
.NotEmpty()
.When(command => command.Cover is not null)
.WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
}
}
@@ -2,7 +2,7 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -2,7 +2,7 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -28,8 +28,8 @@ public class GetBooksLiteQueryValidator : AbstractValidator<GetBooksLiteQuery>
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// the alpha key must be exactly one of the three picker bucket kinds, so that the filter specification can
// derive the key of a title unambiguously: no filter, a number bucket, a symbol bucket, or a single ASCII letter
// The alpha key must be exactly one of the three picker bucket kinds, so that the filter specification can
// derive the key of a title unambiguously: no filter, a number bucket, a symbol bucket, or a single ASCII letter.
RuleFor(query => query.FilterAlphaKey)
.Must(alphaKey => alphaKey is null
|| alphaKey == LibraryItemAlphaKeys.NUMBER
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
@@ -8,7 +7,9 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Query for checking the reading availability of a book.
/// </summary>
/// <param name="BookId">The Id of the book whose reading availability is checked.</param>
/// <param name="LibraryId">The unique identifier of the media library the book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book whose reading availability is checked, taken from the route.</param>
public record GetReadingAvailabilityQuery(
Guid BookId
string? LibraryId,
string? BookId
) : IQuery;
@@ -68,22 +68,31 @@ public class GetReadingAvailabilityQueryHandler : IQueryHandler<GetReadingAvaila
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(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.Reading.BookNotFound;
BookEntity book = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (book.LibraryId != libraryId)
return DomainErrors.Reading.BookNotFound;
// Admins can read the books of any library; for everyone else, only their own libraries.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
@@ -17,8 +17,24 @@ public class GetReadingAvailabilityQueryValidator : AbstractValidator<GetReading
/// </summary>
public GetReadingAvailabilityQueryValidator()
{
// Validates the identifier of the media library the book belongs to, 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);
// Validates the identifier of the book whose reading availability is checked, taken from the route.
RuleFor(query => query.BookId)
.NotEmpty()
.WithError(Errors.Reading.BookIdCannotBeEmpty);
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(query => query.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(query => query.BookId is not null && query.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
@@ -8,7 +7,9 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Query for getting the reading manifest of a book.
/// </summary>
/// <param name="BookId">The Id of the book whose reading manifest is retrieved.</param>
/// <param name="LibraryId">The unique identifier of the media library the book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book whose reading manifest is retrieved, taken from the route.</param>
public record GetReadingManifestQuery(
Guid BookId
string? LibraryId,
string? BookId
) : IQuery;
@@ -69,22 +69,31 @@ public class GetReadingManifestQueryHandler : IQueryHandler<GetReadingManifestQu
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(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.Reading.BookNotFound;
BookEntity book = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (book.LibraryId != libraryId)
return DomainErrors.Reading.BookNotFound;
// Admins can read the books of any library; for everyone else, only their own libraries.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
@@ -17,8 +17,24 @@ public class GetReadingManifestQueryValidator : AbstractValidator<GetReadingMani
/// </summary>
public GetReadingManifestQueryValidator()
{
// Validates the identifier of the media library the book belongs to, 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);
// Validates the identifier of the book whose reading manifest is retrieved, taken from the route.
RuleFor(query => query.BookId)
.NotEmpty()
.WithError(Errors.Reading.BookIdCannotBeEmpty);
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(query => query.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(query => query.BookId is not null && query.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
@@ -8,9 +7,11 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Query for getting a resource of a book, for reading.
/// </summary>
/// <param name="BookId">The Id of the book whose resource is retrieved.</param>
/// <param name="ResourceKey">The opaque resource key of the resource.</param>
/// <param name="LibraryId">The unique identifier of the media library the book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book whose resource is retrieved, taken from the route.</param>
/// <param name="ResourceKey">The opaque resource key of the resource, taken from the route.</param>
public record GetReadingResourceQuery(
Guid BookId,
string ResourceKey
string? LibraryId,
string? BookId,
string? ResourceKey
) : IQuery;
@@ -69,21 +69,30 @@ public class GetReadingResourceQueryHandler : IQueryHandler<GetReadingResourceQu
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(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.Reading.BookNotFound;
BookEntity book = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (book.LibraryId != libraryId)
return DomainErrors.Reading.BookNotFound;
// Admins can read the books of any library; for everyone else, only their own libraries.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
@@ -97,6 +106,6 @@ public class GetReadingResourceQueryHandler : IQueryHandler<GetReadingResourceQu
return getSettingsResult.Errors;
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
return await _bookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
return await _bookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey!, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
}
}
@@ -17,10 +17,27 @@ public class GetReadingResourceQueryValidator : AbstractValidator<GetReadingReso
/// </summary>
public GetReadingResourceQueryValidator()
{
// Validates the identifier of the media library the book belongs to, 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);
// Validates the identifier of the book whose resource is retrieved, taken from the route.
RuleFor(query => query.BookId)
.NotEmpty()
.WithError(Errors.Reading.BookIdCannotBeEmpty);
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(query => query.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(query => query.BookId is not null && query.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
// Validates the opaque resource key of the resource, taken from the route.
RuleFor(query => query.ResourceKey)
.NotEmpty()
.WithError(Errors.Reading.ResourceKeyCannotBeEmpty);
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
@@ -8,9 +7,11 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Query for getting the content of a reading section of a book.
/// </summary>
/// <param name="BookId">The Id of the book whose reading section is retrieved.</param>
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
/// <param name="LibraryId">The unique identifier of the media library the book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book whose reading section is retrieved, taken from the route.</param>
/// <param name="LocationRef">The opaque location reference of the reading section, taken from the route.</param>
public record GetReadingSectionQuery(
Guid BookId,
string LocationRef
string? LibraryId,
string? BookId,
string? LocationRef
) : IQuery;
@@ -69,22 +69,31 @@ public class GetReadingSectionQueryHandler : IQueryHandler<GetReadingSectionQuer
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(query.LibraryId!);
Guid bookId = Guid.Parse(query.BookId!);
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.Reading.BookNotFound;
BookEntity book = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (book.LibraryId != libraryId)
return DomainErrors.Reading.BookNotFound;
// Admins can read the books of any library; for everyone else, only their own libraries.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
@@ -100,6 +109,6 @@ public class GetReadingSectionQueryHandler : IQueryHandler<GetReadingSectionQuer
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
bool shouldPreserveStyles = getSettingsResult.Value is null || getSettingsResult.Value.ShouldPreserveBookStyles;
return await _bookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages, shouldPreserveStyles, cancellationToken).ConfigureAwait(false);
return await _bookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef!, shouldRenderPdfAsImages, shouldPreserveStyles, cancellationToken).ConfigureAwait(false);
}
}
@@ -17,10 +17,27 @@ public class GetReadingSectionQueryValidator : AbstractValidator<GetReadingSecti
/// </summary>
public GetReadingSectionQueryValidator()
{
// Validates the identifier of the media library the book belongs to, 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);
// Validates the identifier of the book whose reading section is retrieved, taken from the route.
RuleFor(query => query.BookId)
.NotEmpty()
.WithError(Errors.Reading.BookIdCannotBeEmpty);
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(query => query.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(query => query.BookId is not null && query.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
// Validates the opaque location reference of the reading section, taken from the route.
RuleFor(query => query.LocationRef)
.NotEmpty()
.WithError(Errors.Reading.LocationRefCannotBeEmpty);
@@ -97,7 +97,9 @@ public class SetLibraryBookReaderEnabledCommandHandler : ICommandHandler<SetLibr
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return upsertResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// The reading service caches the enablement of a reader, because it consults it on every request; the cache is invalidated here,
// so that disabling a reader cuts access to its books immediately, without waiting for the cache to expire.
_enablementCache.Invalidate(command.LibraryId, command.PluginId);
@@ -2,6 +2,8 @@
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
@@ -79,10 +81,10 @@ public class GetLibraryBookReadersQueryHandler : IQueryHandler<GetLibraryBookRea
return getConfigurationsResult.Errors;
// Build a plugin name lookup from the detected plugins.
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
Result<PaginatedResultDto<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPluginsResult.IsFailure)
return getPluginsResult.Errors;
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
IReadOnlyDictionary<Guid, IReadOnlyList<string>> supportedExtensionsByPluginId = _bookReaderRegistry.GetSupportedExtensionsByPluginId();