mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 09:11:10 +00:00
Refactors the add and update album and track slices across the stack
This commit is contained in:
1 parent
ea6eb9f796
commit
54cae054c1
30 files changed
+846
-325
No files matched your search
+25
-3
@@ -83,6 +83,28 @@ public static class AddAlbumCommandMapping
|
||||
musicBrainzReleaseArtistId = musicBrainzReleaseArtistIdResult.Value;
|
||||
}
|
||||
|
||||
List<MusicMediaContributor> contributors = [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)];
|
||||
List<AudioRating> ratings = [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)];
|
||||
List<Track> tracks = [.. domainTracksResult.Select(trackResult => trackResult.Value)];
|
||||
|
||||
// An album carries an Id only when it already exists; otherwise a new one is minted. The repository preserves the stored
|
||||
// creation audit when it merges an existing album, so a transient value is used here.
|
||||
if (command.AlbumId.HasValue)
|
||||
return Album.Create(
|
||||
AlbumId.Create(command.AlbumId.Value),
|
||||
metadataResult.Value,
|
||||
Optional<MusicMediaFormat>.FromNullable(command.MediaFormat),
|
||||
barcode,
|
||||
Optional<string>.FromNullable(command.CatalogNumber),
|
||||
musicBrainzReleaseId,
|
||||
musicBrainzReleaseGroupId,
|
||||
musicBrainzReleaseArtistId,
|
||||
contributors,
|
||||
ratings,
|
||||
tracks,
|
||||
DateTime.UtcNow,
|
||||
Optional<DateTime>.None());
|
||||
|
||||
return Album.Create(
|
||||
metadataResult.Value,
|
||||
Optional<MusicMediaFormat>.FromNullable(command.MediaFormat),
|
||||
@@ -91,9 +113,9 @@ public static class AddAlbumCommandMapping
|
||||
musicBrainzReleaseId,
|
||||
musicBrainzReleaseGroupId,
|
||||
musicBrainzReleaseArtistId,
|
||||
[.. domainContributorsResult.Select(contributorResult => contributorResult.Value)],
|
||||
[.. domainRatingsResult.Select(ratingResult => ratingResult.Value)],
|
||||
[.. domainTracksResult.Select(trackResult => trackResult.Value)]);
|
||||
contributors,
|
||||
ratings,
|
||||
tracks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+3
-2
@@ -72,8 +72,9 @@ public static class AlbumMapping
|
||||
Tracks = [.. domainEntity.Tracks.Select(track => track.ToRepositoryEntity(domainEntity.Id.Value, libraryId))],
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
|
||||
UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : null
|
||||
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
+15
-15
@@ -1,11 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaContributors;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
@@ -21,25 +20,25 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibra
|
||||
public static class UpdateAlbumCommandMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="command"/> to a domain <see cref="Album"/>, preserving the identity and creation metadata of the stored album identified by <paramref name="existingAlbum"/>.
|
||||
/// Applies the editable data of <paramref name="command"/> to the album of <paramref name="artist"/> identified by the command, through the aggregate root.
|
||||
/// </summary>
|
||||
/// <param name="command">The command whose data is used to create the album.</param>
|
||||
/// <param name="existingAlbum">The stored album whose identity and creation metadata are preserved.</param>
|
||||
/// <param name="command">The command whose data is applied to the album.</param>
|
||||
/// <param name="artist">The artist aggregate that owns the album.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Album"/>, or an error message.
|
||||
/// An <see cref="Result{TValue}"/> containing either the successfully updated <see cref="Artist"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Album> ToDomainEntity(this UpdateAlbumCommand command, AlbumEntity existingAlbum)
|
||||
public static Result<Artist> ToDomainEntity(this UpdateAlbumCommand command, Artist artist)
|
||||
{
|
||||
Result<AlbumMetadata> metadataResult = command.Metadata!.ToDomainEntity();
|
||||
if (metadataResult.IsFailure)
|
||||
return metadataResult.Errors;
|
||||
|
||||
IEnumerable<Result<MusicMediaContributor>> domainContributorsResult = (command.Contributors ?? []).ToMusicDomainEntities();
|
||||
IEnumerable<Result<MusicMediaContributor>> domainContributorsResult = command.Contributors!.ToMusicDomainEntities();
|
||||
List<Error> errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)];
|
||||
if (errors.Count > 0)
|
||||
return errors;
|
||||
|
||||
IEnumerable<Result<AudioRating>> domainRatingsResult = (command.Ratings ?? []).ToDomainEntities();
|
||||
IEnumerable<Result<AudioRating>> domainRatingsResult = command.Ratings!.ToDomainEntities();
|
||||
errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)];
|
||||
if (errors.Count > 0)
|
||||
return errors;
|
||||
@@ -78,8 +77,8 @@ public static class UpdateAlbumCommandMapping
|
||||
musicBrainzReleaseArtistId = musicBrainzReleaseArtistIdResult.Value;
|
||||
}
|
||||
|
||||
return Album.Create(
|
||||
AlbumId.Create(existingAlbum.Id),
|
||||
Result<Updated> updateResult = artist.UpdateAlbum(
|
||||
AlbumId.Create(Guid.Parse(command.AlbumId!)),
|
||||
metadataResult.Value,
|
||||
Optional<MusicMediaFormat>.FromNullable(command.MediaFormat),
|
||||
barcode,
|
||||
@@ -88,9 +87,10 @@ public static class UpdateAlbumCommandMapping
|
||||
musicBrainzReleaseGroupId,
|
||||
musicBrainzReleaseArtistId,
|
||||
[.. domainContributorsResult.Select(contributorResult => contributorResult.Value)],
|
||||
[.. domainRatingsResult.Select(ratingResult => ratingResult.Value)],
|
||||
[],
|
||||
existingAlbum.CreatedOnUtc,
|
||||
Optional<DateTime>.FromNullable(existingAlbum.UpdatedOnUtc));
|
||||
[.. domainRatingsResult.Select(ratingResult => ratingResult.Value)]);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
return artist;
|
||||
}
|
||||
}
|
||||
+29
-4
@@ -77,22 +77,47 @@ public static class AddTrackCommandMapping
|
||||
musicBrainzWorkId = musicBrainzWorkIdResult.Value;
|
||||
}
|
||||
|
||||
List<Isrc> isrcs = [.. domainIsrcsResult.Select(isrcResult => isrcResult.Value)];
|
||||
List<Mood> moods = [.. domainMoodsResult.Select(moodResult => moodResult.Value)];
|
||||
List<MusicMediaContributor> contributors = [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)];
|
||||
List<AudioRating> ratings = [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)];
|
||||
|
||||
// A track carries an Id only when it already exists; otherwise a new one is minted.
|
||||
if (command.TrackId.HasValue)
|
||||
return Track.Create(
|
||||
TrackId.Create(command.TrackId.Value),
|
||||
command.Path!,
|
||||
metadataResult.Value,
|
||||
command.TrackNumber ?? 1,
|
||||
Optional<int>.FromNullable(command.DiscNumber),
|
||||
isrcs,
|
||||
Optional<string>.FromNullable(command.Script),
|
||||
Optional<MusicKey>.FromNullable(command.Key),
|
||||
Optional<int>.FromNullable(command.Bpm),
|
||||
moods,
|
||||
Optional<string>.FromNullable(command.Work),
|
||||
musicBrainzRecordingId,
|
||||
musicBrainzTrackId,
|
||||
musicBrainzWorkId,
|
||||
contributors,
|
||||
ratings);
|
||||
|
||||
return Track.Create(
|
||||
command.Path!,
|
||||
metadataResult.Value,
|
||||
command.TrackNumber ?? 1,
|
||||
Optional<int>.FromNullable(command.DiscNumber),
|
||||
[.. domainIsrcsResult.Select(isrcResult => isrcResult.Value)],
|
||||
isrcs,
|
||||
Optional<string>.FromNullable(command.Script),
|
||||
Optional<MusicKey>.FromNullable(command.Key),
|
||||
Optional<int>.FromNullable(command.Bpm),
|
||||
[.. domainMoodsResult.Select(moodResult => moodResult.Value)],
|
||||
moods,
|
||||
Optional<string>.FromNullable(command.Work),
|
||||
musicBrainzRecordingId,
|
||||
musicBrainzTrackId,
|
||||
musicBrainzWorkId,
|
||||
[.. domainContributorsResult.Select(contributorResult => contributorResult.Value)],
|
||||
[.. domainRatingsResult.Select(ratingResult => ratingResult.Value)]);
|
||||
contributors,
|
||||
ratings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+29
-13
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaContributors;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
@@ -6,11 +7,13 @@ using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
@@ -21,21 +24,29 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibra
|
||||
public static class UpdateTrackCommandMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="command"/> to a domain <see cref="Track"/>, preserving the provided <paramref name="id"/>.
|
||||
/// Applies the editable data of <paramref name="command"/> to the track of <paramref name="artist"/> identified by the command, through the aggregate root.
|
||||
/// </summary>
|
||||
/// <param name="command">The command whose data is used to create the track.</param>
|
||||
/// <param name="id">The unique identifier of the track.</param>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="ratings">The list of ratings of the track.</param>
|
||||
/// <param name="command">The command whose data is applied to the track.</param>
|
||||
/// <param name="artist">The artist aggregate that owns the track.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Track"/>, or an error message.
|
||||
/// An <see cref="Result{TValue}"/> containing either the successfully updated <see cref="Artist"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Track> ToDomainEntity(this UpdateTrackCommand command, TrackId id, Guid libraryId, List<AudioRating> ratings)
|
||||
public static Result<Artist> ToDomainEntity(this UpdateTrackCommand command, Artist artist)
|
||||
{
|
||||
Result<AudioMetadata> metadataResult = command.Metadata!.ToDomainEntity();
|
||||
if (metadataResult.IsFailure)
|
||||
return metadataResult.Errors;
|
||||
|
||||
IEnumerable<Result<MusicMediaContributor>> domainContributorsResult = command.Contributors!.ToMusicDomainEntities();
|
||||
List<Error> errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)];
|
||||
if (errors.Count > 0)
|
||||
return errors;
|
||||
|
||||
IEnumerable<Result<AudioRating>> domainRatingsResult = command.Ratings!.ToDomainEntities();
|
||||
errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)];
|
||||
if (errors.Count > 0)
|
||||
return errors;
|
||||
|
||||
Optional<MusicBrainzId> musicBrainzRecordingId = Optional<MusicBrainzId>.None();
|
||||
if (command.MusicBrainzRecordingId is not null)
|
||||
{
|
||||
@@ -79,22 +90,27 @@ public static class UpdateTrackCommandMapping
|
||||
domainMoods.Add(moodResult.Value);
|
||||
}
|
||||
|
||||
return Track.Create(
|
||||
id,
|
||||
Result<Updated> updateResult = artist.UpdateTrackInAlbum(
|
||||
AlbumId.Create(Guid.Parse(command.AlbumId!)),
|
||||
TrackId.Create(Guid.Parse(command.TrackId!)),
|
||||
command.Path!,
|
||||
metadataResult.Value,
|
||||
command.TrackNumber ?? 1,
|
||||
Optional<int>.FromNullable(command.DiscNumber),
|
||||
domainIsrcs,
|
||||
Optional<string>.FromNullable(command.Script),
|
||||
Optional<MusicKey>.FromNullable(command.Key),
|
||||
Optional<int>.FromNullable(command.Bpm),
|
||||
domainMoods,
|
||||
Optional<string>.FromNullable(command.Work),
|
||||
musicBrainzRecordingId,
|
||||
musicBrainzTrackId,
|
||||
musicBrainzWorkId,
|
||||
[],
|
||||
ratings);
|
||||
[.. domainContributorsResult.Select(contributorResult => contributorResult.Value)],
|
||||
[.. domainRatingsResult.Select(ratingResult => ratingResult.Value)],
|
||||
domainMoods,
|
||||
domainIsrcs);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
return artist;
|
||||
}
|
||||
}
|
||||
+1
@@ -37,6 +37,7 @@ public static class UpdateTrackRequestMapping
|
||||
request.MusicBrainzRecordingId,
|
||||
request.MusicBrainzTrackId,
|
||||
request.MusicBrainzWorkId,
|
||||
request.Contributors,
|
||||
request.Ratings,
|
||||
request.Moods,
|
||||
request.Isrcs);
|
||||
|
||||
+2
-1
@@ -40,5 +40,6 @@ public record AddAlbumCommand(
|
||||
Guid? MusicBrainzReleaseArtistId,
|
||||
List<MediaContributorReferenceDto>? Contributors,
|
||||
List<AudioRatingDto>? Ratings,
|
||||
List<AddTrackCommand>? Tracks
|
||||
List<AddTrackCommand>? Tracks,
|
||||
Guid? AlbumId = null
|
||||
) : ICommand;
|
||||
+30
-22
@@ -9,10 +9,12 @@ 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.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
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;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using System;
|
||||
@@ -78,20 +80,8 @@ public class AddAlbumCommandHandler : ICommandHandler<AddAlbumCommand, Result<Al
|
||||
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);
|
||||
// An album is a child of the artist aggregate, so the whole aggregate is loaded and the album is added within it.
|
||||
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getArtistResult.IsFailure)
|
||||
return getArtistResult.Errors;
|
||||
if (getArtistResult.Value is null)
|
||||
@@ -103,6 +93,19 @@ public class AddAlbumCommandHandler : ICommandHandler<AddAlbumCommand, Result<Al
|
||||
if (existingArtist.LibraryId != libraryId)
|
||||
return DomainErrors.Music.ArtistNotFound;
|
||||
|
||||
// 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(existingArtist.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;
|
||||
|
||||
// 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))
|
||||
@@ -113,22 +116,27 @@ public class AddAlbumCommandHandler : ICommandHandler<AddAlbumCommand, Result<Al
|
||||
if (getContributorsResult.IsFailure)
|
||||
return getContributorsResult.Errors;
|
||||
|
||||
// The write path goes through the aggregate root: an album is a child entity of the artist aggregate, unlike Book and Artist,
|
||||
// which are aggregate roots and are created directly with their own Create method. This difference is intentional.
|
||||
Result<Artist> artistResult = existingArtist.ToDomainEntity();
|
||||
if (artistResult.IsFailure)
|
||||
return artistResult.Errors;
|
||||
|
||||
Result<Album> createAlbumResult = command.ToDomainEntity();
|
||||
if (createAlbumResult.IsFailure)
|
||||
return createAlbumResult.Errors;
|
||||
Result<Created> addAlbumResult = artistResult.Value.AddAlbum(createAlbumResult.Value);
|
||||
if (addAlbumResult.IsFailure)
|
||||
return addAlbumResult.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<Updated> updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), 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 album as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the database applied on save.
|
||||
// Reading does not need the aggregate: the album is read directly and mapped to the response.
|
||||
Result<AlbumEntity?> getPersistedAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(createAlbumResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPersistedAlbumResult.IsFailure)
|
||||
return getPersistedAlbumResult.Errors;
|
||||
|
||||
+29
-19
@@ -207,6 +207,16 @@ public class AddAlbumCommandValidator : AbstractValidator<AddAlbumCommand>
|
||||
.When(command => command.CatalogNumber is not null)
|
||||
.WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong);
|
||||
|
||||
RuleFor(command => command.Barcode)
|
||||
.NotEmpty()
|
||||
.When(command => command.Barcode is not null)
|
||||
.WithError(Errors.Music.BarcodeValueCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.Barcode)
|
||||
.Matches(@"^\d{12,13}$")
|
||||
.When(command => command.Barcode is not null && command.Barcode.Length > 0)
|
||||
.WithError(Errors.Music.InvalidFormatForBarcode);
|
||||
|
||||
RuleFor(command => command.MusicBrainzReleaseId)
|
||||
.Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty)
|
||||
.When(command => command.MusicBrainzReleaseId.HasValue)
|
||||
@@ -222,6 +232,25 @@ public class AddAlbumCommandValidator : AbstractValidator<AddAlbumCommand>
|
||||
.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()
|
||||
@@ -246,25 +275,6 @@ public class AddAlbumCommandValidator : AbstractValidator<AddAlbumCommand>
|
||||
.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()
|
||||
|
||||
+28
-16
@@ -12,6 +12,7 @@ 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.Artists;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
@@ -21,6 +22,7 @@ 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;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
@@ -85,21 +87,23 @@ public class UpdateAlbumCommandHandler : ICommandHandler<UpdateAlbumCommand, Res
|
||||
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;
|
||||
// An album is a child of the artist aggregate, so the whole aggregate is loaded and the album is edited within it.
|
||||
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getArtistResult.IsFailure)
|
||||
return getArtistResult.Errors;
|
||||
|
||||
// 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)
|
||||
if (getArtistResult.Value is null || getArtistResult.Value.LibraryId != libraryId)
|
||||
return Errors.Music.AlbumNotFound;
|
||||
ArtistEntity existingArtist = getArtistResult.Value;
|
||||
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
|
||||
if (existingAlbum is null)
|
||||
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);
|
||||
userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
@@ -115,23 +119,31 @@ public class UpdateAlbumCommandHandler : ICommandHandler<UpdateAlbumCommand, Res
|
||||
if (getContributorsResult.IsFailure)
|
||||
return getContributorsResult.Errors;
|
||||
|
||||
Result<Album> updateAlbumResult = command.ToDomainEntity(existingAlbum);
|
||||
// The write path goes through the aggregate root: an album is a child entity of the artist aggregate, unlike Book and Artist,
|
||||
// which are aggregate roots and are reconstituted directly with their own Create method. This difference is intentional.
|
||||
Result<Artist> artistResult = existingArtist.ToDomainEntity();
|
||||
if (artistResult.IsFailure)
|
||||
return artistResult.Errors;
|
||||
|
||||
Result<Artist> updateAlbumResult = command.ToDomainEntity(artistResult.Value);
|
||||
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);
|
||||
Result<Updated> updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(updateAlbumResult.Value.ToRepositoryEntity(), 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();
|
||||
// Reading does not need the aggregate: the album is read directly and mapped to the response.
|
||||
Result<AlbumEntity?> getPersistedAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPersistedAlbumResult.IsFailure)
|
||||
return getPersistedAlbumResult.Errors;
|
||||
if (getPersistedAlbumResult.Value is null)
|
||||
return Errors.Music.AlbumNotFound;
|
||||
|
||||
return getPersistedAlbumResult.Value.ToResponse();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+31
-21
@@ -47,7 +47,7 @@ public class UpdateAlbumCommandValidator : AbstractValidator<UpdateAlbumCommand>
|
||||
.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.
|
||||
// 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)
|
||||
@@ -70,6 +70,26 @@ public class UpdateAlbumCommandValidator : AbstractValidator<UpdateAlbumCommand>
|
||||
.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)
|
||||
@@ -184,26 +204,6 @@ public class UpdateAlbumCommandValidator : AbstractValidator<UpdateAlbumCommand>
|
||||
.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.
|
||||
@@ -217,6 +217,16 @@ public class UpdateAlbumCommandValidator : AbstractValidator<UpdateAlbumCommand>
|
||||
.When(command => command.CatalogNumber is not null)
|
||||
.WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong);
|
||||
|
||||
RuleFor(command => command.Barcode)
|
||||
.NotEmpty()
|
||||
.When(command => command.Barcode is not null)
|
||||
.WithError(Errors.Music.BarcodeValueCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.Barcode)
|
||||
.Matches(@"^\d{12,13}$")
|
||||
.When(command => command.Barcode is not null && command.Barcode.Length > 0)
|
||||
.WithError(Errors.Music.InvalidFormatForBarcode);
|
||||
|
||||
RuleFor(command => command.MusicBrainzReleaseId)
|
||||
.Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty)
|
||||
.When(command => command.MusicBrainzReleaseId.HasValue)
|
||||
|
||||
+2
-1
@@ -52,5 +52,6 @@ public record AddTrackCommand(
|
||||
List<MoodDto>? Moods,
|
||||
List<IsrcDto>? Isrcs,
|
||||
List<MediaContributorReferenceDto>? Contributors,
|
||||
List<AudioRatingDto>? Ratings
|
||||
List<AudioRatingDto>? Ratings,
|
||||
Guid? TrackId = null
|
||||
) : ICommand;
|
||||
+28
-18
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
|
||||
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.Artists;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
@@ -22,6 +23,7 @@ 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;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
@@ -90,9 +92,20 @@ public class AddTrackCommandHandler : ICommandHandler<AddTrackCommand, Result<Tr
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
|
||||
// A track is a child of the artist aggregate, so the whole aggregate is loaded and the track is added within it.
|
||||
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getArtistResult.IsFailure)
|
||||
return getArtistResult.Errors;
|
||||
if (getArtistResult.Value is null || getArtistResult.Value.LibraryId != libraryId)
|
||||
return Errors.Music.AlbumNotFound;
|
||||
ArtistEntity existingArtist = getArtistResult.Value;
|
||||
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
|
||||
if (existingAlbum is null)
|
||||
return Errors.Music.AlbumNotFound;
|
||||
|
||||
// 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);
|
||||
userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
@@ -103,17 +116,6 @@ public class AddTrackCommandHandler : ICommandHandler<AddTrackCommand, Result<Tr
|
||||
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))
|
||||
@@ -124,20 +126,28 @@ public class AddTrackCommandHandler : ICommandHandler<AddTrackCommand, Result<Tr
|
||||
if (getContributorsResult.IsFailure)
|
||||
return getContributorsResult.Errors;
|
||||
|
||||
// The write path goes through the aggregate root: a track is a child entity of the artist aggregate, unlike Book and Artist,
|
||||
// which are aggregate roots and are created directly with their own Create method. This difference is intentional.
|
||||
Result<Artist> artistResult = existingArtist.ToDomainEntity();
|
||||
if (artistResult.IsFailure)
|
||||
return artistResult.Errors;
|
||||
|
||||
Result<Track> createTrackResult = command.ToDomainEntity();
|
||||
if (createTrackResult.IsFailure)
|
||||
return createTrackResult.Errors;
|
||||
Result<Created> addTrackResult = artistResult.Value.AddTrackToAlbum(AlbumId.Create(albumId), createTrackResult.Value);
|
||||
if (addTrackResult.IsFailure)
|
||||
return addTrackResult.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<Updated> updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), 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 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);
|
||||
// Reading does not need the aggregate: the track is read directly and mapped to the response.
|
||||
Result<TrackEntity?> getPersistedTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(createTrackResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPersistedTrackResult.IsFailure)
|
||||
return getPersistedTrackResult.Errors;
|
||||
if (getPersistedTrackResult.Value is null)
|
||||
|
||||
+3
@@ -1,6 +1,7 @@
|
||||
#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;
|
||||
@@ -29,6 +30,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.
|
||||
/// <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="Contributors">The list of media contributors that performed on the track.</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>
|
||||
@@ -49,6 +51,7 @@ public record UpdateTrackCommand(
|
||||
Guid? MusicBrainzRecordingId,
|
||||
Guid? MusicBrainzTrackId,
|
||||
Guid? MusicBrainzWorkId,
|
||||
List<MediaContributorReferenceDto>? Contributors,
|
||||
List<AudioRatingDto>? Ratings,
|
||||
List<MoodDto>? Moods,
|
||||
List<IsrcDto>? Isrcs
|
||||
|
||||
+33
-39
@@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
|
||||
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.Artists;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
@@ -20,12 +21,14 @@ 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;
|
||||
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;
|
||||
@@ -84,31 +87,27 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
|
||||
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;
|
||||
// A track is a child of the artist aggregate, so the whole aggregate is loaded and the track is edited within it.
|
||||
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getArtistResult.IsFailure)
|
||||
return getArtistResult.Errors;
|
||||
|
||||
// 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)
|
||||
// Resource scoping: the track must belong to the library, the artist and the album named by the route, so that a track can never be
|
||||
// edited through another library's, artist's or album's route; the mismatch is reported as not found.
|
||||
if (getArtistResult.Value is null || getArtistResult.Value.LibraryId != libraryId)
|
||||
return Errors.Music.TrackNotFound;
|
||||
ArtistEntity existingArtist = getArtistResult.Value;
|
||||
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
|
||||
TrackEntity? existingTrack = existingAlbum?.Tracks.FirstOrDefault(track => track.Id == trackId);
|
||||
if (existingTrack is null)
|
||||
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);
|
||||
userId, new LibraryOwnershipPolicyContext(existingArtist.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)
|
||||
@@ -116,35 +115,30 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
|
||||
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;
|
||||
// The write path goes through the aggregate root: a track is a child entity of the artist aggregate, unlike Book and Artist,
|
||||
// which are aggregate roots and are reconstituted directly with their own Create method. This difference is intentional.
|
||||
Result<Artist> artistResult = existingArtist.ToDomainEntity();
|
||||
if (artistResult.IsFailure)
|
||||
return artistResult.Errors;
|
||||
|
||||
Result<Track> updatedTrackResult = command.ToDomainEntity(TrackId.Create(existingTrack.Id), existingTrack.LibraryId, domainRatings);
|
||||
if (updatedTrackResult.IsFailure)
|
||||
return updatedTrackResult.Errors;
|
||||
Result<Artist> updatedArtistResult = command.ToDomainEntity(artistResult.Value);
|
||||
if (updatedArtistResult.IsFailure)
|
||||
return updatedArtistResult.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);
|
||||
Result<Updated> updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(updatedArtistResult.Value.ToRepositoryEntity(), 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();
|
||||
// Reading does not need the aggregate: the track is read directly and mapped to the response.
|
||||
Result<TrackEntity?> getPersistedTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(trackId, 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();
|
||||
}
|
||||
}
|
||||
+19
@@ -248,6 +248,25 @@ public class UpdateTrackCommandValidator : AbstractValidator<UpdateTrackCommand>
|
||||
.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()
|
||||
|
||||
Reference in new issue
Block a user