mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 12:11:10 +00:00
Adds the playback manifest endpoint
This commit is contained in:
1 parent
7dc5953e1d
commit
d7c1ae60c2
17 files changed
+993
-10
No files matched your search
+62
@@ -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; }
|
||||
}
|
||||
+16
@@ -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.
|
||||
|
||||
+22
-8
@@ -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;
|
||||
|
||||
+25
@@ -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;
|
||||
+125
@@ -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);
|
||||
}
|
||||
}
|
||||
+60
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user