Refactors the track slice across the stack

This commit is contained in:
BinaryAlley committed 2026-09-25 13:19:28 -07:00
1 parent e842c7baaf
commit 6bd0cf6d42
37 files changed
+853 -403

No files matched your search

@@ -96,12 +96,14 @@ public class AddTrackCommandHandler : ICommandHandler<AddTrackCommand, Result<Tr
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
if (getArtistResult.Value is null || getArtistResult.Value.LibraryId != libraryId)
return Errors.Music.AlbumNotFound;
if (getArtistResult.Value is null)
return Errors.Music.ArtistNotFound;
ArtistEntity existingArtist = getArtistResult.Value;
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
if (existingAlbum is null)
return Errors.Music.AlbumNotFound;
// Resource scoping: the track must belong to an artist of the library named by the route, so that a track can never be added through
// another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library.
if (existingArtist.LibraryId != libraryId)
return Errors.Music.ArtistNotFound;
// 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>(
@@ -109,6 +111,10 @@ public class AddTrackCommandHandler : ICommandHandler<AddTrackCommand, Result<Tr
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
if (existingAlbum is null)
return Errors.Music.AlbumNotFound;
// A track can only belong to a library that exists, so a client can never register an entry that points to a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
@@ -135,7 +141,11 @@ public class AddTrackCommandHandler : ICommandHandler<AddTrackCommand, Result<Tr
Result<Track> createTrackResult = command.ToDomainEntity();
if (createTrackResult.IsFailure)
return createTrackResult.Errors;
Result<Created> addTrackResult = artistResult.Value.AddTrackToAlbum(AlbumId.Create(albumId), createTrackResult.Value);
// The album is an entity inside the artist aggregate, so it is referenced by object, not by id; the aggregate member is located here and passed through.
Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId);
if (domainAlbum is null)
return Errors.Music.AlbumNotFound;
Result<Created> addTrackResult = artistResult.Value.AddTrackToAlbum(domainAlbum, createTrackResult.Value);
if (addTrackResult.IsFailure)
return addTrackResult.Errors;
@@ -192,6 +192,7 @@ public class AddTrackCommandValidator : AbstractValidator<AddTrackCommand>
.When(m => m!.OriginalLanguage is not null);
});
// Validates the MusicBrainz identifiers of the track.
RuleFor(command => command.MusicBrainzRecordingId)
.Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty)
.When(command => command.MusicBrainzRecordingId.HasValue)
@@ -208,6 +209,10 @@ public class AddTrackCommandValidator : AbstractValidator<AddTrackCommand>
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the ordering and performance characteristics of the track.
RuleFor(command => command.TrackNumber)
.NotNull()
.WithError(Errors.Music.TrackNumberMustBeGreaterThanZero);
RuleFor(command => command.TrackNumber)
.GreaterThan(0)
.When(command => command.TrackNumber.HasValue)
@@ -238,6 +243,19 @@ public class AddTrackCommandValidator : AbstractValidator<AddTrackCommand>
.When(command => command.Work is not null)
.WithError(Errors.Music.WorkMustBeMaximum255CharactersLong);
// Validates the moods and the ISRC codes of the track.
RuleForEach(command => command.Moods)
.ChildRules(mood =>
mood.RuleFor(m => m.Name)
.NotEmpty()
.WithError(Errors.Metadata.MoodNameCannotBeEmpty));
RuleForEach(command => command.Isrcs)
.ChildRules(isrc =>
isrc.RuleFor(i => i.Value)
.NotEmpty()
.WithError(Errors.Music.IsrcValueCannotBeEmpty));
// Validates the media contributors that performed on the track.
RuleFor(command => command.Contributors)
.NotNull()
@@ -11,7 +11,6 @@ using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.A
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.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -81,14 +80,10 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
return DomainErrors.Music.ArtistNotFound;
ArtistEntity existingArtist = getArtistResult.Value;
// Resource scoping: the track must belong to an album of the artist of the library named by the route, so that a track can never be
// deleted through another library's, artist's or album's route; the mismatch is reported as not found.
// Resource scoping: the track must belong to an artist of the library named by the route, so that a track can never be deleted through
// another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library.
if (existingArtist.LibraryId != libraryId)
return DomainErrors.Music.TrackNotFound;
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
TrackEntity? existingTrack = existingAlbum?.Tracks.FirstOrDefault(track => track.Id == trackId);
if (existingTrack is null)
return DomainErrors.Music.TrackNotFound;
return DomainErrors.Music.ArtistNotFound;
// Admins can delete the tracks of all libraries; for everyone else, only the tracks of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
@@ -96,6 +91,13 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
if (existingAlbum is null)
return DomainErrors.Music.AlbumNotFound;
TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == trackId);
if (existingTrack is null)
return DomainErrors.Music.TrackNotFound;
// A track can only belong to a library that exists, so a client can never delete a track of a library of the host that is not there.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository
.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -109,14 +111,21 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
Result<Artist> artistResult = existingArtist.ToDomainEntity();
if (artistResult.IsFailure)
return artistResult.Errors;
Result<Deleted> removeTrackResult = artistResult.Value.RemoveTrackFromAlbum(AlbumId.Create(albumId), TrackId.Create(trackId));
// The album and the track are entities inside the artist aggregate, so they are referenced by object, not by id; the aggregate members are located here and passed through.
Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId);
if (domainAlbum is null)
return DomainErrors.Music.AlbumNotFound;
Track? domainTrack = domainAlbum.Tracks.FirstOrDefault(track => track.Id.Value == trackId);
if (domainTrack is null)
return DomainErrors.Music.TrackNotFound;
Result<Deleted> removeTrackResult = artistResult.Value.RemoveTrackFromAlbum(domainAlbum, domainTrack);
if (removeTrackResult.IsFailure)
return removeTrackResult.Errors;
Result<Updated> updateResult = await _unitOfWork.ArtistRepository
.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
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;
@@ -30,10 +30,10 @@ 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>
/// <param name="Contributors">The list of media contributors that performed on the track.</param>
/// <param name="Ratings">The list of ratings for this track.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateTrackCommand(
string? LibraryId,
@@ -51,8 +51,8 @@ public record UpdateTrackCommand(
Guid? MusicBrainzRecordingId,
Guid? MusicBrainzTrackId,
Guid? MusicBrainzWorkId,
List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings,
List<MoodDto>? Moods,
List<IsrcDto>? Isrcs
List<IsrcDto>? Isrcs,
List<MediaContributorReferenceDto>? Contributors,
List<AudioRatingDto>? Ratings
) : ICommand;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.UoW;
@@ -13,6 +14,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.A
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
@@ -24,6 +26,7 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIden
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;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
@@ -45,6 +48,7 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateTrackCommand> _validator;
private readonly IPathService _pathService;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateTrackCommandHandler"/> class.
@@ -53,12 +57,14 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateTrackCommand> validator)
/// <param name="pathService">Injected service for file system path related functionality.</param>
public UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateTrackCommand> validator, IPathService pathService)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
_pathService = pathService;
}
/// <summary>
@@ -92,15 +98,14 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
// 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;
if (getArtistResult.Value is null)
return Errors.Music.ArtistNotFound;
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;
// Resource scoping: the track must belong to an artist of the library named by the route, so that a track can never be edited through
// another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library.
if (existingArtist.LibraryId != libraryId)
return Errors.Music.ArtistNotFound;
// 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>(
@@ -108,6 +113,13 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId);
if (existingAlbum is null)
return Errors.Music.AlbumNotFound;
TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == trackId);
if (existingTrack is null)
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)
@@ -115,8 +127,18 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
if (getLibraryResult.Value is null)
return Errors.Library.LibraryNotFound;
// The write path goes through the aggregate root: a track is a child entity of the artist aggregate, unlike Book and Artist,
// which are aggregate roots and are reconstituted directly with their own Create method. This difference is intentional.
// A track is only readable if it is stored inside one of the content locations of its library, so a client can never edit an entry
// that points the reading pipeline at an arbitrary file of the host.
if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command))
return Errors.Music.TrackPathMustBeWithinLibraryContentLocations;
// Media contributors are referenced by Id and are never created implicitly by editing a track, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
// The write path goes through the aggregate root: a track is a child entity of the artist aggregate, so it is mutated through its owning
// artist. Book is itself an aggregate root, so its update flow reconstitutes it directly with its own Create method instead.
Result<Artist> artistResult = existingArtist.ToDomainEntity();
if (artistResult.IsFailure)
return artistResult.Errors;
@@ -141,4 +163,49 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
return getPersistedTrackResult.Value.ToResponse();
}
/// <summary>
/// Determines whether the track path referenced by <paramref name="command"/> is stored inside one of the content locations of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library that owns the track.</param>
/// <param name="command">The command carrying the referenced track.</param>
/// <returns><see langword="true"/> when the referenced track path is within a content location of the library; otherwise, <see langword="false"/>.</returns>
private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, UpdateTrackCommand command)
{
return library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path));
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(UpdateTrackCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. CollectContributorIds(command).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return Errors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
/// <summary>
/// Collects the unique identifiers of every media contributor referenced by <paramref name="command"/>.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <returns>The collected media contributor identifiers.</returns>
private static IEnumerable<Guid> CollectContributorIds(UpdateTrackCommand command)
{
foreach (MediaContributorReferenceDto contributor in command.Contributors!)
yield return contributor.ContributorId;
}
}
@@ -202,6 +202,7 @@ public class UpdateTrackCommandValidator : AbstractValidator<UpdateTrackCommand>
.When(m => m!.OriginalLanguage is not null);
});
// Validates the MusicBrainz identifiers of the track.
RuleFor(command => command.MusicBrainzRecordingId)
.Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty)
.When(command => command.MusicBrainzRecordingId.HasValue)
@@ -218,6 +219,10 @@ public class UpdateTrackCommandValidator : AbstractValidator<UpdateTrackCommand>
.WithError(Errors.Music.MusicBrainzIdInvalidFormat);
// Validates the ordering and performance characteristics of the track.
RuleFor(command => command.TrackNumber)
.NotNull()
.WithError(Errors.Music.TrackNumberMustBeGreaterThanZero);
RuleFor(command => command.TrackNumber)
.GreaterThan(0)
.When(command => command.TrackNumber.HasValue)
@@ -248,6 +253,19 @@ public class UpdateTrackCommandValidator : AbstractValidator<UpdateTrackCommand>
.When(command => command.Work is not null)
.WithError(Errors.Music.WorkMustBeMaximum255CharactersLong);
// Validates the moods and the ISRC codes of the track.
RuleForEach(command => command.Moods)
.ChildRules(mood =>
mood.RuleFor(m => m.Name)
.NotEmpty()
.WithError(Errors.Metadata.MoodNameCannotBeEmpty));
RuleForEach(command => command.Isrcs)
.ChildRules(isrc =>
isrc.RuleFor(i => i.Value)
.NotEmpty()
.WithError(Errors.Music.IsrcValueCannotBeEmpty));
// Validates the media contributors that performed on the track.
RuleFor(command => command.Contributors)
.NotNull()
@@ -6,7 +6,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Errors;
@@ -76,13 +75,13 @@ public class GetTrackQueryHandler : IQueryHandler<GetTrackQuery, Result<TrackRes
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return Errors.Music.TrackNotFound;
return Errors.Music.AlbumNotFound;
AlbumEntity existingAlbum = getAlbumResult.Value;
// Resource scoping: the album must belong to the library and the artist named by the route, so that a track can never be read through
// another library's or artist's route; the mismatch is reported as not found, without disclosing that the track exists elsewhere.
// Resource scoping: the album must belong to the artist and the library named by the route, so that a track can never be read through
// another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere.
if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
return Errors.Music.TrackNotFound;
return Errors.Music.AlbumNotFound;
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)