mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 16: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()
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Album
|
||||
/// <param name="MusicBrainzReleaseId">The MusicBrainz identifier of the release. Optional.</param>
|
||||
/// <param name="MusicBrainzReleaseGroupId">The MusicBrainz identifier of the release group. Optional.</param>
|
||||
/// <param name="MusicBrainzReleaseArtistId">The MusicBrainz identifier of the release artist. Optional.</param>
|
||||
/// <param name="Contributors">The list of media contributors that performed on the album. Optional.</param>
|
||||
/// <param name="Contributors">The list of media contributors that performed on the album. Required.</param>
|
||||
/// <param name="Ratings">The list of ratings for this album. Required.</param>
|
||||
[DebuggerDisplay("Title: {Metadata.Title}")]
|
||||
public record UpdateAlbumRequest(
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Track
|
||||
/// <param name="MusicBrainzRecordingId">The MusicBrainz identifier of the recording. Optional.</param>
|
||||
/// <param name="MusicBrainzTrackId">The MusicBrainz identifier of the track. Optional.</param>
|
||||
/// <param name="MusicBrainzWorkId">The MusicBrainz identifier of the work. Optional.</param>
|
||||
/// <param name="Contributors">The list of media contributors that performed on the track. Optional.</param>
|
||||
/// <param name="Contributors">The list of media contributors that performed on the track. Required.</param>
|
||||
/// <param name="Ratings">The list of ratings for this track. Required.</param>
|
||||
/// <param name="Moods">The list of moods of the track. Optional.</param>
|
||||
/// <param name="Isrcs">The list of ISRC (International Standard Recording Code) of the track. Optional.</param>
|
||||
|
||||
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -75,56 +76,89 @@ internal sealed class AlbumRepository : IAlbumRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing album, replacing its editable data while preserving its identity and audit columns.
|
||||
/// Updates an existing album, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns.
|
||||
/// </summary>
|
||||
/// <param name="album">The album whose editable data is applied to the stored album.</param>
|
||||
/// <param name="data">The album whose editable data is applied to the stored album.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> UpdateAsync(AlbumEntity album, CancellationToken cancellationToken)
|
||||
public async Task<Result<Updated>> UpdateAsync(AlbumEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
AlbumEntity? foundAlbum = await _luminaDbContext.Albums
|
||||
.Include(repositoryAlbum => repositoryAlbum.Tags)
|
||||
.Include(repositoryAlbum => repositoryAlbum.Genres)
|
||||
.Include(repositoryAlbum => repositoryAlbum.Ratings)
|
||||
.Include(repositoryAlbum => repositoryAlbum.Contributors)
|
||||
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == album.Id, cancellationToken).ConfigureAwait(false);
|
||||
.FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == data.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (foundAlbum is null)
|
||||
return Errors.Music.AlbumNotFound;
|
||||
|
||||
// The stored identity and audit columns are never overwritten by an edit.
|
||||
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
|
||||
Guid artistId = foundAlbum.ArtistId;
|
||||
Guid libraryId = foundAlbum.LibraryId;
|
||||
DateTime createdOnUtc = foundAlbum.CreatedOnUtc;
|
||||
Guid createdBy = foundAlbum.CreatedBy;
|
||||
|
||||
// Copy the editable scalar properties of the album, ignoring the unchanged collection columns.
|
||||
_luminaDbContext.Entry(foundAlbum).CurrentValues.SetValues(album);
|
||||
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundAlbum, data);
|
||||
foundAlbum.ArtistId = artistId;
|
||||
foundAlbum.LibraryId = libraryId;
|
||||
foundAlbum.CreatedOnUtc = createdOnUtc;
|
||||
foundAlbum.CreatedBy = createdBy;
|
||||
|
||||
// Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated.
|
||||
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
|
||||
.Where(tag => album.Tags.Select(albumTag => albumTag.Name).Contains(tag.Name))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
|
||||
.Where(genre => album.Genres.Select(albumGenre => albumGenre.Name).Contains(genre.Name))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
await ReconcileTagsAndGenresAsync(foundAlbum, data, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
foundAlbum.Tags.Clear();
|
||||
foundAlbum.Tags.UnionWith(album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
|
||||
foundAlbum.Genres.Clear();
|
||||
foundAlbum.Genres.UnionWith(album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
|
||||
// Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change
|
||||
// are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the album.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundAlbum.Ratings,
|
||||
data.Ratings,
|
||||
existingRating => existingRating.Source?.ToString() ?? string.Empty,
|
||||
incomingRating => incomingRating.Source?.ToString() ?? string.Empty,
|
||||
shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating),
|
||||
createNew: incomingRating => incomingRating);
|
||||
|
||||
// Replace the owned ratings and contributors collections of the album, so that removed entries are deleted and new entries are inserted.
|
||||
foundAlbum.Ratings.Clear();
|
||||
foundAlbum.Ratings.AddRange(album.Ratings);
|
||||
foundAlbum.Contributors.Clear();
|
||||
foundAlbum.Contributors.AddRange(album.Contributors);
|
||||
// A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a
|
||||
// contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another album of the same artist was edited.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundAlbum.Contributors,
|
||||
data.Contributors,
|
||||
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
|
||||
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
|
||||
shouldReplace: (existingContributor, incomingContributor) => false,
|
||||
createNew: incomingContributor => incomingContributor);
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconciles the tags and genres of <paramref name="foundAlbum"/> against the ones carried by <paramref name="data"/>, reusing the stored tags and genres whose names already exist.
|
||||
/// </summary>
|
||||
/// <param name="foundAlbum">The tracked album whose tags and genres are reconciled.</param>
|
||||
/// <param name="data">The album carrying the desired tags and genres.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task ReconcileTagsAndGenresAsync(AlbumEntity foundAlbum, AlbumEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
// Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted.
|
||||
List<string> tagNames = [.. data.Tags.Select(tag => tag.Name!)];
|
||||
List<string> genreNames = [.. data.Genres.Select(genre => genre.Name!)];
|
||||
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
|
||||
.Where(tag => tagNames.Contains(tag.Name!))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
|
||||
.Where(genre => genreNames.Contains(genre.Name!))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundAlbum.Tags,
|
||||
data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag),
|
||||
existingTag => existingTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (existingTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundAlbum.Genres,
|
||||
data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre),
|
||||
existingGenre => existingGenre.Name!,
|
||||
incomingGenre => incomingGenre.Name!,
|
||||
shouldReplace: (existingGenre, incomingGenre) => false,
|
||||
createNew: incomingGenre => incomingGenre);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an album by its Id.
|
||||
/// </summary>
|
||||
|
||||
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -25,14 +26,20 @@ namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
internal sealed class ArtistRepository : IArtistRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
private readonly IAlbumRepository _albumRepository;
|
||||
private readonly ITrackRepository _trackRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ArtistRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public ArtistRepository(LuminaDbContext luminaDbContext)
|
||||
/// <param name="albumRepository">Injected repository for albums.</param>
|
||||
/// <param name="trackRepository">Injected repository for tracks.</param>
|
||||
public ArtistRepository(LuminaDbContext luminaDbContext, IAlbumRepository albumRepository, ITrackRepository trackRepository)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
_albumRepository = albumRepository;
|
||||
_trackRepository = trackRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -87,37 +94,96 @@ internal sealed class ArtistRepository : IArtistRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing artist.
|
||||
/// Updates an existing artist, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns.
|
||||
/// </summary>
|
||||
/// <param name="artist">The artist to update.</param>
|
||||
/// <param name="data">The artist whose editable data is applied to the stored artist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> UpdateAsync(ArtistEntity artist, CancellationToken cancellationToken)
|
||||
public async Task<Result<Updated>> UpdateAsync(ArtistEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
ArtistEntity? foundArtist = await _luminaDbContext.Artists
|
||||
.Include(repositoryArtist => repositoryArtist.Contributors)
|
||||
.Include(repositoryArtist => repositoryArtist.Albums)
|
||||
.ThenInclude(album => album.Tracks)
|
||||
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == artist.Id, cancellationToken).ConfigureAwait(false);
|
||||
.FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == data.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (foundArtist is null)
|
||||
return Errors.Music.ArtistNotFound;
|
||||
|
||||
// The stored identity and audit columns are never overwritten by an edit.
|
||||
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
|
||||
Guid libraryId = foundArtist.LibraryId;
|
||||
DateTime createdOnUtc = foundArtist.CreatedOnUtc;
|
||||
Guid createdBy = foundArtist.CreatedBy;
|
||||
|
||||
// Copy the editable scalar properties of the artist, ignoring the unchanged collection columns.
|
||||
_luminaDbContext.Entry(foundArtist).CurrentValues.SetValues(artist);
|
||||
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundArtist, data);
|
||||
foundArtist.LibraryId = libraryId;
|
||||
foundArtist.CreatedOnUtc = createdOnUtc;
|
||||
foundArtist.CreatedBy = createdBy;
|
||||
|
||||
// Replace the owned collections of the artist, so that removed entries are deleted and new entries are inserted.
|
||||
foundArtist.Contributors.Clear();
|
||||
foundArtist.Contributors.AddRange(artist.Contributors);
|
||||
foundArtist.Albums.Clear();
|
||||
foundArtist.Albums.AddRange(artist.Albums);
|
||||
// A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a
|
||||
// contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another field of the artist was edited.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundArtist.Contributors,
|
||||
data.Contributors,
|
||||
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
|
||||
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
|
||||
shouldReplace: (existingContributor, incomingContributor) => false,
|
||||
createNew: incomingContributor => incomingContributor);
|
||||
|
||||
// Reconcile the albums by their Id: albums that are no longer present are removed, new albums are inserted, and existing
|
||||
// albums and their tracks are updated in place, so that persisted entities keep their identity across an edit. An album whose data did
|
||||
// not change produces no write statement, because its own repository only applies the values that actually changed.
|
||||
List<Guid> incomingAlbumIds = [.. data.Albums.Select(album => album.Id)];
|
||||
foreach (AlbumEntity removedAlbum in foundArtist.Albums.Where(album => !incomingAlbumIds.Contains(album.Id)).ToList())
|
||||
foundArtist.Albums.Remove(removedAlbum);
|
||||
|
||||
foreach (AlbumEntity incomingAlbum in data.Albums)
|
||||
{
|
||||
AlbumEntity? existingAlbum = foundArtist.Albums.FirstOrDefault(album => album.Id == incomingAlbum.Id);
|
||||
if (existingAlbum is null)
|
||||
{
|
||||
Result<Created> insertAlbumResult = await _albumRepository.InsertAsync(incomingAlbum, cancellationToken).ConfigureAwait(false);
|
||||
if (insertAlbumResult.IsFailure)
|
||||
return insertAlbumResult.Errors;
|
||||
continue;
|
||||
}
|
||||
|
||||
Result<Updated> updateAlbumResult = await _albumRepository.UpdateAsync(incomingAlbum, cancellationToken).ConfigureAwait(false);
|
||||
if (updateAlbumResult.IsFailure)
|
||||
return updateAlbumResult.Errors;
|
||||
|
||||
Result<Updated> updateTracksResult = await ReconcileTracksAsync(existingAlbum, incomingAlbum, cancellationToken).ConfigureAwait(false);
|
||||
if (updateTracksResult.IsFailure)
|
||||
return updateTracksResult.Errors;
|
||||
}
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconciles the tracks of an existing album against the provided tracks, by their Id.
|
||||
/// </summary>
|
||||
/// <param name="existingAlbum">The tracked album whose tracks are reconciled.</param>
|
||||
/// <param name="incomingAlbum">The album carrying the tracks to reconcile with.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<Result<Updated>> ReconcileTracksAsync(AlbumEntity existingAlbum, AlbumEntity incomingAlbum, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Guid> incomingTrackIds = [.. incomingAlbum.Tracks.Select(track => track.Id)];
|
||||
foreach (TrackEntity removedTrack in existingAlbum.Tracks.Where(track => !incomingTrackIds.Contains(track.Id)).ToList())
|
||||
existingAlbum.Tracks.Remove(removedTrack);
|
||||
|
||||
foreach (TrackEntity incomingTrack in incomingAlbum.Tracks)
|
||||
{
|
||||
incomingTrack.AlbumId = existingAlbum.Id;
|
||||
incomingTrack.LibraryId = existingAlbum.LibraryId;
|
||||
TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == incomingTrack.Id);
|
||||
if (existingTrack is null)
|
||||
{
|
||||
Result<Created> insertTrackResult = await _trackRepository.InsertAsync(incomingTrack, cancellationToken).ConfigureAwait(false);
|
||||
if (insertTrackResult.IsFailure)
|
||||
return insertTrackResult.Errors;
|
||||
continue;
|
||||
}
|
||||
|
||||
Result<Updated> updateTrackResult = await _trackRepository.UpdateAsync(incomingTrack, cancellationToken).ConfigureAwait(false);
|
||||
if (updateTrackResult.IsFailure)
|
||||
return updateTrackResult.Errors;
|
||||
}
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -67,60 +68,109 @@ internal sealed class TrackRepository : ITrackRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing track, replacing its editable data while preserving its identity and audit columns.
|
||||
/// Updates an existing track, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns.
|
||||
/// </summary>
|
||||
/// <param name="track">The track whose editable data is applied to the stored track.</param>
|
||||
/// <param name="data">The track whose editable data is applied to the stored track.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> UpdateAsync(TrackEntity track, CancellationToken cancellationToken)
|
||||
public async Task<Result<Updated>> UpdateAsync(TrackEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
// Every collection that is reconciled must be loaded, so that the reconciliation can see the rows that are already stored and leave the unchanged ones alone.
|
||||
TrackEntity? foundTrack = await _luminaDbContext.Tracks
|
||||
.Include(repositoryTrack => repositoryTrack.Tags)
|
||||
.Include(repositoryTrack => repositoryTrack.Genres)
|
||||
.Include(repositoryTrack => repositoryTrack.Ratings)
|
||||
.Include(repositoryTrack => repositoryTrack.Contributors)
|
||||
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == track.Id, cancellationToken).ConfigureAwait(false);
|
||||
.Include(repositoryTrack => repositoryTrack.Moods)
|
||||
.Include(repositoryTrack => repositoryTrack.Isrcs)
|
||||
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == data.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (foundTrack is null)
|
||||
return Errors.Music.TrackNotFound;
|
||||
|
||||
// The stored identity and audit columns are never overwritten by an edit.
|
||||
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
|
||||
Guid albumId = foundTrack.AlbumId;
|
||||
Guid libraryId = foundTrack.LibraryId;
|
||||
DateTime createdOnUtc = foundTrack.CreatedOnUtc;
|
||||
Guid createdBy = foundTrack.CreatedBy;
|
||||
|
||||
// Copy the editable scalar properties of the track, ignoring the unchanged collection columns.
|
||||
_luminaDbContext.Entry(foundTrack).CurrentValues.SetValues(track);
|
||||
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundTrack, data);
|
||||
foundTrack.AlbumId = albumId;
|
||||
foundTrack.LibraryId = libraryId;
|
||||
foundTrack.CreatedOnUtc = createdOnUtc;
|
||||
foundTrack.CreatedBy = createdBy;
|
||||
|
||||
// Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated.
|
||||
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
|
||||
.Where(tag => track.Tags.Select(trackTag => trackTag.Name).Contains(tag.Name))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
|
||||
.Where(genre => track.Genres.Select(trackGenre => trackGenre.Name).Contains(genre.Name))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
await ReconcileTagsAndGenresAsync(foundTrack, data, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
foundTrack.Tags.Clear();
|
||||
foundTrack.Tags.UnionWith(track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
|
||||
foundTrack.Genres.Clear();
|
||||
foundTrack.Genres.UnionWith(track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
|
||||
// Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change
|
||||
// are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the track.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Ratings,
|
||||
data.Ratings,
|
||||
existingRating => existingRating.Source?.ToString() ?? string.Empty,
|
||||
incomingRating => incomingRating.Source?.ToString() ?? string.Empty,
|
||||
shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating),
|
||||
createNew: incomingRating => incomingRating);
|
||||
|
||||
// Replace the owned collections of the track, so that removed entries are deleted and new entries are inserted.
|
||||
foundTrack.Ratings.Clear();
|
||||
foundTrack.Ratings.AddRange(track.Ratings);
|
||||
foundTrack.Contributors.Clear();
|
||||
foundTrack.Contributors.AddRange(track.Contributors);
|
||||
foundTrack.Moods.Clear();
|
||||
foundTrack.Moods.AddRange(track.Moods);
|
||||
foundTrack.Isrcs.Clear();
|
||||
foundTrack.Isrcs.AddRange(track.Isrcs);
|
||||
// A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a
|
||||
// contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another track of the same album was edited.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Contributors,
|
||||
data.Contributors,
|
||||
existingContributor => (existingContributor.MediaContributorId, existingContributor.Role),
|
||||
incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role),
|
||||
shouldReplace: (existingContributor, incomingContributor) => false,
|
||||
createNew: incomingContributor => incomingContributor);
|
||||
|
||||
// Moods and ISRCs are owned value objects whose value is also their identity, so a match means there is nothing to change.
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Moods,
|
||||
data.Moods,
|
||||
existingMood => existingMood.Name,
|
||||
incomingMood => incomingMood.Name,
|
||||
shouldReplace: (existingMood, incomingMood) => false,
|
||||
createNew: incomingMood => incomingMood);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Isrcs,
|
||||
data.Isrcs,
|
||||
existingIsrc => existingIsrc.Value,
|
||||
incomingIsrc => incomingIsrc.Value,
|
||||
shouldReplace: (existingIsrc, incomingIsrc) => false,
|
||||
createNew: incomingIsrc => incomingIsrc);
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconciles the tags and genres of <paramref name="foundTrack"/> against the ones carried by <paramref name="data"/>, reusing the stored tags and genres whose names already exist.
|
||||
/// </summary>
|
||||
/// <param name="foundTrack">The tracked track whose tags and genres are reconciled.</param>
|
||||
/// <param name="data">The track carrying the desired tags and genres.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task ReconcileTagsAndGenresAsync(TrackEntity foundTrack, TrackEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
// Tags and genres are shared across the whole database, so the ones whose names are already stored are reused, and only the missing names are inserted.
|
||||
List<string> tagNames = [.. data.Tags.Select(tag => tag.Name!)];
|
||||
List<string> genreNames = [.. data.Genres.Select(genre => genre.Name!)];
|
||||
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
|
||||
.Where(tag => tagNames.Contains(tag.Name!))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<GenreEntity> existingGenres = await _luminaDbContext.Set<GenreEntity>()
|
||||
.Where(genre => genreNames.Contains(genre.Name!))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Tags,
|
||||
data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag),
|
||||
existingTag => existingTag.Name!,
|
||||
incomingTag => incomingTag.Name!,
|
||||
shouldReplace: (existingTag, incomingTag) => false,
|
||||
createNew: incomingTag => incomingTag);
|
||||
|
||||
CollectionReconciler.Reconcile(
|
||||
foundTrack.Genres,
|
||||
data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre),
|
||||
existingGenre => existingGenre.Name!,
|
||||
incomingGenre => incomingGenre.Name!,
|
||||
shouldReplace: (existingGenre, incomingGenre) => false,
|
||||
createNew: incomingGenre => incomingGenre);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a track by its Id.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Themes;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||
using Lumina.DataAccess.Core.Repositories.Books;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaContributors;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.Repositories.Scheduling;
|
||||
using Lumina.DataAccess.Core.Repositories.Themes;
|
||||
using Lumina.DataAccess.Core.Repositories.Users;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using System;
|
||||
using System.Threading;
|
||||
@@ -37,6 +43,9 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
private IRoleRepository? _roleRepository;
|
||||
private IUserRoleRepository? _userRoleRepository;
|
||||
private IBookRepository? _bookRepository;
|
||||
private IArtistRepository? _artistRepository;
|
||||
private IAlbumRepository? _albumRepository;
|
||||
private ITrackRepository? _trackRepository;
|
||||
private IMediaContributorRepository? _mediaContributorRepository;
|
||||
private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository;
|
||||
private ILibraryRepository? _libraryRepository;
|
||||
@@ -114,6 +123,42 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artist repository.
|
||||
/// </summary>
|
||||
public IArtistRepository ArtistRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_artistRepository ??= new ArtistRepository(_luminaDbContext, AlbumRepository, TrackRepository);
|
||||
return _artistRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the album repository.
|
||||
/// </summary>
|
||||
public IAlbumRepository AlbumRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_albumRepository ??= new AlbumRepository(_luminaDbContext);
|
||||
return _albumRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the track repository.
|
||||
/// </summary>
|
||||
public ITrackRepository TrackRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_trackRepository ??= new TrackRepository(_luminaDbContext);
|
||||
return _trackRepository;
|
||||
}
|
||||
}
|
||||
|
||||
public IMediaContributorRepository MediaContributorRepository
|
||||
{
|
||||
get
|
||||
@@ -316,9 +361,33 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async Task SaveChangesAsync(CancellationToken cancellationToken)
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.Success;
|
||||
}
|
||||
// A unique constraint violation is an expected persistence conflict, so it is reported as a failure result instead of bubbling up
|
||||
// as an unhandled exception and being turned into a generic internal server error. Any other exception is unexpected and is left
|
||||
// to propagate to the centralized exception handling middleware.
|
||||
catch (DbUpdateException exception) when (IsUniqueConstraintViolation(exception))
|
||||
{
|
||||
return Errors.Persistence.UniqueConstraintViolation;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided <paramref name="exception"/> was caused by a unique constraint violation of the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to inspect.</param>
|
||||
/// <returns><see langword="true"/> if the exception was caused by a unique constraint violation, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsUniqueConstraintViolation(DbUpdateException exception)
|
||||
{
|
||||
// SQLite reports a generic constraint failure code for several constraints, so the extended code is used to tell a unique violation apart.
|
||||
return exception.InnerException is SqliteException sqliteException
|
||||
&& sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+140
@@ -2,12 +2,16 @@
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
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 System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
@@ -230,4 +234,140 @@ public sealed class Artist : AggregateRoot<ArtistId>
|
||||
UpdatedOnUtc = DateTime.UtcNow;
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates an album of the artist, together with its media contributors and ratings, without touching its tracks.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// An album is a child entity of the artist aggregate, not an aggregate root, so it is mutated through its owning artist,
|
||||
/// which is the consistency boundary. Book and Artist are themselves aggregate roots, so their update flows reconstitute them
|
||||
/// directly with their own Create method instead. This difference is intentional.
|
||||
/// </remarks>
|
||||
/// <param name="albumId">The Id of the album to update.</param>
|
||||
/// <param name="metadata">The album metadata of the album.</param>
|
||||
/// <param name="mediaFormat">The optional physical or digital medium of the album.</param>
|
||||
/// <param name="barcode">The optional barcode of the album.</param>
|
||||
/// <param name="catalogNumber">The optional catalog number of the album.</param>
|
||||
/// <param name="musicBrainzReleaseId">The optional MusicBrainz identifier of the release.</param>
|
||||
/// <param name="musicBrainzReleaseGroupId">The optional MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="musicBrainzReleaseArtistId">The optional MusicBrainz identifier of the release artist.</param>
|
||||
/// <param name="contributors">The media contributors of the album.</param>
|
||||
/// <param name="ratings">The ratings of the album.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Updated> UpdateAlbum(
|
||||
AlbumId albumId,
|
||||
AlbumMetadata metadata,
|
||||
Optional<MusicMediaFormat> mediaFormat,
|
||||
Optional<Barcode> barcode,
|
||||
Optional<string> catalogNumber,
|
||||
Optional<MusicBrainzId> musicBrainzReleaseId,
|
||||
Optional<MusicBrainzId> musicBrainzReleaseGroupId,
|
||||
Optional<MusicBrainzId> musicBrainzReleaseArtistId,
|
||||
IReadOnlyCollection<MusicMediaContributor> contributors,
|
||||
IReadOnlyCollection<AudioRating> ratings)
|
||||
{
|
||||
Album? album = _albums.FirstOrDefault(album => album.Id == albumId);
|
||||
if (album is null)
|
||||
return Errors.Music.AlbumNotFound;
|
||||
|
||||
album.UpdateDetails(metadata, mediaFormat, barcode, catalogNumber, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId);
|
||||
album.UpdateContributors(contributors);
|
||||
album.UpdateRatings(ratings);
|
||||
UpdatedOnUtc = DateTime.UtcNow;
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a track of an album of the artist, together with its media contributors, ratings, moods and ISRCs.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A track is a child entity of the artist aggregate, not an aggregate root, so it is mutated through its owning artist,
|
||||
/// which is the consistency boundary. Book and Artist are themselves aggregate roots, so their update flows reconstitute them
|
||||
/// directly with their own Create method instead. This difference is intentional.
|
||||
/// </remarks>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track to update.</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 optional number of the disc the track belongs to.</param>
|
||||
/// <param name="script">The optional script used by the language of the track.</param>
|
||||
/// <param name="key">The optional musical key of the track.</param>
|
||||
/// <param name="bpm">The optional tempo of the track in beats per minute.</param>
|
||||
/// <param name="work">The optional title of the work the track is a recording of.</param>
|
||||
/// <param name="musicBrainzRecordingId">The optional MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="musicBrainzTrackId">The optional MusicBrainz identifier of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">The optional MusicBrainz identifier of the work.</param>
|
||||
/// <param name="contributors">The media contributors of the track.</param>
|
||||
/// <param name="ratings">The ratings of the track.</param>
|
||||
/// <param name="moods">The moods of the track.</param>
|
||||
/// <param name="isrcs">The ISRCs of the track.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Updated> UpdateTrackInAlbum(
|
||||
AlbumId albumId,
|
||||
TrackId trackId,
|
||||
string path,
|
||||
AudioMetadata metadata,
|
||||
int trackNumber,
|
||||
Optional<int> discNumber,
|
||||
Optional<string> script,
|
||||
Optional<MusicKey> key,
|
||||
Optional<int> bpm,
|
||||
Optional<string> work,
|
||||
Optional<MusicBrainzId> musicBrainzRecordingId,
|
||||
Optional<MusicBrainzId> musicBrainzTrackId,
|
||||
Optional<MusicBrainzId> musicBrainzWorkId,
|
||||
IReadOnlyCollection<MusicMediaContributor> contributors,
|
||||
IReadOnlyCollection<AudioRating> ratings,
|
||||
IReadOnlyCollection<Mood> moods,
|
||||
IReadOnlyCollection<Isrc> isrcs)
|
||||
{
|
||||
Album? album = _albums.FirstOrDefault(album => album.Id == albumId);
|
||||
Track? track = album?.Tracks.FirstOrDefault(track => track.Id == trackId);
|
||||
if (track is null)
|
||||
return Errors.Music.TrackNotFound;
|
||||
|
||||
track.UpdateDetails(
|
||||
path,
|
||||
metadata,
|
||||
trackNumber,
|
||||
discNumber,
|
||||
script,
|
||||
key,
|
||||
bpm,
|
||||
work,
|
||||
musicBrainzRecordingId,
|
||||
musicBrainzTrackId,
|
||||
musicBrainzWorkId);
|
||||
track.UpdateContributors(contributors);
|
||||
track.UpdateRatings(ratings);
|
||||
track.UpdateMoods(moods);
|
||||
track.UpdateIsrcs(isrcs);
|
||||
UpdatedOnUtc = DateTime.UtcNow;
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a track to an album of the artist.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album the track is added to.</param>
|
||||
/// <param name="track">The track to be added.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
/// <remarks>
|
||||
/// A track is a child entity of the artist aggregate, not an aggregate root, so it is added through its owning artist,
|
||||
/// which is the consistency boundary. Book and Artist are themselves aggregate roots, so they are created directly instead.
|
||||
/// This difference is intentional.
|
||||
/// </remarks>
|
||||
public Result<Created> AddTrackToAlbum(AlbumId albumId, Track track)
|
||||
{
|
||||
Album? album = _albums.FirstOrDefault(album => album.Id == albumId);
|
||||
if (album is null)
|
||||
return Errors.Music.AlbumNotFound;
|
||||
|
||||
Result<Created> addResult = album.AddTrack(track);
|
||||
if (addResult.IsFailure)
|
||||
return addResult.Errors;
|
||||
|
||||
return Result.Created;
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -217,7 +217,7 @@ public sealed class Album : Entity<AlbumId>
|
||||
/// </summary>
|
||||
/// <param name="track">The track to be added.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Created> AddTrack(Track track)
|
||||
internal Result<Created> AddTrack(Track track)
|
||||
{
|
||||
if (_tracks.Contains(track))
|
||||
return Errors.Music.TheTrackIsAlreadyInTheAlbum;
|
||||
@@ -230,7 +230,7 @@ public sealed class Album : Entity<AlbumId>
|
||||
/// </summary>
|
||||
/// <param name="track">The track to be removed.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Deleted> RemoveTrack(Track track)
|
||||
internal Result<Deleted> RemoveTrack(Track track)
|
||||
{
|
||||
if (!_tracks.Contains(track))
|
||||
return Errors.Music.TheTrackIsNotInTheAlbum;
|
||||
@@ -242,7 +242,7 @@ public sealed class Album : Entity<AlbumId>
|
||||
/// Replaces the media contributors of the album with the provided <paramref name="contributors"/>.
|
||||
/// </summary>
|
||||
/// <param name="contributors">The media contributors of the album.</param>
|
||||
public void UpdateContributors(IReadOnlyCollection<MusicMediaContributor> contributors)
|
||||
internal void UpdateContributors(IReadOnlyCollection<MusicMediaContributor> contributors)
|
||||
{
|
||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
||||
_contributors.Clear();
|
||||
@@ -253,7 +253,7 @@ public sealed class Album : Entity<AlbumId>
|
||||
/// Replaces the ratings of the album with the provided <paramref name="ratings"/>.
|
||||
/// </summary>
|
||||
/// <param name="ratings">The ratings of the album.</param>
|
||||
public void UpdateRatings(IReadOnlyCollection<AudioRating> ratings)
|
||||
internal void UpdateRatings(IReadOnlyCollection<AudioRating> ratings)
|
||||
{
|
||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
||||
_ratings.Clear();
|
||||
@@ -271,7 +271,7 @@ public sealed class Album : Entity<AlbumId>
|
||||
/// <param name="musicBrainzReleaseGroupId">The optional MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="musicBrainzReleaseArtistId">The optional MusicBrainz identifier of the release artist.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Updated> UpdateDetails(
|
||||
internal Result<Updated> UpdateDetails(
|
||||
AlbumMetadata metadata,
|
||||
Optional<MusicMediaFormat> mediaFormat,
|
||||
Optional<Barcode> barcode,
|
||||
|
||||
+25
-3
@@ -274,7 +274,7 @@ public sealed class Track : Entity<TrackId>
|
||||
/// Replaces the media contributors of the track with the provided <paramref name="contributors"/>.
|
||||
/// </summary>
|
||||
/// <param name="contributors">The media contributors of the track.</param>
|
||||
public void UpdateContributors(IReadOnlyCollection<MusicMediaContributor> contributors)
|
||||
internal void UpdateContributors(IReadOnlyCollection<MusicMediaContributor> contributors)
|
||||
{
|
||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
||||
_contributors.Clear();
|
||||
@@ -285,13 +285,35 @@ public sealed class Track : Entity<TrackId>
|
||||
/// Replaces the ratings of the track with the provided <paramref name="ratings"/>.
|
||||
/// </summary>
|
||||
/// <param name="ratings">The ratings of the track.</param>
|
||||
public void UpdateRatings(IReadOnlyCollection<AudioRating> ratings)
|
||||
internal void UpdateRatings(IReadOnlyCollection<AudioRating> ratings)
|
||||
{
|
||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
||||
_ratings.Clear();
|
||||
_ratings.AddRange(ratings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the moods of the track with the provided <paramref name="moods"/>.
|
||||
/// </summary>
|
||||
/// <param name="moods">The moods of the track.</param>
|
||||
internal void UpdateMoods(IReadOnlyCollection<Mood> moods)
|
||||
{
|
||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
||||
_moods.Clear();
|
||||
_moods.AddRange(moods);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the ISRCs of the track with the provided <paramref name="isrcs"/>.
|
||||
/// </summary>
|
||||
/// <param name="isrcs">The ISRCs of the track.</param>
|
||||
internal void UpdateIsrcs(IReadOnlyCollection<Isrc> isrcs)
|
||||
{
|
||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
||||
_isrcs.Clear();
|
||||
_isrcs.AddRange(isrcs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the details of the track, without touching the moods, the ISRCs, the media contributors, and the ratings.
|
||||
/// </summary>
|
||||
@@ -307,7 +329,7 @@ public sealed class Track : Entity<TrackId>
|
||||
/// <param name="musicBrainzTrackId">The optional MusicBrainz identifier of the track.</param>
|
||||
/// <param name="musicBrainzWorkId">The optional MusicBrainz identifier of the work.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Updated> UpdateDetails(
|
||||
internal Result<Updated> UpdateDetails(
|
||||
string path,
|
||||
AudioMetadata metadata,
|
||||
int trackNumber,
|
||||
|
||||
+2
@@ -746,6 +746,8 @@ public class AddAlbumEndpointSummary : Summary<AddAlbumEndpoint, AddAlbumRequest
|
||||
"LanguageNativeNameMustBeMaximum50CharactersLong",
|
||||
"UnknownMusicMediaFormat",
|
||||
"CatalogNumberMustBeMaximum50CharactersLong",
|
||||
"BarcodeValueCannotBeEmpty",
|
||||
"InvalidFormatForBarcode",
|
||||
"MusicBrainzIdInvalidFormat",
|
||||
"ContributorsListCannotBeNull",
|
||||
"MediaContributorIdCannotBeEmpty",
|
||||
|
||||
+48
-46
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
@@ -28,7 +28,41 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
public UpdateAlbumEndpointSummary()
|
||||
{
|
||||
Summary = "Updates an existing album.";
|
||||
Description = "Updates the details of the album identified by the request, returning the full details of the updated album. The tracks of the album are left untouched. The album is updated by an Admin, who can update the albums of all libraries, or by the owner of the library of the album.";
|
||||
Description = "Updates the details of the album identified by the request, returning the full details of the updated album. The album is updated by an Admin, who can update the albums of all libraries, or by the owner of the library of the album.";
|
||||
|
||||
RequestParam(r => r.Metadata, "The album metadata of the album. Required.");
|
||||
RequestParam(r => r.Metadata!.Title, "The title of the album. Required.");
|
||||
RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Description, "The description of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseType, "The type of the release. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseStatus, "The status of the release. Optional.");
|
||||
RequestParam(r => r.Metadata!.TotalDiscs, "The number of discs of the release. Optional.");
|
||||
RequestParam(r => r.Metadata!.TotalTracks, "The number of tracks of the release. Optional.");
|
||||
RequestParam(r => r.Metadata!.Language, "The language of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English. Optional.");
|
||||
RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the album, if it has been translated. Optional.");
|
||||
RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English. Optional.");
|
||||
RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Genres, "The list of genres associated with the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album. Optional.");
|
||||
RequestParam(r => r.MediaFormat, "The physical or digital medium of the album. Optional.");
|
||||
RequestParam(r => r.Barcode, "The barcode of the album. Optional.");
|
||||
RequestParam(r => r.CatalogNumber, "The catalog number of the album. Optional.");
|
||||
RequestParam(r => r.MusicBrainzReleaseId, "The MusicBrainz identifier of the release. Optional.");
|
||||
RequestParam(r => r.MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group. Optional.");
|
||||
RequestParam(r => r.MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist. Optional.");
|
||||
RequestParam(r => r.Contributors, "The list of media contributors that performed on the album. Required.");
|
||||
RequestParam(r => r.Ratings, "The list of ratings for this album. Required.");
|
||||
|
||||
ExampleRequest = new UpdateAlbumRequest(
|
||||
Metadata: new AlbumMetadataDto(
|
||||
@@ -102,40 +136,6 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
]
|
||||
);
|
||||
|
||||
RequestParam(r => r.Metadata, "The album metadata of the album. Required.");
|
||||
RequestParam(r => r.Metadata!.Title, "The title of the album. Required.");
|
||||
RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Description, "The description of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseType, "The type of the release. Optional.");
|
||||
RequestParam(r => r.Metadata!.ReleaseStatus, "The status of the release. Optional.");
|
||||
RequestParam(r => r.Metadata!.TotalDiscs, "The number of discs of the release. Optional.");
|
||||
RequestParam(r => r.Metadata!.TotalTracks, "The number of tracks of the release. Optional.");
|
||||
RequestParam(r => r.Metadata!.Language, "The language of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English. Optional.");
|
||||
RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the album, if it has been translated. Optional.");
|
||||
RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English. Optional.");
|
||||
RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Genres, "The list of genres associated with the album. Optional.");
|
||||
RequestParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album. Optional.");
|
||||
RequestParam(r => r.MediaFormat, "The physical or digital medium of the album. Optional.");
|
||||
RequestParam(r => r.Barcode, "The barcode of the album. Optional.");
|
||||
RequestParam(r => r.CatalogNumber, "The catalog number of the album. Optional.");
|
||||
RequestParam(r => r.MusicBrainzReleaseId, "The MusicBrainz identifier of the release. Optional.");
|
||||
RequestParam(r => r.MusicBrainzReleaseGroupId, "The MusicBrainz identifier of the release group. Optional.");
|
||||
RequestParam(r => r.MusicBrainzReleaseArtistId, "The MusicBrainz identifier of the release artist. Optional.");
|
||||
RequestParam(r => r.Contributors, "The list of media contributors that performed on the album. Required.");
|
||||
RequestParam(r => r.Ratings, "The list of ratings for this album. Required.");
|
||||
|
||||
ResponseParam<AlbumResponse>(r => r.Id, "The Id of the album.");
|
||||
ResponseParam<AlbumResponse>(r => r.ArtistId, "The Id of the artist the album belongs to.");
|
||||
ResponseParam<AlbumResponse>(r => r.LibraryId, "The Id of the media library the album belongs to.");
|
||||
@@ -256,16 +256,16 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "You are not authorized",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"
|
||||
detail = "Authentication failed",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"
|
||||
detail = "The token has expired",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}"
|
||||
},
|
||||
new
|
||||
{
|
||||
@@ -273,7 +273,7 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}"
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -285,7 +285,7 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
title = "General.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
@@ -299,7 +299,7 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "AlbumNotFound",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
},
|
||||
new
|
||||
@@ -308,7 +308,7 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "LibraryNotFound",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
},
|
||||
new
|
||||
@@ -317,7 +317,7 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "MediaContributorNotFound",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
}
|
||||
@@ -330,7 +330,7 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
@@ -369,6 +369,8 @@ public class UpdateAlbumEndpointSummary : Summary<UpdateAlbumEndpoint, UpdateAlb
|
||||
"LanguageNativeNameMustBeMaximum50CharactersLong",
|
||||
"UnknownMusicMediaFormat",
|
||||
"CatalogNumberMustBeMaximum50CharactersLong",
|
||||
"BarcodeValueCannotBeEmpty",
|
||||
"InvalidFormatForBarcode",
|
||||
"MusicBrainzIdInvalidFormat",
|
||||
"ContributorsListCannotBeNull",
|
||||
"MediaContributorIdCannotBeEmpty",
|
||||
|
||||
+14
-11
@@ -28,7 +28,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
public UpdateTrackEndpointSummary()
|
||||
{
|
||||
Summary = "Updates an existing track.";
|
||||
Description = "Updates the details of the track identified by the request, returning the full details of the updated track. The media contributors of the track are left untouched. The track is updated by an Admin, who can update the tracks of all libraries, or by the owner of the library of the track.";
|
||||
Description = "Updates the details of the track identified by the request, returning the full details of the updated track. The track is updated by an Admin, who can update the tracks of all libraries, or by the owner of the library of the track.";
|
||||
|
||||
ExampleRequest = new UpdateTrackRequest(
|
||||
Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
|
||||
@@ -154,7 +154,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
RequestParam(r => r.MusicBrainzRecordingId, "The MusicBrainz identifier of the recording. Optional.");
|
||||
RequestParam(r => r.MusicBrainzTrackId, "The MusicBrainz identifier of the track. Optional.");
|
||||
RequestParam(r => r.MusicBrainzWorkId, "The MusicBrainz identifier of the work. Optional.");
|
||||
RequestParam(r => r.Contributors, "The list of media contributors that performed on the track. Optional.");
|
||||
RequestParam(r => r.Contributors, "The list of media contributors that performed on the track. Required.");
|
||||
RequestParam(r => r.Ratings, "The list of ratings for this track. Required.");
|
||||
RequestParam(r => r.Moods, "The list of moods of the track. Optional.");
|
||||
RequestParam(r => r.Isrcs, "The list of ISRC (International Standard Recording Code) of the track. Optional.");
|
||||
@@ -298,16 +298,16 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "You are not authorized",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"
|
||||
detail = "Authentication failed",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"
|
||||
detail = "The token has expired",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"
|
||||
},
|
||||
new
|
||||
{
|
||||
@@ -315,7 +315,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -327,7 +327,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
title = "General.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
@@ -341,7 +341,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "TrackNotFound",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
},
|
||||
new
|
||||
@@ -350,7 +350,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "LibraryNotFound",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
}
|
||||
@@ -363,7 +363,7 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}",
|
||||
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
@@ -375,6 +375,9 @@ public class UpdateTrackEndpointSummary : Summary<UpdateTrackEndpoint, UpdateTra
|
||||
"TrackIdCannotBeEmpty",
|
||||
"TrackPathCannotBeEmpty",
|
||||
"TrackNumberMustBeGreaterThanZero",
|
||||
"ContributorsListCannotBeNull",
|
||||
"MediaContributorIdCannotBeEmpty",
|
||||
"UnknownMediaContributorRole",
|
||||
"MusicBrainzIdInvalidFormat"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user