Refactors the track slice across the stack

This commit is contained in:
BinaryAlley committed 2026-09-19 12:58:01 -07:00
1 parent d4cc3c1f8d
commit b398f26bfe
25 files changed
+2927 -432

No files matched your search

@@ -93,7 +93,7 @@ public class AddTrackCommandHandler : ICommandHandler<AddTrackCommand, Result<Tr
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);
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)
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -9,8 +8,14 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.
/// <summary>
/// Command for deleting a track by its Id.
/// </summary>
/// <param name="TrackId">The unique identifier of the track to delete.</param>
/// <param name="LibraryId">The unique identifier of the media library this track belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist the album of the track belongs to, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route.</param>
/// <param name="TrackId">The unique identifier of the track to delete, taken from the route.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record DeleteTrackCommand(
Guid TrackId
string? LibraryId,
string? ArtistId,
string? AlbumId,
string? TrackId
) : ICommand;
@@ -1,18 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Errors;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
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;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
@@ -60,25 +66,61 @@ public class DeleteTrackCommandHandler : ICommandHandler<DeleteTrackCommand, Res
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(command.TrackId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null)
return Errors.Music.TrackNotFound;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
Guid trackId = Guid.Parse(command.TrackId!);
// A track is a child of the artist aggregate, so the whole aggregate is loaded and the track is removed within it.
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)
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.
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;
// Admins can delete the tracks of all libraries; for everyone else, only the tracks of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<Deleted> deleteTrackResult = await _unitOfWork.TrackRepository.DeleteByIdAsync(command.TrackId, cancellationToken).ConfigureAwait(false);
if (deleteTrackResult.IsFailure)
return deleteTrackResult.Errors;
// 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);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// The write path goes through the aggregate root: a track is a child entity of the artist aggregate, unlike Book and Artist,
// which are aggregate roots and are deleted directly through their own repositories. This difference is intentional.
Result<Artist> artistResult = existingArtist.ToDomainEntity();
if (artistResult.IsFailure)
return artistResult.Errors;
Result<Deleted> removeTrackResult = artistResult.Value.RemoveTrackFromAlbum(AlbumId.Create(albumId), TrackId.Create(trackId));
if (removeTrackResult.IsFailure)
return removeTrackResult.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;
return deleteTrackResult;
return Result.Deleted;
}
}
@@ -17,10 +17,44 @@ public class DeleteTrackCommandValidator : AbstractValidator<DeleteTrackCommand>
/// </summary>
public DeleteTrackCommandValidator()
{
// Validates the identifier of the media library that owns the track, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the artist the album of the track belongs to, taken from the route.
RuleFor(command => command.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
RuleFor(command => command.ArtistId)
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
// Validates the identifier of the album the track belongs to, taken from the route.
RuleFor(command => command.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
RuleFor(command => command.AlbumId)
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
.When(command => command.AlbumId is not null && command.AlbumId.Length > 0)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
// Validates the identifier of the track to delete, taken from the route.
RuleFor(command => command.TrackId)
.NotEmpty()
.WithError(Errors.Music.TrackIdCannotBeEmpty)
.Must(trackId => trackId != Guid.Empty)
.WithError(Errors.Music.TrackIdCannotBeEmpty);
RuleFor(command => command.TrackId)
.Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty)
.When(command => command.TrackId is not null && command.TrackId.Length > 0)
.WithError(Errors.Music.TrackIdCannotBeEmpty);
}
}
@@ -88,7 +88,7 @@ public class UpdateTrackCommandHandler : ICommandHandler<UpdateTrackCommand, Res
Guid trackId = Guid.Parse(command.TrackId!);
// A track is a child of the artist aggregate, so the whole aggregate is loaded and the track is edited within it.
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, cancellationToken: cancellationToken).ConfigureAwait(false);
Result<ArtistEntity?> getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
@@ -9,8 +9,14 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.
/// <summary>
/// Query for getting a track by its Id.
/// </summary>
/// <param name="TrackId">The unique identifier of the track to get.</param>
/// <param name="LibraryId">The unique identifier of the media library the track belongs to, taken from the route.</param>
/// <param name="ArtistId">The unique identifier of the artist the album of the track belongs to, taken from the route.</param>
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route.</param>
/// <param name="TrackId">The unique identifier of the track to get, taken from the route.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record GetTrackQuery(
Guid TrackId
string? LibraryId,
string? ArtistId,
string? AlbumId,
string? TrackId
) : IQuery;
@@ -65,18 +65,43 @@ public class GetTrackQueryHandler : IQueryHandler<GetTrackQuery, Result<TrackRes
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(query.TrackId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(query.LibraryId!);
Guid artistId = Guid.Parse(query.ArtistId!);
Guid albumId = Guid.Parse(query.AlbumId!);
Guid trackId = Guid.Parse(query.TrackId!);
// The album is loaded first, so that the artist and the library named by the route are enforced before the track itself is read.
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
if (getAlbumResult.Value is null)
return Errors.Music.TrackNotFound;
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.
if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
return Errors.Music.TrackNotFound;
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null)
return Errors.Music.TrackNotFound;
TrackEntity existingTrack = getTrackResult.Value;
// Resource scoping: the track must belong to the album and the library named by the route, so that a track of another album can never
// be read through this album's route; the mismatch is reported as not found, without disclosing that the track exists elsewhere.
if (existingTrack.AlbumId != albumId || existingTrack.LibraryId != libraryId)
return Errors.Music.TrackNotFound;
// Admins can see the tracks of all libraries; for everyone else, only the tracks of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
userId, new LibraryOwnershipPolicyContext(existingTrack.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
return getTrackResult.Value.ToResponse();
return existingTrack.ToResponse();
}
}
@@ -17,10 +17,44 @@ public class GetTrackQueryValidator : AbstractValidator<GetTrackQuery>
/// </summary>
public GetTrackQueryValidator()
{
// Validates the identifier of the media library the track belongs to, taken from the route.
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(query => query.LibraryId is not null && query.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the artist the album of the track belongs to, taken from the route.
RuleFor(query => query.ArtistId)
.NotEmpty()
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
RuleFor(query => query.ArtistId)
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
.When(query => query.ArtistId is not null && query.ArtistId.Length > 0)
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
// Validates the identifier of the album the track belongs to, taken from the route.
RuleFor(query => query.AlbumId)
.NotEmpty()
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
RuleFor(query => query.AlbumId)
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
.When(query => query.AlbumId is not null && query.AlbumId.Length > 0)
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
// Validates the identifier of the track to get, taken from the route.
RuleFor(query => query.TrackId)
.NotEmpty()
.WithError(Errors.Music.TrackIdCannotBeEmpty)
.Must(trackId => trackId != Guid.Empty)
.WithError(Errors.Music.TrackIdCannotBeEmpty);
RuleFor(query => query.TrackId)
.Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty)
.When(query => query.TrackId is not null && query.TrackId.Length > 0)
.WithError(Errors.Music.TrackIdCannotBeEmpty);
}
}