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

@@ -2,15 +2,6 @@
- [Lumina API](#lumina-api)
- [Track](#track)
- [Get Album Tracks](#get-album-tracks)
- [Get Album Tracks Request](#get-album-tracks-request)
- [Get Album Tracks Response](#get-album-tracks-response)
- [Get Album Tracks Lite](#get-album-tracks-lite)
- [Get Album Tracks Lite Request](#get-album-tracks-lite-request)
- [Get Album Tracks Lite Response](#get-album-tracks-lite-response)
- [Add Track](#add-track)
- [Add Track Request](#add-track-request)
- [Add Track Response](#add-track-response)
- [Get Track](#get-track)
- [Get Track Request](#get-track-request)
- [Get Track Response](#get-track-response)
@@ -21,227 +12,6 @@
## Track
### Get Album Tracks
#### Get Album Tracks Request
```js
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks
```
#### Get Album Tracks Response
```js
200 Ok
```
```json
[
{
"id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"releaseInfo": { "originalReleaseDate": "1975-10-31", "originalReleaseYear": 1975, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", "releaseVersion": "Original" },
"language": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"originalLanguage": { "languageCode": "en", "languageName": "English", "nativeName": "English" },
"tags": [ { "name": "classic" }, { "name": "epic" } ],
"genres": [ { "name": "Rock" }, { "name": "Progressive Rock" } ],
"durationInSeconds": 354,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980
},
"trackNumber": 1,
"discNumber": 1,
"script": "Latn",
"key": "CMajor",
"bpm": 72,
"work": "Bohemian Rhapsody",
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"createdOnUtc": "2025-01-01T12:00:00.0000000Z",
"updatedOnUtc": null,
"contributors": [
{
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Vocals"
},
{
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Guitar"
}
],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
},
{
"value": 4.8,
"maxValue": 5,
"source": "LastFm",
"voteCount": 1234
}
],
"moods": [
{
"name": "dramatic"
},
{
"name": "anxious"
}
],
"isrcs": [
{
"value": "GBUM71029604"
}
]
}
]
```
### Get Album Tracks Lite
#### Get Album Tracks Lite Request
```js
GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/lite?currentPage=1&perPage=10
```
| Query Parameter | Type | Description |
| --- | --- | --- |
| `currentPage` | `int` | Optional. The page of results to retrieve. |
| `perPage` | `int` | Optional. The maximum number of tracks to retrieve per page. |
#### Get Album Tracks Lite Response
```js
200 Ok
```
```json
{
"data": [
{
"id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
"title": "Bohemian Rhapsody",
"trackNumber": 1,
"discNumber": 1
}
],
"currentPage": 1,
"perPage": 10,
"count": 1,
"numberOfPages": 1
}
```
### Add Track
#### Add Track Request
```js
POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks
```
```json
{
"path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac",
"metadata": {
"title": "Bohemian Rhapsody",
"originalTitle": "Bohemian Rhapsody",
"description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.",
"durationInSeconds": 354,
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"audioCodec": "FLAC",
"bitrate": 980,
"releaseInfo": {
"originalReleaseDate": "1975-10-31",
"originalReleaseYear": 1975,
"reReleaseDate": null,
"reReleaseYear": null,
"releaseCountry": "GB",
"releaseVersion": "Original"
},
"language": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"originalLanguage": {
"languageCode": "en",
"languageName": "English",
"nativeName": "English"
},
"genres": [
{ "name": "Rock" },
{ "name": "Progressive Rock" }
],
"tags": [
{ "name": "classic" },
{ "name": "epic" }
]
},
"trackNumber": 1,
"discNumber": 1,
"script": "Latn",
"key": "CMajor",
"bpm": 72,
"work": "Bohemian Rhapsody",
"musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
"musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
"musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c",
"contributors": [
{ "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" },
{ "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" }
],
"ratings": [
{
"value": 4.5,
"maxValue": 5,
"source": "MusicBrainz",
"voteCount": 2345
},
{
"value": 4.8,
"maxValue": 5,
"source": "LastFm",
"voteCount": 1234
}
],
"moods": [
{ "name": "dramatic" },
{ "name": "anxious" }
],
"isrcs": [
{ "value": "GBUM71029604" }
]
}
```
#### Add Track Response
```js
201 Created
```
The response carries the full details of the newly created track, using the same shape as the [Get Track Response](#get-track-response).
### Get Track
#### Get Track Request
@@ -427,11 +197,11 @@ The response carries the full details of the updated track, using the same shape
### Delete Track
```js
DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f
DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{trackId}
```
```js
200 Ok
```
Deletes the track identified by the path.
Deletes the track identified by the path.
@@ -1,2 +1,2 @@
DELETE {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f
DELETE {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -1,2 +1,2 @@
GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f
GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -19,8 +19,7 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
public interface ITrackRepository : IRepository<TrackEntity>,
IInsertRepositoryAction<TrackEntity>,
IUpdateRepositoryAction<TrackEntity>,
IGetByIdRepositoryAction<TrackEntity, Guid>,
IDeleteByIdRepositoryAction<Guid>
IGetByIdRepositoryAction<TrackEntity, Guid>
{
/// <summary>
/// Gets all the tracks of the album identified by <paramref name="albumId"/>.
@@ -1,23 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Extension methods for converting <see cref="DeleteTrackRequest"/>.
/// </summary>
public static class DeleteTrackRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="DeleteTrackCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static DeleteTrackCommand ToCommand(this DeleteTrackRequest request)
{
return new DeleteTrackCommand(
request.TrackId);
}
}
@@ -1,23 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Extension methods for converting <see cref="GetTrackRequest"/>.
/// </summary>
public static class GetTrackRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetTrackQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetTrackQuery ToQuery(this GetTrackRequest request)
{
return new GetTrackQuery(
request.TrackId);
}
}
@@ -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);
}
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Data transfer object for a mood of a media element.
/// </summary>
/// <param name="Name">The name of the mood.</param>
[DebuggerDisplay("Name: {Name}")]
public record MoodDto(
string? Name
);
@@ -1,19 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Represents a request to delete a track by the specified Id.
/// </summary>
/// <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.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record DeleteTrackRequest(
Guid ArtistId,
Guid AlbumId,
Guid TrackId
);
@@ -1,19 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Represents a request to get a track by the specified Id.
/// </summary>
/// <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 retrieve.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record GetTrackRequest(
Guid ArtistId,
Guid AlbumId,
Guid TrackId
);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class MakesTrackPathUniquePerLibrary : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Tracks_LibraryId_Path",
table: "Tracks");
migrationBuilder.CreateIndex(
name: "IX_Tracks_LibraryId_Path",
table: "Tracks",
columns: new[] { "LibraryId", "Path" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Tracks_LibraryId_Path",
table: "Tracks");
migrationBuilder.CreateIndex(
name: "IX_Tracks_LibraryId_Path",
table: "Tracks",
columns: new[] { "LibraryId", "Path" });
}
}
}
@@ -194,28 +194,12 @@ internal sealed class TrackRepository : ITrackRepository
.Include(track => track.Genres)
.Include(track => track.Moods)
.Include(track => track.Isrcs)
.Include(track => track.Contributors);
.Include(track => track.Contributors)
.AsSplitQuery();
}
return await query.FirstOrDefaultAsync(track => track.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the track identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the track to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
TrackEntity? track = await _luminaDbContext.Tracks
.FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == id, cancellationToken).ConfigureAwait(false);
if (track is null)
return Errors.Music.TrackNotFound;
_luminaDbContext.Tracks.Remove(track);
return Result.Deleted;
}
/// <summary>
/// Gets all the tracks of the album identified by <paramref name="albumId"/>.
/// </summary>
@@ -231,6 +215,7 @@ internal sealed class TrackRepository : ITrackRepository
.Include(track => track.Moods)
.Include(track => track.Isrcs)
.Include(track => track.Contributors)
.AsSplitQuery()
.Where(track => track.AlbumId == albumId)
.OrderBy(track => track.DiscNumber)
.ThenBy(track => track.TrackNumber)
@@ -299,7 +299,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks"
},
new
{
@@ -307,7 +307,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
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"
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks"
},
new
{
@@ -315,7 +315,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks"
}
}
);
@@ -327,7 +327,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
@@ -341,7 +341,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
title = "General.NotFound",
status = 404,
detail = "AlbumNotFound",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
@@ -350,7 +350,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
@@ -359,7 +359,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
title = "General.NotFound",
status = 404,
detail = "MediaContributorNotFound",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
@@ -374,7 +374,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
title = "General.Conflict",
status = 409,
detail = "TrackAlreadyExists",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
@@ -383,7 +383,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
title = "General.Conflict",
status = 409,
detail = "UniqueConstraintViolation",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
@@ -396,7 +396,7 @@ public class AddTrackEndpointSummary : Summary<AddTrackEndpoint, AddTrackRequest
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks",
errors = new Dictionary<string, string[]>
{
{
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
@@ -14,9 +12,9 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
/// <summary>
/// API endpoint for the <c>/artists/{artistId}/albums/{albumId}/tracks/{trackId}</c> route.
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}</c> route.
/// </summary>
public class DeleteTrackEndpoint : BaseEndpoint<DeleteTrackRequest, IResult>
public class DeleteTrackEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<DeleteTrackCommand, Result<Deleted>> _deleteTrackCommandHandler;
@@ -43,11 +41,17 @@ public class DeleteTrackEndpoint : BaseEndpoint<DeleteTrackRequest, IResult>
/// <summary>
/// Deletes a track by Id.
/// </summary>
/// <param name="request">The request containing the id of the track to be deleted.</param>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(DeleteTrackRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
Result<Deleted> result = await _deleteTrackCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString();
Result<Deleted> result = await _deleteTrackCommandHandler
.HandleAsync(new DeleteTrackCommand(libraryId, artistId, albumId, trackId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -12,7 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
/// Class used for providing a textual description for the <see cref="DeleteTrackEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteTrackEndpointSummary : Summary<DeleteTrackEndpoint, DeleteTrackRequest>
public class DeleteTrackEndpointSummary : Summary<DeleteTrackEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteTrackEndpointSummary"/> class.
@@ -22,16 +21,6 @@ public class DeleteTrackEndpointSummary : Summary<DeleteTrackEndpoint, DeleteTra
Summary = "Deletes an existing track.";
Description = "Deletes the track identified by the request. The track is deleted by an Admin, who can delete the tracks of all libraries, or by the owner of the library of the track.";
ExampleRequest = new DeleteTrackRequest(
ArtistId: Guid.NewGuid(),
AlbumId: Guid.NewGuid(),
TrackId: Guid.NewGuid()
);
RequestParam(r => r.ArtistId, "The unique identifier of the artist the album of the track belongs to, taken from the route.");
RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to, taken from the route.");
RequestParam(r => r.TrackId, "The Id of the track to delete, taken from the route. Required.");
Response(200, "The track was successfully deleted.");
Response(401, "Authentication required.", "application/problem+json",
@@ -42,16 +31,16 @@ public class DeleteTrackEndpointSummary : Summary<DeleteTrackEndpoint, DeleteTra
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
{
@@ -59,7 +48,7 @@ public class DeleteTrackEndpointSummary : Summary<DeleteTrackEndpoint, DeleteTra
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()}"
}
}
);
@@ -71,20 +60,50 @@ public class DeleteTrackEndpointSummary : Summary<DeleteTrackEndpoint, DeleteTra
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"
}
);
Response(404, "The request failed because the requested track does not exist.", "application/problem+json",
example: new
Response(404, "The request failed because the requested artist, album, track, or their media library does not exist.", "application/problem+json",
example: new[]
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "TrackNotFound",
instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "ArtistNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "AlbumNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "TrackNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
@@ -95,12 +114,15 @@ public class DeleteTrackEndpointSummary : Summary<DeleteTrackEndpoint, DeleteTra
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[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"ArtistIdCannotBeEmpty",
"AlbumIdCannotBeEmpty",
"TrackIdCannotBeEmpty"
}
}
@@ -1,9 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
@@ -18,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
/// <summary>
/// API endpoint for the <c>/artists/{artistId}/albums/{albumId}/tracks/{trackId}</c> route.
/// </summary>
public class GetTrackEndpoint : BaseEndpoint<GetTrackRequest, IResult>
public class GetTrackEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly IQueryHandler<GetTrackQuery, Result<TrackResponse>> _getTrackQueryHandler;
@@ -45,11 +43,17 @@ public class GetTrackEndpoint : BaseEndpoint<GetTrackRequest, IResult>
/// <summary>
/// Gets a track by Id.
/// </summary>
/// <param name="request">The request containing the id of the track to be retrieved.</param>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetTrackRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
Result<TrackResponse> result = await _getTrackQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
// Take unique identifiers from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString();
GetTrackQuery query = new(libraryId, artistId, albumId, trackId);
Result<TrackResponse> result = await _getTrackQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -4,7 +4,6 @@ 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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
@@ -20,7 +19,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
/// Class used for providing a textual description for the <see cref="GetTrackEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, GetTrackRequest>
public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackEndpointSummary"/> class.
@@ -28,17 +27,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, GetTrackRequest
public GetTrackEndpointSummary()
{
Summary = "Gets a track by its Id.";
Description = "Returns the full details of the track identified by the request. The track is returned to an Admin, who can see the tracks of all libraries, or to the owner of the library of the track.";
ExampleRequest = new GetTrackRequest(
ArtistId: Guid.NewGuid(),
AlbumId: Guid.NewGuid(),
TrackId: Guid.NewGuid()
);
RequestParam(r => r.ArtistId, "The unique identifier of the artist the album of the track belongs to, taken from the route.");
RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to, taken from the route.");
RequestParam(r => r.TrackId, "The Id of the track to get. Required.");
Description = "Returns the full details of the track identified by the route. The track is returned to an Admin, who can see the tracks of all libraries, or to the owner of the library of the track.";
ResponseParam<TrackResponse>(r => r.Id, "The Id of the track.");
ResponseParam<TrackResponse>(r => r.AlbumId, "The Id of the album the track belongs to.");
@@ -180,7 +169,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, GetTrackRequest
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
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()}"
},
new
{
@@ -188,7 +177,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, GetTrackRequest
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}"
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"
},
new
{
@@ -196,7 +185,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, GetTrackRequest
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()}"
}
}
);
@@ -208,7 +197,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, GetTrackRequest
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"
}
);
@@ -220,7 +209,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, GetTrackRequest
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"
}
);
@@ -232,7 +221,7 @@ public class GetTrackEndpointSummary : Summary<GetTrackEndpoint, GetTrackRequest
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[]>
{
{