Adds the playback manifest endpoint

This commit is contained in:
BinaryAlley committed 2026-10-15 14:58:57 +03:00
1 parent 7dc5953e1d
commit d7c1ae60c2
17 files changed
+993 -10

No files matched your search

@@ -11,6 +11,9 @@
- [Stream Track](#stream-track)
- [Stream Track Request](#stream-track-request)
- [Stream Track Response](#stream-track-response)
- [Get Playback Manifest](#get-playback-manifest)
- [Get Playback Manifest Request](#get-playback-manifest-request)
- [Get Playback Manifest Response](#get-playback-manifest-response)
- [Update Track](#update-track)
- [Update Track Request](#update-track-request)
- [Update Track Response](#update-track-response)
@@ -344,6 +347,49 @@ Accept-Ranges: bytes
The response is the raw bytes of the audio file, served with the media type of the file when it is an audio type, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private` and `Vary: Authorization`, together with a `Last-Modified` and an `ETag` derived from the size and the modification time of the file.
### Get Playback Manifest
#### Get Playback Manifest Request
```js
GET 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/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac
Authorization: Bearer <token>
```
Returns the playback manifest of the track identified by the route: the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream, so that a player is told what to fetch and how before it fetches any audio. The `capabilities` query parameter is optional, and its value is a comma separated list of the `container/codec` pairs the player advertises it can demux and decode directly, matched case insensitively, with at most 32 pairs read from one request. When the parameter is absent, empty, or lists no valid pair, the default capabilities of the bundled player apply. The manifest is returned to an Admin, who can build the manifest of the tracks of all libraries, or to the owner of the library of the track.
#### Get Playback Manifest Response
```js
200 Ok
```
```json
{
"trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
"durationInSeconds": 354,
"sourceContainer": "FLAC",
"sourceCodec": "FLAC",
"sampleRate": 44100,
"channels": 2,
"bitDepth": 16,
"replayGainTrackGain": -7.5,
"replayGainTrackPeak": 0.9877,
"replayGainAlbumGain": -6.8,
"replayGainAlbumPeak": 0.9999,
"directPlay": true,
"deliveryContainer": null,
"deliveryCodec": null,
"deliveryShape": null,
"segmentDurationSeconds": null,
"seekable": true,
"streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream"
}
```
When the player can play the stored audio as it is, `directPlay` is `true`, and `deliveryContainer`, `deliveryCodec`, `deliveryShape` and `segmentDurationSeconds` are `null`, because the delivery is the stored file itself. When it cannot, `directPlay` is `false`, and those fields name the container, the codec, the addressing the server produces instead, and the length in seconds of each of its time addressed segments. A normalized delivery is always addressed as `TimeAddressedSegments`, and `segmentDurationSeconds` is the length of each of its segments, so that the server that produces the segments and the player that consumes them agree on it without duplicating the value on both sides. `seekable` reports whether the delivered audio can be seeked by the player. `streamPath` is relative to the API, without a host or a scheme, so that a client reaches the stream through its own application rather than the API server directly.
### Update Track
#### Update Track Request
@@ -0,0 +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/{{$guid}}/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Data transfer object for the stored probe result of a track, containing only the fields a playback manifest is built from.
/// </summary>
[DebuggerDisplay("Container: {Container} Codec: {AudioCodec}")]
public sealed record TrackPlaybackManifestDto
{
/// <summary>
/// Gets the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.
/// </summary>
public string? Container { get; init; }
/// <summary>
/// Gets the audio codec used by the audio file of the track, if applicable.
/// </summary>
public string? AudioCodec { get; init; }
/// <summary>
/// Gets the duration of the audio of the track in seconds.
/// </summary>
public int DurationInSeconds { get; init; }
/// <summary>
/// Gets the sample rate of the audio of the track in Hz.
/// </summary>
public int SampleRate { get; init; }
/// <summary>
/// Gets the number of audio channels of the track.
/// </summary>
public int Channels { get; init; }
/// <summary>
/// Gets the bit depth of the audio of the track, if applicable.
/// </summary>
public int? BitDepth { get; init; }
/// <summary>
/// Gets the ReplayGain track gain of the track, in decibels, if applicable.
/// </summary>
public decimal? ReplayGainTrackGain { get; init; }
/// <summary>
/// Gets the ReplayGain track peak of the track, if applicable.
/// </summary>
public decimal? ReplayGainTrackPeak { get; init; }
/// <summary>
/// Gets the ReplayGain album gain of the track, in decibels, if applicable.
/// </summary>
public decimal? ReplayGainAlbumGain { get; init; }
/// <summary>
/// Gets the ReplayGain album peak of the track, if applicable.
/// </summary>
public decimal? ReplayGainAlbumPeak { get; init; }
}
@@ -74,6 +74,22 @@ public interface ITrackRepository : IRepository<TrackEntity>,
/// </returns>
Task<Result<TrackStreamDto?>> GetTrackStreamInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken);
/// <summary>
/// Gets the stored probe result needed to build the playback manifest of the track identified by <paramref name="trackId"/>, when it belongs to
/// the album identified by <paramref name="albumId"/> and to the media library identified by <paramref name="libraryId"/>, and that album belongs
/// to the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the track must belong to.</param>
/// <param name="albumId">The Id of the album the track must belong to.</param>
/// <param name="artistId">The Id of the artist that must own the album the track belongs to.</param>
/// <param name="trackId">The Id of the track whose playback manifest data is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the <see cref="TrackPlaybackManifestDto"/> of the track, <see langword="null"/> when no track
/// matches the provided identifiers, or an error.
/// </returns>
Task<Result<TrackPlaybackManifestDto?>> GetPlaybackManifestInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken);
/// <summary>
/// Resets the enrichment state of the tracks stored at the provided <paramref name="paths"/> in the media library identified by
/// <paramref name="libraryId"/>, together with their albums and artists, so that they are re-enriched, because their content changed since the last scan.
@@ -14,8 +14,9 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playbac
/// The input is a comma separated list of <c>container/codec</c> pairs, for example
/// <c>mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac</c>. The container and the codec of a pair are matched case
/// insensitively, and a pair that does not name both, with a non-empty container and codec, is ignored. The number of pairs is
/// capped, so a request cannot force an unbounded amount of parsing work. When the input is absent or lists no valid pair, the
/// <see cref="Default"/> capabilities of the bundled player apply.
/// capped, and the input is scanned entry by entry over its own characters, so a request never materializes an array of all its
/// entries and never yields more than a fixed number of capabilities, regardless of its length. When the input is absent or lists no
/// valid pair, the <see cref="Default"/> capabilities of the bundled player apply.
/// </remarks>
public static class PlaybackCapabilitiesParser
{
@@ -58,17 +59,30 @@ public static class PlaybackCapabilitiesParser
return Default;
List<PlaybackCapabilityDto> capabilities = [];
foreach (string entry in capabilitiesInput.Split(CAPABILITY_SEPARATOR, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
// The input is scanned entry by entry over its own characters, so the entries are never all materialized at once: only the
// container and the codec of an accepted pair are allocated, and the number of accepted pairs is capped.
ReadOnlySpan<char> remainingEntries = capabilitiesInput.AsSpan();
while (!remainingEntries.IsEmpty)
{
// The number of pairs is capped, so a single request cannot force an unbounded amount of parsing work.
// The number of accepted pairs is capped, so a request never yields more than a fixed number of capabilities.
if (capabilities.Count >= MAX_CAPABILITY_COUNT)
break;
// Both parts must be named: a container or a codec that is empty (for example "a//b" or "/wav") does not name a pair.
string[] parts = entry.Split(CONTAINER_CODEC_SEPARATOR, StringSplitOptions.TrimEntries);
if (parts.Length != 2 || parts[0].Length == 0 || parts[1].Length == 0)
int entrySeparatorIndex = remainingEntries.IndexOf(CAPABILITY_SEPARATOR);
ReadOnlySpan<char> entry = entrySeparatorIndex < 0 ? remainingEntries : remainingEntries[..entrySeparatorIndex];
remainingEntries = entrySeparatorIndex < 0 ? ReadOnlySpan<char>.Empty : remainingEntries[(entrySeparatorIndex + 1)..];
// A pair names exactly one container and one codec, so exactly one separator must be present, and both parts must be
// named: a container or a codec that is empty (for example "a//b" or "/wav") does not name a pair.
int containerCodecSeparatorIndex = entry.IndexOf(CONTAINER_CODEC_SEPARATOR);
if (containerCodecSeparatorIndex < 0)
continue;
capabilities.Add(new PlaybackCapabilityDto(parts[0], parts[1]));
ReadOnlySpan<char> container = entry[..containerCodecSeparatorIndex].Trim();
ReadOnlySpan<char> codec = entry[(containerCodecSeparatorIndex + 1)..].Trim();
if (container.IsEmpty || codec.IsEmpty || codec.Contains(CONTAINER_CODEC_SEPARATOR))
continue;
capabilities.Add(new PlaybackCapabilityDto(container.ToString(), codec.ToString()));
}
return capabilities.Count == 0 ? Default : capabilities;
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
/// <summary>
/// Query for getting the playback manifest of a track.
/// </summary>
/// <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 whose playback manifest is retrieved, taken from the route.</param>
/// <param name="Capabilities">The container and codec pairs the player advertises it can demux and decode directly, taken from the request, or <see langword="null"/> when it advertises none.</param>
/// <param name="StreamPath">The path of the track stream, relative to the API, taken from the endpoint so that it always matches the stream route.</param>
[DebuggerDisplay("TrackId: {TrackId}")]
public record GetPlaybackManifestQuery(
string? LibraryId,
string? ArtistId,
string? AlbumId,
string? TrackId,
string? Capabilities,
string StreamPath
) : IQuery;
@@ -0,0 +1,125 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
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.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
/// <summary>
/// Handler for the query to get the playback manifest of a track.
/// </summary>
public class GetPlaybackManifestQueryHandler : IQueryHandler<GetPlaybackManifestQuery, Result<PlaybackManifestResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPlaybackFormatService _playbackFormatService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetPlaybackManifestQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackManifestQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="playbackFormatService">Injected service for deciding how a track's audio is delivered to a player.</param>
/// <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 GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetPlaybackManifestQuery> validator)
{
_unitOfWork = unitOfWork;
_playbackFormatService = playbackFormatService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the playback manifest of a track.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the playback manifest of the track, or an error message.
/// </returns>
public async Task<Result<PlaybackManifestResponse>> HandleAsync(GetPlaybackManifestQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// 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!);
// Admins can build the manifest of 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(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// The projection is filtered by the library, the album and the artist named by the route as well as by the track, so a null row
// means the track either does not exist or is not in scope for the route, which is reported as not found without disclosing anything further.
Result<TrackPlaybackManifestDto?> getTrackResult = await _unitOfWork.TrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
if (getTrackResult.Value is null)
return Errors.Music.TrackNotFound;
TrackPlaybackManifestDto track = getTrackResult.Value;
// The stored container and codec of the probe result are the source format the delivery is decided on, and the capabilities
// the player advertises, or the default capabilities of the bundled player when it advertises none, decide the delivery.
IReadOnlyList<PlaybackCapabilityDto> capabilities = PlaybackCapabilitiesParser.Parse(query.Capabilities);
Result<PlaybackDeliveryDecisionDto> decisionResult = _playbackFormatService.DecideDelivery(new PlaybackSourceFormatDto(track.Container, track.AudioCodec), capabilities);
if (decisionResult.IsFailure)
return decisionResult.Errors;
PlaybackDeliveryDecisionDto decision = decisionResult.Value;
bool isDirectPlay = decision.Mode == PlaybackDeliveryMode.DirectPlay;
// Whether the delivered audio can be seeked is a property of the shape it is delivered in, so the rule lives on the shape itself.
bool isSeekable = decision.Shape.IsSeekable();
return new PlaybackManifestResponse(
trackId,
track.DurationInSeconds,
track.Container,
track.AudioCodec,
track.SampleRate,
track.Channels,
track.BitDepth,
track.ReplayGainTrackGain,
track.ReplayGainTrackPeak,
track.ReplayGainAlbumGain,
track.ReplayGainAlbumPeak,
isDirectPlay,
isDirectPlay ? null : decision.Container,
isDirectPlay ? null : decision.Codec,
isDirectPlay ? null : decision.Shape,
decision.Shape == PlaybackDeliveryShape.TimeAddressedSegments ? decision.SegmentDurationSeconds : null,
isSeekable,
query.StreamPath);
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
/// <summary>
/// Validates the needed validation rules for <see cref="GetPlaybackManifestQuery"/>.
/// </summary>
public class GetPlaybackManifestQueryValidator : AbstractValidator<GetPlaybackManifestQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackManifestQueryValidator"/> class.
/// </summary>
public GetPlaybackManifestQueryValidator()
{
// 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 whose playback manifest is retrieved, taken from the route.
RuleFor(query => query.TrackId)
.NotEmpty()
.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,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents a response for the playback manifest of a track, containing the format of its stored audio, the delivery the server decided on for the
/// requesting player, and the path of the track stream, so that a player is told what to fetch and how before it fetches any audio.
/// </summary>
/// <param name="TrackId">The Id of the track the manifest describes.</param>
/// <param name="DurationInSeconds">The duration of the audio of the track, in seconds.</param>
/// <param name="SourceContainer">The container of the audio file of the track, as stored by the probe, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional.</param>
/// <param name="SourceCodec">The codec of the audio of the track, as stored by the probe. Optional.</param>
/// <param name="SampleRate">The sample rate of the audio of the track, in Hz.</param>
/// <param name="Channels">The number of audio channels of the track.</param>
/// <param name="BitDepth">The bit depth of the audio of the track. Optional.</param>
/// <param name="ReplayGainTrackGain">The ReplayGain track gain of the track, in decibels. Optional.</param>
/// <param name="ReplayGainTrackPeak">The ReplayGain track peak of the track. Optional.</param>
/// <param name="ReplayGainAlbumGain">The ReplayGain album gain of the track, in decibels. Optional.</param>
/// <param name="ReplayGainAlbumPeak">The ReplayGain album peak of the track. Optional.</param>
/// <param name="DirectPlay">Whether the player can play the stored audio as it is, without the server changing its container or its codec.</param>
/// <param name="DeliveryContainer">The container of the audio the server delivers, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
/// <param name="DeliveryCodec">The codec of the audio the server delivers, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
/// <param name="DeliveryShape">The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. <see langword="null"/> otherwise.</param>
/// <param name="Seekable">Whether the delivered audio can be seeked by the player.</param>
/// <param name="StreamPath">The path of the track stream, relative to the API, without a host or a scheme, so that a client never reaches the API directly.</param>
[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")]
public sealed record PlaybackManifestResponse(
Guid TrackId,
int DurationInSeconds,
string? SourceContainer,
string? SourceCodec,
int SampleRate,
int Channels,
int? BitDepth,
decimal? ReplayGainTrackGain,
decimal? ReplayGainTrackPeak,
decimal? ReplayGainAlbumGain,
decimal? ReplayGainAlbumPeak,
bool DirectPlay,
string? DeliveryContainer,
string? DeliveryCodec,
PlaybackDeliveryShape? DeliveryShape,
int? SegmentDurationSeconds,
bool Seekable,
string StreamPath
);
@@ -357,6 +357,43 @@ internal sealed class TrackRepository : ITrackRepository
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the stored probe result needed to build the playback manifest of the track identified by <paramref name="trackId"/>, when it belongs to
/// the album identified by <paramref name="albumId"/> and to the media library identified by <paramref name="libraryId"/>, and that album belongs
/// to the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the track must belong to.</param>
/// <param name="albumId">The Id of the album the track must belong to.</param>
/// <param name="artistId">The Id of the artist that must own the album the track belongs to.</param>
/// <param name="trackId">The Id of the track whose playback manifest data is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the <see cref="TrackPlaybackManifestDto"/> of the track, <see langword="null"/> when no track
/// matches the provided identifiers, or an error.
/// </returns>
public async Task<Result<TrackPlaybackManifestDto?>> GetPlaybackManifestInfoAsync(Guid libraryId, Guid albumId, Guid artistId, Guid trackId, CancellationToken cancellationToken)
{
// The projection is flat and untracked, and the album is joined both to scope the track by its artist and to project the artist Id, so a track
// that is not in the named library, album and artist simply yields no row.
return await _luminaDbContext.Tracks
.AsNoTracking()
.Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId)
.Select(track => new TrackPlaybackManifestDto
{
Container = track.Container,
AudioCodec = track.AudioCodec,
DurationInSeconds = track.DurationInSeconds,
SampleRate = track.SampleRate,
Channels = track.Channels,
BitDepth = track.BitDepth,
ReplayGainTrackGain = track.ReplayGainTrackGain,
ReplayGainTrackPeak = track.ReplayGainTrackPeak,
ReplayGainAlbumGain = track.ReplayGainAlbumGain,
ReplayGainAlbumPeak = track.ReplayGainAlbumPeak
})
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the track identified by <paramref name="id"/>, together with its owned collections and contributions, by the database cascade.
/// </summary>
@@ -0,0 +1,21 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Playback;
/// <summary>
/// Extension methods for <see cref="PlaybackDeliveryShape"/>.
/// </summary>
public static class PlaybackDeliveryShapeExtensions
{
/// <summary>
/// Gets whether the audio delivered in the provided <paramref name="shape"/> can be seeked by a player.
/// </summary>
/// <param name="shape">The shape the delivered audio is addressed and seeked by.</param>
/// <returns>
/// <see langword="true"/> when the shape can be seeked, otherwise <see langword="false"/>. Audio delivered as the original file is
/// seeked by byte range, and audio delivered as time addressed segments is seeked by segment, so both of the shapes the server
/// produces are seekable; a future shape that cannot be seeked reports <see langword="false"/>.
/// </returns>
public static bool IsSeekable(this PlaybackDeliveryShape shape)
{
return shape is PlaybackDeliveryShape.ByteRangeSeekable or PlaybackDeliveryShape.TimeAddressedSegments;
}
}
@@ -15,5 +15,6 @@ public static partial class ApiRoutes
public const string UPDATE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}";
public const string DELETE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}";
public const string STREAM_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream";
public const string GET_PLAYBACK_MANIFEST = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest";
}
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest</c> route.
/// </summary>
public class GetPlaybackManifestEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetPlaybackManifestQuery, Result<PlaybackManifestResponse>> _getPlaybackManifestQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpoint"/> class.
/// </summary>
/// <param name="getPlaybackManifestQueryHandler">Injected service for handling get playback manifest queries.</param>
public GetPlaybackManifestEndpoint(IQueryHandler<GetPlaybackManifestQuery, Result<PlaybackManifestResponse>> getPlaybackManifestQueryHandler)
{
_getPlaybackManifestQueryHandler = getPlaybackManifestQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Tracks.GET_PLAYBACK_MANIFEST);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the playback manifest of the track identified by the route.
/// </summary>
/// <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(EmptyRequest request, CancellationToken cancellationToken)
{
// 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();
// The capabilities the player advertises are optional; an absent parameter is an empty value, which the handler treats as no capabilities.
string capabilities = HttpContext.Request.Query["capabilities"].ToString();
// The stream path is filled in from the stream route itself, so that the manifest and the stream can never disagree on the shape of the route.
// It is kept relative, without a host, a scheme or the version prefix, so that a client reaches the stream through its own application.
string streamPath = ApiRoutes.Tracks.STREAM_TRACK
.Replace("{libraryId}", libraryId, StringComparison.Ordinal)
.Replace("{artistId}", artistId, StringComparison.Ordinal)
.Replace("{albumId}", albumId, StringComparison.Ordinal)
.Replace("{trackId}", trackId, StringComparison.Ordinal);
GetPlaybackManifestQuery query = new(libraryId, artistId, albumId, trackId, capabilities, streamPath);
Result<PlaybackManifestResponse> result = await _getPlaybackManifestQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,161 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPlaybackManifestEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackManifestEndpointSummary : Summary<GetPlaybackManifestEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointSummary"/> class.
/// </summary>
public GetPlaybackManifestEndpointSummary()
{
Summary = "Retrieves the playback manifest of a track.";
Description = "Retrieves the playback manifest of a track, containing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream. The player advertises the container and codec pairs it can demux and decode directly in the optional capabilities query parameter, as a comma separated list of container/codec pairs; when the parameter is absent, empty or lists no valid pair, the default capabilities of the bundled player apply. The manifest is returned to an Admin, who can build the manifest of the tracks of all libraries, or to the owner of the library of the track.";
ResponseParam<PlaybackManifestResponse>(r => r.TrackId, "The Id of the track the manifest describes.");
ResponseParam<PlaybackManifestResponse>(r => r.DurationInSeconds, "The duration of the audio of the track, in seconds.");
ResponseParam<PlaybackManifestResponse>(r => r.SourceContainer, "The container of the stored audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV.");
ResponseParam<PlaybackManifestResponse>(r => r.SourceCodec, "The codec of the stored audio of the track.");
ResponseParam<PlaybackManifestResponse>(r => r.SampleRate, "The sample rate of the audio of the track, in Hz.");
ResponseParam<PlaybackManifestResponse>(r => r.Channels, "The number of audio channels of the track.");
ResponseParam<PlaybackManifestResponse>(r => r.BitDepth, "The bit depth of the audio of the track, if applicable.");
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainTrackGain, "The ReplayGain track gain of the track, in decibels, if applicable.");
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainTrackPeak, "The ReplayGain track peak of the track, if applicable.");
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainAlbumGain, "The ReplayGain album gain of the track, in decibels, if applicable.");
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainAlbumPeak, "The ReplayGain album peak of the track, if applicable.");
ResponseParam<PlaybackManifestResponse>(r => r.DirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec.");
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryContainer, "The container of the audio the server delivers, when the delivery is not a direct play.");
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryCodec, "The codec of the audio the server delivers, when the delivery is not a direct play.");
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryShape, "The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play.");
ResponseParam<PlaybackManifestResponse>(r => r.SegmentDurationSeconds, "The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments.");
ResponseParam<PlaybackManifestResponse>(r => r.Seekable, "Whether the delivered audio can be seeked by the player.");
ResponseParam<PlaybackManifestResponse>(r => r.StreamPath, "The path of the track stream, relative to the API, without a host or a scheme.");
Response(200, "The playback manifest of the track is returned.",
example: new PlaybackManifestResponse(
TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
DurationInSeconds: 354,
SourceContainer: "FLAC",
SourceCodec: "FLAC",
SampleRate: 44100,
Channels: 2,
BitDepth: 16,
ReplayGainTrackGain: -7.5m,
ReplayGainTrackPeak: 0.9877m,
ReplayGainAlbumGain: -6.8m,
ReplayGainAlbumPeak: 0.9999m,
DirectPlay: false,
DeliveryContainer: "MP3",
DeliveryCodec: "MP3",
DeliveryShape: PlaybackDeliveryShape.TimeAddressedSegments,
SegmentDurationSeconds: 6,
Seekable: true,
StreamPath: "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream"
)
);
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library, or because the server cannot produce any format the player advertises it supports.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Forbidden",
status = 403,
detail = "NoSupportedPlaybackFormat",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(404, "The request failed because the track or its media library does not exist, or the track does not belong to the library, album and artist named by the route.", "application/problem+json",
example: new[]
{
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()}/playback-manifest",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"ArtistIdCannotBeEmpty",
"AlbumIdCannotBeEmpty",
"TrackIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
+1
View File
@@ -286,6 +286,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657
ProjectSection(SolutionItems) = preProject
..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http
..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http
..\docs\technical\requests\library\audio-library\music-library\tracks\GetPlaybackManifest.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetPlaybackManifest.http
..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http
..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http
..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http
@@ -50,6 +50,13 @@ public class TrackEntityFixture
/// <param name="includeReReleaseYear">Whether the re-release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
/// <param name="metadataStatus">Optional. The metadata enrichment status of the track.</param>
/// <param name="audioCodec">Optional. The audio codec of the track.</param>
/// <param name="includeAudioCodec">Whether the audio codec should be included, or forced to <see langword="null"/>.</param>
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain of the track, in decibels.</param>
/// <param name="replayGainTrackPeak">Optional. The ReplayGain track peak of the track.</param>
/// <param name="replayGainAlbumGain">Optional. The ReplayGain album gain of the track, in decibels.</param>
/// <param name="replayGainAlbumPeak">Optional. The ReplayGain album peak of the track.</param>
/// <param name="includeReplayGain">Whether the ReplayGain values should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="TrackEntity"/>.</returns>
public TrackEntity Create(
Guid? id = null,
@@ -69,7 +76,14 @@ public class TrackEntityFixture
bool includeReReleaseDate = true,
bool includeReReleaseYear = true,
bool includeContainer = true,
MetadataStatus? metadataStatus = null)
MetadataStatus? metadataStatus = null,
string? audioCodec = null,
bool includeAudioCodec = true,
decimal? replayGainTrackGain = null,
decimal? replayGainTrackPeak = null,
decimal? replayGainAlbumGain = null,
decimal? replayGainAlbumPeak = null,
bool includeReplayGain = true)
{
Guid resolvedId = id ?? Guid.NewGuid();
Guid resolvedAlbumId = albumId ?? Guid.NewGuid();
@@ -114,8 +128,12 @@ public class TrackEntityFixture
.RuleFor(x => x.SampleRate, f => f.PickRandom(44100, 48000, 96000))
.RuleFor(x => x.Channels, f => f.PickRandom(1, 2, 6))
.RuleFor(x => x.BitDepth, Random.Shared.Next(8, 32))
.RuleFor(x => x.AudioCodec, f => f.PickRandom("FLAC", "MP3", "AAC", "ALAC"))
.RuleFor(x => x.AudioCodec, f => includeAudioCodec ? (audioCodec ?? f.PickRandom("FLAC", "MP3", "AAC", "ALAC")) : null)
.RuleFor(x => x.Container, f => includeContainer ? (container ?? f.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV")) : null)
.RuleFor(x => x.ReplayGainTrackGain, f => includeReplayGain ? (replayGainTrackGain ?? f.Random.Decimal(-20m, 0m)) : null)
.RuleFor(x => x.ReplayGainTrackPeak, f => includeReplayGain ? (replayGainTrackPeak ?? f.Random.Decimal(0m, 1.5m)) : null)
.RuleFor(x => x.ReplayGainAlbumGain, f => includeReplayGain ? (replayGainAlbumGain ?? f.Random.Decimal(-20m, 0m)) : null)
.RuleFor(x => x.ReplayGainAlbumPeak, f => includeReplayGain ? (replayGainAlbumPeak ?? f.Random.Decimal(0m, 1.5m)) : null)
.RuleFor(x => x.Bitrate, Random.Shared.Next(96, 1411))
.RuleFor(x => x.TrackNumber, f => trackNumber ?? f.Random.Int(1, 20))
.RuleFor(x => x.DiscNumber, Random.Shared.Next(1, 3))
@@ -0,0 +1,274 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
/// <summary>
/// Contains integration tests for the <see cref="GetPlaybackManifestEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackManifestEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackManifestEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPlaybackManifestEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client of the test.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetPlaybackManifest_WhenTrackBelongsToAnOwnedLibrary_ShouldReturnDirectPlayManifest()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(
userId,
container: "FLAC",
audioCodec: "FLAC",
replayGainTrackGain: -7.5m,
replayGainTrackPeak: 0.9877m,
replayGainAlbumGain: -6.8m,
replayGainAlbumPeak: 0.9999m);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaybackManifestResponse? manifest = await ReadManifestAsync(response);
Assert.NotNull(manifest);
Assert.Equal(trackId, manifest!.TrackId);
Assert.True(manifest.DirectPlay);
Assert.Equal("FLAC", manifest.SourceContainer);
Assert.Equal("FLAC", manifest.SourceCodec);
Assert.Equal(-7.5m, manifest.ReplayGainTrackGain);
Assert.Equal(0.9877m, manifest.ReplayGainTrackPeak);
Assert.Equal(-6.8m, manifest.ReplayGainAlbumGain);
Assert.Equal(0.9999m, manifest.ReplayGainAlbumPeak);
Assert.Null(manifest.DeliveryContainer);
Assert.Null(manifest.DeliveryCodec);
Assert.Null(manifest.DeliveryShape);
Assert.Null(manifest.SegmentDurationSeconds);
Assert.True(manifest.Seekable);
Assert.Equal($"/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream", manifest.StreamPath);
Assert.DoesNotContain("http", manifest.StreamPath, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetPlaybackManifest_WhenPlayerCannotDecodeTheStoredCodec_ShouldReturnTranscodedDelivery()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "OGG", audioCodec: "OPUS");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
PlaybackManifestResponse? manifest = await ReadManifestAsync(response);
Assert.NotNull(manifest);
Assert.Equal(trackId, manifest!.TrackId);
Assert.False(manifest.DirectPlay);
Assert.Equal("MP3", manifest.DeliveryContainer);
Assert.Equal("MP3", manifest.DeliveryCodec);
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, manifest.DeliveryShape);
Assert.Equal(6, manifest.SegmentDurationSeconds);
Assert.True(manifest.Seekable);
}
[Fact]
public async Task GetPlaybackManifest_WhenTrackIsRequestedThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, container: "FLAC", audioCodec: "FLAC");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/playback-manifest");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = await ReadProblemDetailsAsync(response);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("TrackNotFound", problemDetails.Detail);
}
[Fact]
public async Task GetPlaybackManifest_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, container: "FLAC", audioCodec: "FLAC");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(await response.Content.ReadAsStringAsync(), _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
}
[Fact]
public async Task GetPlaybackManifest_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/playback-manifest");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="container">The container of the audio file of the seeded track.</param>
/// <param name="audioCodec">The codec of the audio of the seeded track.</param>
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain of the seeded track, in decibels.</param>
/// <param name="replayGainTrackPeak">Optional. The ReplayGain track peak of the seeded track.</param>
/// <param name="replayGainAlbumGain">Optional. The ReplayGain album gain of the seeded track, in decibels.</param>
/// <param name="replayGainAlbumPeak">Optional. The ReplayGain album peak of the seeded track.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(
Guid userId,
string container,
string audioCodec,
decimal? replayGainTrackGain = null,
decimal? replayGainTrackPeak = null,
decimal? replayGainAlbumGain = null,
decimal? replayGainAlbumPeak = null)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
dbContext.Tracks.Add(_trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
container: container,
audioCodec: audioCodec,
title: "A Track",
includeMetadata: false,
replayGainTrackGain: replayGainTrackGain,
replayGainTrackPeak: replayGainTrackPeak,
replayGainAlbumGain: replayGainAlbumGain,
replayGainAlbumPeak: replayGainAlbumPeak));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user and its username.</returns>
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return (userId, username);
}
/// <summary>
/// Reads the playback manifest of a response.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized playback manifest.</returns>
private async Task<PlaybackManifestResponse?> ReadManifestAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<PlaybackManifestResponse>(content, _jsonOptions);
}
/// <summary>
/// Reads the problem details of a response.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized problem details.</returns>
private async Task<Microsoft.AspNetCore.Mvc.ProblemDetails?> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Removes the test user created for the tests.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}