diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDtoFixture.cs
new file mode 100644
index 00000000..10ca100f
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDtoFixture.cs
@@ -0,0 +1,75 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class NormalizedTrackDtoFixture
+{
+ private readonly Faker _faker = new();
+ private readonly NormalizedTrackSegmentDtoFixture _normalizedTrackSegmentDtoFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the track whose audio the cached entry holds.
+ /// Optional. The opaque identifier of the cached entry that holds the normalized audio.
+ /// Optional. The way the audio is delivered.
+ /// Optional. The container of the delivered audio.
+ /// Optional. The codec of the delivered audio.
+ /// Optional. The duration of each segment of the delivered audio, in seconds.
+ /// Optional. The duration of the produced and cached audio, in seconds.
+ /// Optional. The segments that make up the delivered audio, in playback order.
+ /// Whether the segments should be included, or forced to an empty collection.
+ /// The created .
+ public NormalizedTrackDto Create(
+ Guid? trackId = null,
+ string? cacheId = null,
+ PlaybackDeliveryMode? mode = null,
+ string? container = null,
+ string? codec = null,
+ int? segmentDurationSeconds = null,
+ int? durationInSeconds = null,
+ IReadOnlyList? segments = null,
+ bool includeSegments = true)
+ {
+ int resolvedSegmentDurationSeconds = segmentDurationSeconds ?? _faker.Random.Int(1, 30);
+ List generatedSegments = [];
+ int generatedSegmentCount = _faker.Random.Int(1, 6);
+ for (int index = 0; index < generatedSegmentCount; index++)
+ generatedSegments.Add(_normalizedTrackSegmentDtoFixture.Create(
+ index: index,
+ startSeconds: index * resolvedSegmentDurationSeconds,
+ durationSeconds: resolvedSegmentDurationSeconds));
+
+ return new NormalizedTrackDto(
+ trackId ?? _faker.Random.Guid(),
+ cacheId ?? _faker.Random.Guid().ToString("N") + _faker.Random.Guid().ToString("N"),
+ mode ?? _faker.PickRandom(PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode),
+ container ?? _faker.PickRandom("MP3", "AAC", "FLAC", "WAV", "OGG"),
+ codec ?? _faker.PickRandom("MP3", "AAC", "FLAC", "PCM", "OPUS"),
+ resolvedSegmentDurationSeconds,
+ durationInSeconds ?? _faker.Random.Int(1, 3600),
+ includeSegments ? (segments ?? generatedSegments) : []);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDtoFixture.cs
new file mode 100644
index 00000000..d9882e5d
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDtoFixture.cs
@@ -0,0 +1,102 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class NormalizedTrackRequestDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the track whose audio is normalized.
+ /// Optional. The Id of the user whose request starts the production.
+ /// Optional. The file system path of the stored audio file of the track.
+ /// Optional. The content locations the source path is allowed to be inside.
+ /// Optional. The container of the stored audio file, as captured by the probe.
+ /// Optional. The way the audio is delivered.
+ /// Optional. The container of the delivered audio.
+ /// Optional. The codec of the delivered audio.
+ /// Optional. The duration of each segment of the delivered audio, in seconds.
+ /// Optional. The duration of the audio of the track, in seconds.
+ /// Optional. The stored audio bitrate of the track, in kbps.
+ /// Optional. The sample rate of the stored audio of the track, in Hz.
+ /// Optional. The number of audio channels of the track.
+ /// Optional. The bit depth of the stored audio of the track.
+ /// Optional. The quality cap applied to the delivered audio when it has to be re-encoded.
+ /// Optional. The length the source file had when the delivery was declared, in bytes.
+ /// Optional. The last modification time the source file had when the delivery was declared.
+ /// Whether the source container should be included, or forced to .
+ /// Whether the bitrate should be included, or forced to .
+ /// Whether the bit depth should be included, or forced to .
+ /// The created .
+ public NormalizedTrackRequestDto Create(
+ Guid? trackId = null,
+ Guid? userId = null,
+ string? sourcePath = null,
+ IReadOnlyList? allowedRoots = null,
+ string? sourceContainer = null,
+ PlaybackDeliveryMode? mode = null,
+ string? container = null,
+ string? codec = null,
+ int? segmentDurationSeconds = null,
+ int? durationInSeconds = null,
+ int? bitrate = null,
+ int? sampleRate = null,
+ int? channels = null,
+ int? bitDepth = null,
+ PlaybackStreamingQuality? quality = null,
+ long? sourceLength = null,
+ DateTime? sourceLastModifiedUtc = null,
+ bool includeSourceContainer = true,
+ bool includeBitrate = true,
+ bool includeBitDepth = true)
+ {
+ IReadOnlyList resolvedAllowedRoots = allowedRoots ?? [Path.Combine(Path.GetTempPath(), "lumina-tests", _faker.Random.AlphaNumeric(12))];
+ string resolvedSourcePath = sourcePath ?? (resolvedAllowedRoots.Count > 0
+ ? Path.Combine(resolvedAllowedRoots[0], "track-" + _faker.Random.AlphaNumeric(8) + ".flac")
+ : Path.Combine(Path.GetTempPath(), "track-" + _faker.Random.AlphaNumeric(8) + ".flac"));
+
+ return new NormalizedTrackRequestDto(
+ trackId ?? _faker.Random.Guid(),
+ userId ?? _faker.Random.Guid(),
+ resolvedSourcePath,
+ resolvedAllowedRoots,
+ includeSourceContainer ? (sourceContainer ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "WAV")) : null,
+ mode ?? _faker.PickRandom(PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode),
+ container ?? _faker.PickRandom("MP3", "AAC", "FLAC", "WAV", "OGG"),
+ codec ?? _faker.PickRandom("MP3", "AAC", "FLAC", "PCM", "OPUS"),
+ segmentDurationSeconds ?? _faker.Random.Int(1, 30),
+ durationInSeconds ?? _faker.Random.Int(1, 3600),
+ includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null,
+ sampleRate ?? _faker.PickRandom(44100, 48000, 96000),
+ channels ?? _faker.PickRandom(1, 2, 6),
+ includeBitDepth ? (bitDepth ?? _faker.Random.Int(16, 24)) : null,
+ quality ?? _faker.PickRandom(),
+ sourceLength ?? _faker.Random.Long(1, 100_000_000),
+ sourceLastModifiedUtc ?? _faker.Date.Past().ToUniversalTime());
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDtoFixture.cs
new file mode 100644
index 00000000..4559bb45
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDtoFixture.cs
@@ -0,0 +1,56 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class NormalizedTrackSegmentDataDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The read stream over the segment. When it is not supplied, a fresh empty is created.
+ /// Optional. The length of the segment, in bytes.
+ /// Optional. The exact start of the segment on the track timeline, in seconds.
+ /// Optional. The container of the delivered audio.
+ /// Optional. The number of segments the production holds.
+ /// Optional. The duration of the produced normalized audio, in seconds.
+ /// The created .
+ public NormalizedTrackSegmentDataDto Create(
+ Stream? content = null,
+ long? length = null,
+ decimal? startSeconds = null,
+ string? container = null,
+ int? segmentCount = null,
+ int? durationInSeconds = null)
+ {
+ return new NormalizedTrackSegmentDataDto(
+ content ?? new MemoryStream(),
+ length ?? _faker.Random.Long(1, 10_000_000),
+ startSeconds ?? _faker.Random.Decimal(0, 3600),
+ container ?? _faker.PickRandom("MP3", "AAC", "FLAC", "WAV", "OGG"),
+ segmentCount ?? _faker.Random.Int(1, 1000),
+ durationInSeconds ?? _faker.Random.Int(1, 3600));
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDtoFixture.cs
new file mode 100644
index 00000000..f37659e2
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDtoFixture.cs
@@ -0,0 +1,49 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class NormalizedTrackSegmentDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The zero based position of the segment in the delivered audio.
+ /// Optional. The time, in seconds from the start of the track, at which the segment starts.
+ /// Optional. The duration of the segment, in seconds.
+ /// Optional. The length of the segment, in bytes.
+ /// The created .
+ public NormalizedTrackSegmentDto Create(
+ int? index = null,
+ decimal? startSeconds = null,
+ decimal? durationSeconds = null,
+ long? length = null)
+ {
+ return new NormalizedTrackSegmentDto(
+ index ?? _faker.Random.Int(0, 1000),
+ startSeconds ?? _faker.Random.Decimal(0, 3600),
+ durationSeconds ?? _faker.Random.Decimal(1, 30),
+ length ?? _faker.Random.Long(1, 10_000_000));
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDtoFixture.cs
new file mode 100644
index 00000000..29a626fe
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDtoFixture.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackDeliveryDecisionDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The way the audio is delivered.
+ /// Optional. The container of the delivered audio.
+ /// Optional. The codec of the delivered audio.
+ /// Optional. The shape the delivered audio is addressed and seeked by.
+ /// Optional. The duration of each segment of the delivered audio, in seconds.
+ /// The created .
+ public PlaybackDeliveryDecisionDto Create(
+ PlaybackDeliveryMode? mode = null,
+ string? container = null,
+ string? codec = null,
+ PlaybackDeliveryShape? shape = null,
+ int? segmentDurationSeconds = null)
+ {
+ PlaybackDeliveryShape resolvedShape = shape ?? _faker.PickRandom();
+ return new PlaybackDeliveryDecisionDto(
+ mode ?? _faker.PickRandom(PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode),
+ container ?? _faker.PickRandom("MP3", "AAC", "FLAC", "WAV", "OGG"),
+ codec ?? _faker.PickRandom("MP3", "AAC", "FLAC", "PCM", "OPUS"),
+ resolvedShape,
+ segmentDurationSeconds ?? (resolvedShape == PlaybackDeliveryShape.TimeAddressedSegments ? _faker.Random.Int(1, 30) : 0));
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDtoFixture.cs
new file mode 100644
index 00000000..fb64b30e
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDtoFixture.cs
@@ -0,0 +1,55 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackDeliveryHandleDtoFixture
+{
+ private readonly Faker _faker = new();
+ private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The complete normalization request the delivery declares.
+ /// Optional. The shape the delivered audio is addressed by.
+ /// Optional. The Id of the library the track belongs to.
+ /// Optional. The Id of the album the track belongs to.
+ /// Optional. The Id of the artist that owns the album.
+ /// The created .
+ public PlaybackDeliveryHandleDto Create(
+ NormalizedTrackRequestDto? request = null,
+ PlaybackDeliveryShape? shape = null,
+ Guid? libraryId = null,
+ Guid? albumId = null,
+ Guid? artistId = null)
+ {
+ return new PlaybackDeliveryHandleDto(
+ request ?? _normalizedTrackRequestDtoFixture.Create(),
+ shape ?? _faker.PickRandom(),
+ libraryId ?? _faker.Random.Guid(),
+ albumId ?? _faker.Random.Guid(),
+ artistId ?? _faker.Random.Guid());
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDtoFixture.cs
new file mode 100644
index 00000000..2f40993d
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDtoFixture.cs
@@ -0,0 +1,84 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class TrackPlaybackManifestDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The file system path of the stored audio file of the track.
+ /// Optional. The container of the audio file of the track.
+ /// Optional. The audio codec used by the audio file of the track.
+ /// Optional. The duration of the audio of the track, in seconds.
+ /// Optional. The sample rate of the audio of the track, in Hz.
+ /// Optional. The number of audio channels of the track.
+ /// Optional. The bit depth of the audio of the track.
+ /// Optional. The bitrate of the audio of the track, in kbps.
+ /// Optional. The ReplayGain track gain of the track, in decibels.
+ /// Optional. The ReplayGain track peak of the track.
+ /// Optional. The ReplayGain album gain of the track, in decibels.
+ /// Optional. The ReplayGain album peak of the track.
+ /// Whether the container should be included, or forced to .
+ /// Whether the audio codec should be included, or forced to .
+ /// Whether the bit depth should be included, or forced to .
+ /// Whether the bitrate should be included, or forced to .
+ /// Whether the ReplayGain values should be included, or forced to .
+ /// The created .
+ public TrackPlaybackManifestDto Create(
+ string? path = null,
+ string? container = null,
+ string? audioCodec = null,
+ int? durationInSeconds = null,
+ int? sampleRate = null,
+ int? channels = null,
+ int? bitDepth = null,
+ int? bitrate = null,
+ decimal? replayGainTrackGain = null,
+ decimal? replayGainTrackPeak = null,
+ decimal? replayGainAlbumGain = null,
+ decimal? replayGainAlbumPeak = null,
+ bool includeContainer = true,
+ bool includeAudioCodec = true,
+ bool includeBitDepth = true,
+ bool includeBitrate = true,
+ bool includeReplayGain = true)
+ {
+ return new TrackPlaybackManifestDto(
+ path ?? Path.Combine(_faker.System.DirectoryPath(), _faker.System.FileName("flac")),
+ includeContainer ? (container ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV")) : null,
+ includeAudioCodec ? (audioCodec ?? _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC", "PCM")) : null,
+ durationInSeconds ?? _faker.Random.Int(1, 3600),
+ sampleRate ?? _faker.PickRandom(44100, 48000, 96000),
+ channels ?? _faker.PickRandom(1, 2, 6),
+ includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
+ includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null,
+ includeReplayGain ? (replayGainTrackGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
+ includeReplayGain ? (replayGainTrackPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
+ includeReplayGain ? (replayGainAlbumGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
+ includeReplayGain ? (replayGainAlbumPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryFixture.cs
new file mode 100644
index 00000000..3d8ecd36
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryFixture.cs
@@ -0,0 +1,69 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetPlaybackManifestQueryFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid query to get the playback manifest of a track.
+ ///
+ /// Optional. The Id of the media library the track belongs to.
+ /// Optional. The Id of the artist the album of the track belongs to.
+ /// Optional. The Id of the album the track belongs to.
+ /// Optional. The Id of the track whose playback manifest is retrieved.
+ /// Optional. The container and codec pairs the player advertises it can demux and decode directly.
+ /// Optional. The path of the track stream, relative to the API.
+ /// Optional. The path template of the segment route, relative to the API.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the track Id should be included, or forced to .
+ /// Whether the capabilities should be included, or forced to .
+ /// The created .
+ public GetPlaybackManifestQuery Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? albumId = null,
+ string? trackId = null,
+ string? capabilities = null,
+ string? streamPath = null,
+ string? segmentStreamPathTemplate = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includeTrackId = true,
+ bool includeCapabilities = true)
+ {
+ return new GetPlaybackManifestQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
+ includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null,
+ includeCapabilities ? (capabilities ?? "mp3/mp3,flac/flac") : null,
+ streamPath ?? "/api/v1/music/libraries/" + _faker.Random.AlphaNumeric(8) + "/tracks/" + _faker.Random.AlphaNumeric(8) + "/stream",
+ segmentStreamPathTemplate ?? "/api/v1/music/libraries/" + _faker.Random.AlphaNumeric(8) + "/tracks/" + _faker.Random.AlphaNumeric(8) + "/stream/segments/{deliveryId}/{segmentIndex}");
+ }
+
+ ///
+ /// Creates a list of instances.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryFixture.cs
new file mode 100644
index 00000000..51d432a7
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryFixture.cs
@@ -0,0 +1,68 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetTrackSegmentQueryFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid query to get a single segment of the normalized audio of a track.
+ ///
+ /// Optional. The Id of the media library the track belongs to.
+ /// Optional. The Id of the artist the album of the track belongs to.
+ /// Optional. The Id of the album the track belongs to.
+ /// Optional. The Id of the track whose normalized audio is streamed.
+ /// Optional. The opaque handle of the normalized delivery the segment belongs to.
+ /// Optional. The zero based index of the segment of the normalized audio.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the track Id should be included, or forced to .
+ /// Whether the delivery Id should be included, or forced to .
+ /// Whether the segment index should be included, or forced to .
+ /// The created .
+ public GetTrackSegmentQuery Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? albumId = null,
+ string? trackId = null,
+ string? deliveryId = null,
+ string? segmentIndex = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includeTrackId = true,
+ bool includeDeliveryId = true,
+ bool includeSegmentIndex = true)
+ {
+ return new GetTrackSegmentQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
+ includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null,
+ includeDeliveryId ? (deliveryId ?? Guid.NewGuid().ToString("N")) : null,
+ includeSegmentIndex ? (segmentIndex ?? _faker.Random.Int(0, 1000).ToString()) : null);
+ }
+
+ ///
+ /// Creates a list of instances.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponseFixture.cs
new file mode 100644
index 00000000..4a632228
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponseFixture.cs
@@ -0,0 +1,119 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+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;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackManifestResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the track the manifest describes.
+ /// Optional. The duration of the audio of the track, in seconds.
+ /// Optional. The container of the stored audio file of the track.
+ /// Optional. The codec of the stored audio of the track.
+ /// Optional. The sample rate of the stored audio, in Hz.
+ /// Optional. The number of audio channels of the track.
+ /// Optional. The bit depth of the stored audio of the track.
+ /// Optional. The ReplayGain track gain of the track, in decibels.
+ /// Optional. The ReplayGain track peak of the track.
+ /// Optional. The ReplayGain album gain of the track, in decibels.
+ /// Optional. The ReplayGain album peak of the track.
+ /// Whether the stored audio is delivered as it is.
+ /// Optional. The container of the delivered audio.
+ /// Optional. The codec of the delivered audio.
+ /// Optional. The shape the delivered audio is addressed by.
+ /// Optional. The duration of each segment of the delivered audio, in seconds.
+ /// Whether the delivered audio can be seeked by the player.
+ /// Optional. The relative path of the track stream.
+ /// Optional. The opaque handle of the normalized delivery.
+ /// Optional. The relative path template of the segment route.
+ /// Whether the bit depth should be included, or forced to .
+ /// Whether the ReplayGain values should be included, or forced to .
+ /// Whether the delivery container should be included, or forced to .
+ /// Whether the delivery codec should be included, or forced to .
+ /// Whether the delivery shape should be included, or forced to .
+ /// Whether the segment duration should be included, or forced to .
+ /// Whether the delivery handle should be included, or forced to .
+ /// Whether the segment path template should be included, or forced to .
+ /// The created .
+ public PlaybackManifestResponse Create(
+ Guid? trackId = null,
+ int? durationInSeconds = null,
+ string? sourceContainer = null,
+ string? sourceCodec = null,
+ int? sampleRate = null,
+ int? channels = null,
+ int? bitDepth = null,
+ decimal? replayGainTrackGain = null,
+ decimal? replayGainTrackPeak = null,
+ decimal? replayGainAlbumGain = null,
+ decimal? replayGainAlbumPeak = null,
+ bool isDirectPlay = false,
+ string? deliveryContainer = null,
+ string? deliveryCodec = null,
+ PlaybackDeliveryShape? deliveryShape = null,
+ int? segmentDurationSeconds = null,
+ bool isSeekable = true,
+ string? streamPath = null,
+ string? deliveryId = null,
+ string? segmentStreamPathTemplate = null,
+ bool includeBitDepth = true,
+ bool includeReplayGain = true,
+ bool includeDeliveryContainer = true,
+ bool includeDeliveryCodec = true,
+ bool includeDeliveryShape = true,
+ bool includeSegmentDurationSeconds = true,
+ bool includeDeliveryId = true,
+ bool includeSegmentStreamPathTemplate = true)
+ {
+ Guid resolvedTrackId = trackId ?? _faker.Random.Guid();
+ string resolvedDeliveryId = deliveryId ?? Guid.NewGuid().ToString("N");
+ return new PlaybackManifestResponse(
+ resolvedTrackId,
+ durationInSeconds ?? _faker.Random.Int(1, 3600),
+ sourceContainer ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV"),
+ sourceCodec ?? _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC", "OPUS", "PCM"),
+ sampleRate ?? _faker.PickRandom(44100, 48000, 96000),
+ channels ?? _faker.PickRandom(1, 2, 6),
+ includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
+ includeReplayGain ? (replayGainTrackGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
+ includeReplayGain ? (replayGainTrackPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
+ includeReplayGain ? (replayGainAlbumGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
+ includeReplayGain ? (replayGainAlbumPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
+ isDirectPlay,
+ includeDeliveryContainer ? (deliveryContainer ?? "MP3") : null,
+ includeDeliveryCodec ? (deliveryCodec ?? "MP3") : null,
+ includeDeliveryShape ? (deliveryShape ?? PlaybackDeliveryShape.TimeAddressedSegments) : null,
+ includeSegmentDurationSeconds ? (segmentDurationSeconds ?? 6) : null,
+ isSeekable,
+ streamPath ?? $"/libraries/{Guid.NewGuid():N}/artists/{Guid.NewGuid():N}/albums/{Guid.NewGuid():N}/tracks/{resolvedTrackId:N}/stream",
+ includeDeliveryId ? resolvedDeliveryId : null,
+ includeSegmentStreamPathTemplate
+ ? (segmentStreamPathTemplate ?? $"/libraries/{Guid.NewGuid():N}/artists/{Guid.NewGuid():N}/albums/{Guid.NewGuid():N}/tracks/{resolvedTrackId:N}/stream/deliveries/{{deliveryId}}/segments/{{segmentIndex}}")
+ : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/TranscodingSettingsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/TranscodingSettingsDtoFixture.cs
index c8a4087a..e902381f 100644
--- a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/TranscodingSettingsDtoFixture.cs
+++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/TranscodingSettingsDtoFixture.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
+using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -31,6 +32,7 @@ public class TranscodingSettingsDtoFixture
/// default temporary directory.
///
/// Whether to generate the optional cache directory, defaulting to .
+ /// Whether the ffmpeg path should be included, or forced to , defaulting to .
/// A configured instance.
public TranscodingSettingsDto Create(
string? ffmpegPath = null,
@@ -40,16 +42,19 @@ public class TranscodingSettingsDtoFixture
int? jobTimeoutSeconds = null,
int? evictionGraceSeconds = null,
string? cacheDirectory = null,
- bool includeCacheDirectory = true)
+ bool includeCacheDirectory = true,
+ bool includeFfmpegPath = true)
{
+ int resolvedMaxConcurrentJobs = maxConcurrentJobs ?? _faker.Random.Int(1, 16);
return new TranscodingSettingsDto
{
- FfmpegPath = ffmpegPath ?? _faker.System.FileName("exe"),
- MaxConcurrentJobs = maxConcurrentJobs ?? _faker.Random.Int(1, 16),
- MaxConcurrentJobsPerUser = maxConcurrentJobsPerUser ?? _faker.Random.Int(1, 8),
+ FfmpegPath = includeFfmpegPath ? (ffmpegPath ?? _faker.System.FileName("exe")) : null!,
+ MaxConcurrentJobs = resolvedMaxConcurrentJobs,
+ // A per-user limit above the global one is rejected by the validator, so the generated value never exceeds the global limit.
+ MaxConcurrentJobsPerUser = maxConcurrentJobsPerUser ?? _faker.Random.Int(1, Math.Max(1, resolvedMaxConcurrentJobs)),
MaxCacheBytes = maxCacheBytes ?? _faker.Random.Long(1_000_000_000, 8_589_934_592),
JobTimeoutSeconds = jobTimeoutSeconds ?? _faker.Random.Int(60, 3600),
- EvictionGraceSeconds = evictionGraceSeconds ?? _faker.Random.Int(0, 600),
+ EvictionGraceSeconds = evictionGraceSeconds ?? _faker.Random.Int(1, 600),
CacheDirectory = includeCacheDirectory ? cacheDirectory ?? _faker.System.DirectoryPath() : null
};
}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubStreamRequest.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubStreamRequest.cs
new file mode 100644
index 00000000..03df3e14
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubStreamRequest.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Api;
+
+///
+/// A streamed request that was sent to the stub.
+///
+/// The endpoint the stream was requested from.
+/// The request headers that were forwarded with the request.
+[ExcludeFromCodeCoverage]
+public record StubStreamRequest(string Endpoint, IReadOnlyDictionary Headers);
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubStreamingApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubStreamingApiHttpClient.cs
new file mode 100644
index 00000000..d79236ff
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubStreamingApiHttpClient.cs
@@ -0,0 +1,90 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Api;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Api;
+
+///
+/// Test double for the interface, allowing integration and security tests to stub the
+/// streamed responses of the remote API without hosting a real backend.
+///
+[ExcludeFromCodeCoverage]
+public class StubStreamingApiHttpClient : IStreamingApiHttpClient
+{
+ private readonly Dictionary> _streamResponseFactories = [];
+ private readonly Dictionary> _streamExceptionFactories = [];
+
+ ///
+ /// Gets the streamed requests that were sent, with the headers that were forwarded with them.
+ ///
+ public List StreamRequests { get; } = [];
+
+ ///
+ /// Gets the list of endpoints the streams were requested from.
+ ///
+ public List GetEndpointsCalled { get; } = [];
+
+ ///
+ /// Registers the streamed response returned when the specified endpoint is called.
+ ///
+ /// The API endpoint for which to register the response.
+ /// The streamed response to return.
+ public void RegisterStreamResponse(string endpoint, ApiStreamResult response)
+ {
+ _streamResponseFactories[endpoint] = () => response;
+ }
+
+ ///
+ /// Registers the response factory invoked when the specified endpoint is called.
+ ///
+ /// The API endpoint for which to register the response factory.
+ /// The factory that produces the streamed response.
+ public void RegisterStreamResponseFactory(string endpoint, Func responseFactory)
+ {
+ _streamResponseFactories[endpoint] = responseFactory;
+ }
+
+ ///
+ /// Registers the exception thrown when the specified endpoint is called.
+ ///
+ /// The API endpoint for which to register the exception.
+ /// The exception to throw.
+ public void RegisterStreamException(string endpoint, Exception exception)
+ {
+ _streamExceptionFactories[endpoint] = () => exception;
+ }
+
+ ///
+ /// Resets all registered responses and captured requests.
+ ///
+ public void Reset()
+ {
+ _streamResponseFactories.Clear();
+ _streamExceptionFactories.Clear();
+ StreamRequests.Clear();
+ GetEndpointsCalled.Clear();
+ }
+
+ ///
+ /// Sends a GET request to the specified as an asynchronous operation and returns the response as a stream.
+ ///
+ /// The API endpoint where the request is being sent.
+ /// The range and conditional headers of the incoming request to forward.
+ /// Cancellation token that can be used to stop the execution.
+ /// The streamed response of the API request.
+ public Task GetStreamAsync(string endpoint, IReadOnlyDictionary requestHeaders, CancellationToken cancellationToken = default)
+ {
+ GetEndpointsCalled.Add(endpoint);
+ StreamRequests.Add(new StubStreamRequest(endpoint, new Dictionary(requestHeaders)));
+ if (_streamExceptionFactories.TryGetValue(endpoint, out Func? exceptionFactory))
+ throw exceptionFactory();
+ if (_streamResponseFactories.TryGetValue(endpoint, out Func? responseFactory))
+ return Task.FromResult(responseFactory());
+ throw new InvalidOperationException($"No stream response is registered for the endpoint '{endpoint}'.");
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDtoFixture.cs
new file mode 100644
index 00000000..18b287af
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDtoFixture.cs
@@ -0,0 +1,120 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
+using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackManifestDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The Id of the track the manifest describes.
+ /// Optional. The duration of the audio of the track, in seconds.
+ /// Optional. The container of the stored audio file of the track.
+ /// Optional. The codec of the stored audio of the track.
+ /// Optional. The sample rate of the stored audio, in Hz.
+ /// Optional. The number of audio channels of the track.
+ /// Optional. The bit depth of the stored audio of the track.
+ /// Optional. The ReplayGain track gain of the track, in decibels.
+ /// Optional. The ReplayGain track peak of the track.
+ /// Optional. The ReplayGain album gain of the track, in decibels.
+ /// Optional. The ReplayGain album peak of the track.
+ /// Whether the stored audio is delivered as it is.
+ /// Optional. The container of the delivered audio.
+ /// Optional. The codec of the delivered audio.
+ /// Optional. The shape the delivered audio is addressed by.
+ /// Optional. The duration of each segment of the delivered audio, in seconds.
+ /// Whether the delivered audio can be seeked by the player.
+ /// Optional. The relative path of the track stream.
+ /// Optional. The opaque handle of the normalized delivery.
+ /// Optional. The relative path template of the segment route.
+ /// Whether the bit depth should be included, or forced to .
+ /// Whether the ReplayGain values should be included, or forced to .
+ /// Whether the delivery container should be included, or forced to .
+ /// Whether the delivery codec should be included, or forced to .
+ /// Whether the delivery shape should be included, or forced to .
+ /// Whether the segment duration should be included, or forced to .
+ /// Whether the delivery handle should be included, or forced to .
+ /// Whether the segment path template should be included, or forced to .
+ /// A configured instance.
+ public PlaybackManifestDto Create(
+ Guid? trackId = null,
+ int? durationInSeconds = null,
+ string? sourceContainer = null,
+ string? sourceCodec = null,
+ int? sampleRate = null,
+ int? channels = null,
+ int? bitDepth = null,
+ decimal? replayGainTrackGain = null,
+ decimal? replayGainTrackPeak = null,
+ decimal? replayGainAlbumGain = null,
+ decimal? replayGainAlbumPeak = null,
+ bool isDirectPlay = false,
+ string? deliveryContainer = null,
+ string? deliveryCodec = null,
+ PlaybackDeliveryShape? deliveryShape = null,
+ int? segmentDurationSeconds = null,
+ bool isSeekable = true,
+ string? streamPath = null,
+ string? deliveryId = null,
+ string? segmentStreamPathTemplate = null,
+ bool includeBitDepth = true,
+ bool includeReplayGain = true,
+ bool includeDeliveryContainer = true,
+ bool includeDeliveryCodec = true,
+ bool includeDeliveryShape = true,
+ bool includeSegmentDurationSeconds = true,
+ bool includeDeliveryId = true,
+ bool includeSegmentStreamPathTemplate = true)
+ {
+ Guid resolvedTrackId = trackId ?? _faker.Random.Guid();
+ return new PlaybackManifestDto
+ {
+ TrackId = resolvedTrackId,
+ DurationInSeconds = durationInSeconds ?? _faker.Random.Int(1, 3600),
+ SourceContainer = sourceContainer ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV"),
+ SourceCodec = sourceCodec ?? _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC", "OPUS", "PCM"),
+ SampleRate = sampleRate ?? _faker.PickRandom(44100, 48000, 96000),
+ Channels = channels ?? _faker.PickRandom(1, 2, 6),
+ BitDepth = includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
+ ReplayGainTrackGain = includeReplayGain ? (replayGainTrackGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
+ ReplayGainTrackPeak = includeReplayGain ? (replayGainTrackPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
+ ReplayGainAlbumGain = includeReplayGain ? (replayGainAlbumGain ?? _faker.Random.Decimal(-20m, 0m)) : null,
+ ReplayGainAlbumPeak = includeReplayGain ? (replayGainAlbumPeak ?? _faker.Random.Decimal(0m, 1.5m)) : null,
+ IsDirectPlay = isDirectPlay,
+ DeliveryContainer = includeDeliveryContainer ? (deliveryContainer ?? "MP3") : null,
+ DeliveryCodec = includeDeliveryCodec ? (deliveryCodec ?? "MP3") : null,
+ DeliveryShape = includeDeliveryShape ? (deliveryShape ?? PlaybackDeliveryShape.TimeAddressedSegments) : null,
+ SegmentDurationSeconds = includeSegmentDurationSeconds ? (segmentDurationSeconds ?? 6) : null,
+ IsSeekable = isSeekable,
+ StreamPath = streamPath ?? $"/libraries/{Guid.NewGuid():N}/artists/{Guid.NewGuid():N}/albums/{Guid.NewGuid():N}/tracks/{resolvedTrackId:N}/stream",
+ DeliveryId = includeDeliveryId ? (deliveryId ?? Guid.NewGuid().ToString("N")) : null,
+ SegmentStreamPathTemplate = includeSegmentStreamPathTemplate
+ ? (segmentStreamPathTemplate ?? $"/libraries/{Guid.NewGuid():N}/artists/{Guid.NewGuid():N}/albums/{Guid.NewGuid():N}/tracks/{resolvedTrackId:N}/stream/deliveries/{{deliveryId}}/segments/{{segmentIndex}}")
+ : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequestFixture.cs
new file mode 100644
index 00000000..2598ec76
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifestRequestFixture.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetPlaybackManifestRequestFixture
+{
+ ///
+ /// Creates a new instance.
+ ///
+ /// Optional unique identifier of the artist the album belongs to.
+ /// Optional unique identifier of the album the track belongs to.
+ /// Optional unique identifier of the track whose manifest is requested.
+ /// Optional unique identifier of the media library the track belongs to.
+ /// Optional capabilities the player advertises it can play directly.
+ /// Whether the capabilities should be included, or forced to .
+ /// A configured instance.
+ public GetPlaybackManifestRequest Create(
+ string? artistId = null,
+ string? albumId = null,
+ string? trackId = null,
+ Guid? libraryId = null,
+ string? capabilities = null,
+ bool includeCapabilities = true)
+ {
+ return new GetPlaybackManifestRequest(
+ artistId ?? Guid.NewGuid().ToString(),
+ albumId ?? Guid.NewGuid().ToString(),
+ trackId ?? Guid.NewGuid().ToString(),
+ libraryId ?? Guid.NewGuid(),
+ includeCapabilities ? (capabilities ?? "mp3/mp3") : null);
+ }
+
+ ///
+ /// Creates a list of instances.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequestFixture.cs
new file mode 100644
index 00000000..9146e8e7
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackRequestFixture.cs
@@ -0,0 +1,53 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class StreamMusicTrackRequestFixture
+{
+ ///
+ /// Creates a new instance.
+ ///
+ /// Optional unique identifier of the artist the album belongs to.
+ /// Optional unique identifier of the album the track belongs to.
+ /// Optional unique identifier of the track to stream.
+ /// Optional unique identifier of the media library the track belongs to.
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the track Id should be included, or forced to .
+ /// A configured instance.
+ public StreamMusicTrackRequest Create(
+ string? artistId = null,
+ string? albumId = null,
+ string? trackId = null,
+ Guid? libraryId = null,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includeTrackId = true)
+ {
+ return new StreamMusicTrackRequest(
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null!,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null!,
+ includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null!,
+ libraryId ?? Guid.NewGuid());
+ }
+
+ ///
+ /// Creates a list of instances.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequestFixture.cs
new file mode 100644
index 00000000..75309521
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequestFixture.cs
@@ -0,0 +1,55 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class StreamMusicTrackSegmentRequestFixture
+{
+ ///
+ /// Creates a new instance.
+ ///
+ /// Optional unique identifier of the artist the album belongs to.
+ /// Optional unique identifier of the album the track belongs to.
+ /// Optional unique identifier of the track to stream.
+ /// Optional opaque handle of the normalized delivery.
+ /// Optional zero based index of the segment.
+ /// Optional unique identifier of the media library the track belongs to.
+ /// Whether the delivery handle should be included, or forced to .
+ /// A configured instance.
+ public StreamMusicTrackSegmentRequest Create(
+ string? artistId = null,
+ string? albumId = null,
+ string? trackId = null,
+ string? deliveryId = null,
+ int? segmentIndex = null,
+ Guid? libraryId = null,
+ bool includeDeliveryId = true)
+ {
+ return new StreamMusicTrackSegmentRequest(
+ artistId ?? Guid.NewGuid().ToString(),
+ albumId ?? Guid.NewGuid().ToString(),
+ trackId ?? Guid.NewGuid().ToString(),
+ includeDeliveryId ? (deliveryId ?? Guid.NewGuid().ToString("N")) : null!,
+ segmentIndex ?? Random.Shared.Next(0, 100),
+ libraryId ?? Guid.NewGuid());
+ }
+
+ ///
+ /// Creates a list of instances.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs
index 6db9f0b4..ced16084 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs
@@ -7,6 +7,7 @@ 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.Common.Routes.Library.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
@@ -96,6 +97,8 @@ public class GetPlaybackManifestEndpointTests : IClassFixture(content, _jsonOptions);
+
+ // Assert
+ Assert.NotNull(deliveryIdFromFirstRead);
+ Assert.Matches("^[0-9a-f]{32}$", deliveryIdFromFirstRead);
+ Assert.NotNull(secondRead);
+ Assert.Equal(deliveryIdFromFirstRead, secondRead!.DeliveryId);
+ Assert.Matches("^[0-9a-f]{32}$", secondRead.DeliveryId);
}
[Fact]
@@ -230,6 +286,23 @@ public class GetPlaybackManifestEndpointTests : IClassFixture
+ /// Builds the segment stream path template the manifest is expected to report for a track.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The expected segment stream path template, with its placeholders preserved.
+ private static string BuildExpectedSegmentStreamPathTemplate(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
+ {
+ return ApiRoutes.Tracks.STREAM_TRACK_SEGMENT
+ .Replace("{libraryId}", libraryId.ToString())
+ .Replace("{artistId}", artistId.ToString())
+ .Replace("{albumId}", albumId.ToString())
+ .Replace("{trackId}", trackId.ToString());
+ }
+
///
/// Reads the playback manifest of a response.
///
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs
new file mode 100644
index 00000000..5e1d9933
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs
@@ -0,0 +1,368 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+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.GetTrackSegment;
+
+///
+/// Contains integration tests for the class.
+///
+///
+/// The successful production path of a segment is not exercised here, because it requires ffmpeg, which is not part of the test environment. Every
+/// covered case is rejected before the normalization pipeline is entered, so these tests are deterministic and environment independent.
+///
+[ExcludeFromCodeCoverage]
+public class GetTrackSegmentEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-tests-{Guid.NewGuid():N}");
+ private readonly List _temporaryFiles = [];
+ private readonly List _seededLibraryIds = [];
+ private readonly List _seededArtistIds = [];
+ private readonly List _seededAlbumIds = [];
+ private readonly List _seededTrackIds = [];
+ 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();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetTrackSegmentEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes the authenticated API client and the temporary content root of the test.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ Directory.CreateDirectory(_contentRootPath);
+ }
+
+ [Fact]
+ public async Task GetTrackSegment_WhenUnauthorized_ShouldReturnUnauthorizedResultWithoutLeakingTheDeliveryHandle()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string trackPath = WriteContentFile("bohemian-rhapsody.ogg", CreateAudioBytes());
+ (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
+ string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ // The request path is echoed by the problem details, so the handle the caller sent appears there; no other handle may be disclosed.
+ string[] disclosedHandleCandidates = [.. System.Text.RegularExpressions.Regex.Matches(content, "[0-9a-f]{32}").Select(match => match.Value)];
+ Assert.All(disclosedHandleCandidates, candidate => Assert.Equal(deliveryId, candidate));
+ }
+
+ [Theory]
+ [InlineData("uppercase")] // the handle format only accepts lowercase hexadecimal characters
+ [InlineData("dashed")] // the handle format is the N format of a GUID, without dashes
+ public async Task GetTrackSegment_WhenDeliveryIdFormatIsInvalid_ShouldReturnValidationProblem(string malformedHandleKind)
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string trackPath = WriteContentFile("love-of-my-life.ogg", CreateAudioBytes());
+ (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
+ string validDeliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
+ string malformedDeliveryId = malformedHandleKind switch
+ {
+ "uppercase" => validDeliveryId.ToUpperInvariant(),
+ _ => Guid.Parse(validDeliveryId).ToString("D"),
+ };
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, malformedDeliveryId, 0));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.RootElement.GetProperty("detail").GetString());
+ Assert.Contains(
+ "DeliveryIdIsInvalid",
+ problemDetails.RootElement.GetProperty("errors").GetProperty("General.Validation").EnumerateArray().Select(error => error.GetString()));
+ }
+
+ [Fact]
+ public async Task GetTrackSegment_WhenDeliveryIdIsUnknown_ShouldReturnPlaybackDeliveryNotFound()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string trackPath = WriteContentFile("you-re-my-best-friend.ogg", CreateAudioBytes());
+ (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
+ string unknownDeliveryId = Guid.NewGuid().ToString("N");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, unknownDeliveryId, 0));
+
+ // 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("PlaybackDeliveryNotFound", problemDetails.Detail);
+ }
+
+ [Theory]
+ [InlineData("library")] // the handle was issued for the library of another delivery
+ [InlineData("artist")] // the handle was issued for the artist of another delivery
+ [InlineData("album")] // the handle was issued for the album of another delivery
+ public async Task GetTrackSegment_WhenDeliveryWasIssuedForAnotherScope_ShouldReturnPlaybackDeliveryNotFound(string mismatchedScope)
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string trackPath = WriteContentFile("news-of-the-world.ogg", CreateAudioBytes());
+ (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
+ string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
+ // A second library owned by the same user keeps the ownership check passing, so the delivery scope is what rejects the request.
+ Guid otherLibraryId = await SeedLibraryAsync(userId);
+ Guid requestedLibraryId = mismatchedScope == "library" ? otherLibraryId : libraryId;
+ Guid requestedArtistId = mismatchedScope == "artist" ? Guid.NewGuid() : artistId;
+ Guid requestedAlbumId = mismatchedScope == "album" ? Guid.NewGuid() : albumId;
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(requestedLibraryId, requestedArtistId, requestedAlbumId, trackId, deliveryId, 0));
+
+ // 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("PlaybackDeliveryNotFound", problemDetails.Detail);
+ }
+
+ [Fact]
+ public async Task GetTrackSegment_WhenTrackFileIsOutsideTheLibraryContentLocations_ShouldReturnTrackFileNotFoundWithoutLeakingThePath()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string outsideFilePath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-outside-{Guid.NewGuid():N}.ogg");
+ await File.WriteAllBytesAsync(outsideFilePath, CreateAudioBytes());
+ _temporaryFiles.Add(outsideFilePath);
+ (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, outsideFilePath);
+ string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain(outsideFilePath, content, StringComparison.OrdinalIgnoreCase);
+ Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal("General.NotFound", problemDetails!.Title);
+ Assert.Equal("TrackFileNotFound", problemDetails.Detail);
+ }
+
+ ///
+ /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album.
+ ///
+ /// The Id of the user that owns the library.
+ /// The file system path of the audio file of the track.
+ /// The Ids of the seeded library, artist, album and track.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ 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, contentLocations: [_contentRootPath]));
+ 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,
+ path: trackPath,
+ container: "OGG",
+ audioCodec: "OPUS",
+ title: "A Track",
+ includeMetadata: false));
+ await dbContext.SaveChangesAsync();
+ _seededLibraryIds.Add(libraryId);
+ _seededArtistIds.Add(artistId);
+ _seededAlbumIds.Add(albumId);
+ _seededTrackIds.Add(trackId);
+ return (libraryId, artistId, albumId, trackId);
+ }
+
+ ///
+ /// Seeds an additional music library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
+ await dbContext.SaveChangesAsync();
+ _seededLibraryIds.Add(libraryId);
+ return libraryId;
+ }
+
+ ///
+ /// Requests a transcoded playback manifest for the seeded track and returns the delivery handle it reports.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The delivery handle of the normalized delivery.
+ private async Task GetDeliveryIdAsync(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
+ {
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ PlaybackManifestResponse? manifest = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(manifest);
+ Assert.NotNull(manifest!.DeliveryId);
+ return manifest.DeliveryId;
+ }
+
+ ///
+ /// Builds the route of a single segment of the normalized audio of a track.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The opaque handle of the normalized delivery.
+ /// The zero based index of the segment.
+ /// The route of the requested segment.
+ private static string BuildSegmentPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
+ {
+ return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}";
+ }
+
+ ///
+ /// Writes an audio file with the provided inside the content root of the test, and returns its full path.
+ ///
+ /// The name of the audio file to write.
+ /// The bytes of the audio file to write.
+ /// The full path of the written audio file.
+ private string WriteContentFile(string fileName, byte[] audioBytes)
+ {
+ string filePath = Path.Combine(_contentRootPath, fileName);
+ File.WriteAllBytes(filePath, audioBytes);
+ return filePath;
+ }
+
+ ///
+ /// Creates a deterministic byte array that stands in for the content of an audio file.
+ ///
+ /// The created bytes.
+ private static byte[] CreateAudioBytes()
+ {
+ return [.. Enumerable.Range(0, 4096).Select(index => (byte)(index % 256))];
+ }
+
+ ///
+ /// Reads the problem details of a response.
+ ///
+ /// The HTTP response to read.
+ /// The deserialized problem details.
+ private async Task ReadProblemDetailsAsync(HttpResponseMessage response)
+ {
+ string content = await response.Content.ReadAsStringAsync();
+ return JsonSerializer.Deserialize(content, _jsonOptions);
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Cleans up the seeded database rows, the temporary files and the test user of the test.
+ ///
+ public async Task DisposeAsync()
+ {
+ using (IServiceScope scope = _apiFactory.Services.CreateScope())
+ {
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ foreach (Guid trackId in _seededTrackIds)
+ {
+ TrackEntity? track = dbContext.Tracks.Find(trackId);
+ if (track is not null)
+ dbContext.Tracks.Remove(track);
+ }
+ foreach (Guid albumId in _seededAlbumIds)
+ {
+ AlbumEntity? album = dbContext.Albums.Find(albumId);
+ if (album is not null)
+ dbContext.Albums.Remove(album);
+ }
+ foreach (Guid artistId in _seededArtistIds)
+ {
+ ArtistEntity? artist = dbContext.Artists.Find(artistId);
+ if (artist is not null)
+ dbContext.Artists.Remove(artist);
+ }
+ foreach (Guid libraryId in _seededLibraryIds)
+ {
+ LibraryEntity? library = dbContext.Libraries.Find(libraryId);
+ if (library is not null)
+ dbContext.Libraries.Remove(library);
+ }
+ await dbContext.SaveChangesAsync();
+ }
+ if (Directory.Exists(_contentRootPath))
+ Directory.Delete(_contentRootPath, recursive: true);
+ foreach (string temporaryFile in _temporaryFiles)
+ if (File.Exists(temporaryFile))
+ File.Delete(temporaryFile);
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs
index e36b6f1e..6756559f 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.HealthChecks;
using Lumina.Presentation.Web.Fixtures.Common.Api;
@@ -29,6 +28,11 @@ public class LuminaWebFactory : WebApplicationFactory, IDisposable
///
public StubApiHttpClient ApiClientStub { get; } = new();
+ ///
+ /// Gets the stub used in place of the remote streaming API client.
+ ///
+ public StubStreamingApiHttpClient StreamingApiClientStub { get; } = new();
+
///
/// Initializes a new instance of the class.
///
@@ -44,7 +48,7 @@ public class LuminaWebFactory : WebApplicationFactory, IDisposable
{
builder.ConfigureAppConfiguration((context, config) =>
{
- // provide the application configuration values that the Web app validates on startup
+ // Provide the application configuration values that the Web app validates on startup.
config.AddInMemoryCollection(initialData: new Dictionary
{
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY,
@@ -55,14 +59,19 @@ public class LuminaWebFactory : WebApplicationFactory, IDisposable
});
builder.ConfigureServices(services =>
{
- // remove the typed HTTP client registration, so that the stub can take its place
- ServiceDescriptor[] apiClientDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient)).ToArray();
+ // Remove the typed HTTP client registration, so that the stub can take its place.
+ ServiceDescriptor[] apiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient))];
foreach (ServiceDescriptor descriptor in apiClientDescriptors)
services.Remove(descriptor);
services.AddSingleton(ApiClientStub);
- // the API reachability health check resolves ApiReachabilityHealthCheck from DI when it runs; replace its
- // registration with a healthy subclass, since no real API exists during these tests
+ // Remove the typed streaming HTTP client registration, so that the streaming stub can take its place.
+ ServiceDescriptor[] streamingApiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IStreamingApiHttpClient))];
+ foreach (ServiceDescriptor descriptor in streamingApiClientDescriptors)
+ services.Remove(descriptor);
+ services.AddSingleton(StreamingApiClientStub);
+
+ // The API reachability health check resolves ApiReachabilityHealthCheck from DI when it runs; replace its registration with a healthy subclass, since no real API exists during these tests.
services.RemoveAll();
services.AddScoped();
});
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs
new file mode 100644
index 00000000..3cad3434
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs
@@ -0,0 +1,194 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
+using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetPlaybackManifestEndpointTests : IClassFixture
+{
+ private const string VALID_DELIVERY_ID = "0123456789abcdef0123456789abcdef";
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly PlaybackManifestDtoFixture _playbackManifestDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetPlaybackManifestEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetPlaybackManifest_WhenManifestIsNotADirectPlay_ShouldReturnTheWebProxyPaths()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
+ trackId: trackId,
+ isDirectPlay: false,
+ deliveryId: VALID_DELIVERY_ID,
+ segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
+ string expectedStreamPath = $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}";
+ string expectedSegmentStreamPathTemplate = $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{{deliveryId}}/{{segmentIndex}}?libraryId={libraryId}";
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(expectedStreamPath, data.GetProperty("streamPath").GetString());
+ Assert.Equal(expectedSegmentStreamPathTemplate, data.GetProperty("segmentStreamPathTemplate").GetString());
+ Assert.Equal(VALID_DELIVERY_ID, data.GetProperty("deliveryId").GetString());
+ Assert.DoesNotContain("http", data.GetProperty("streamPath").GetString(), StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("http", data.GetProperty("segmentStreamPathTemplate").GetString(), StringComparison.OrdinalIgnoreCase);
+ Assert.Contains("private", response.Headers.CacheControl?.ToString());
+ Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
+ Assert.Contains("Cookie", response.Headers.Vary);
+ }
+
+ [Fact]
+ public async Task GetPlaybackManifest_WhenManifestIsADirectPlay_ShouldReturnNullDeliveryAndTemplate()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
+ trackId: trackId,
+ isDirectPlay: true,
+ includeDeliveryId: false,
+ includeSegmentStreamPathTemplate: false);
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using JsonDocument json = JsonDocument.Parse(content);
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(JsonValueKind.Null, data.GetProperty("deliveryId").ValueKind);
+ Assert.Equal(JsonValueKind.Null, data.GetProperty("segmentStreamPathTemplate").ValueKind);
+ }
+
+ [Fact]
+ public async Task GetPlaybackManifest_WhenApiDeclaresATemplateWithAnInvalidDeliveryId_ShouldReturnBadGateway()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(
+ trackId: trackId,
+ isDirectPlay: false,
+ deliveryId: "not-a-valid-handle",
+ segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}");
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest", manifest);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = CreateGetRequest(libraryId, artistId, albumId, trackId);
+ // The player fetch classifies as a raw media request, which is answered with a bare status instead of a page or a JSON body.
+ getRequest.Headers.Accept.Clear();
+ getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg"));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
+ Assert.Equal(string.Empty, content);
+ }
+
+ [Fact]
+ public async Task GetPlaybackManifest_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/api-get-playback-manifest?libraryId={Guid.NewGuid()}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task GetPlaybackManifest_WithSQLInjectionInRouteId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid libraryId = Guid.NewGuid();
+ string normalizedId = Guid.Empty.ToString();
+ PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create(isDirectPlay: true, includeDeliveryId: false, includeSegmentStreamPathTemplate: false);
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/playback-manifest", manifest);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(maliciousId)}/albums/{Uri.EscapeDataString(maliciousId)}/tracks/{Uri.EscapeDataString(maliciousId)}/api-get-playback-manifest?libraryId={libraryId}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using (JsonDocument json = JsonDocument.Parse(content))
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousId, content, StringComparison.Ordinal);
+ Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/playback-manifest");
+ }
+
+ ///
+ /// Creates an authenticated JSON request for the playback manifest of a track.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The configured request.
+ private static HttpRequestMessage CreateGetRequest(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
+ {
+ HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest?libraryId={libraryId}");
+ getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ return getRequest;
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs
new file mode 100644
index 00000000..d2396887
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs
@@ -0,0 +1,202 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.Exceptions;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class StreamMusicTrackSegmentEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public StreamMusicTrackSegmentEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task StreamMusicTrackSegment_WhenRequestIsValid_ShouldProxyTheApiSegment()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.StreamingApiClientStub.Reset();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ string deliveryId = Guid.NewGuid().ToString("N");
+ const int SEGMENT_INDEX = 3;
+ string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId, deliveryId, SEGMENT_INDEX);
+ byte[] contentBytes = CreateBytes(1024);
+ _apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(contentBytes));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId, deliveryId, SEGMENT_INDEX));
+ byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
+ Assert.Equal("audio/mp4", response.Content.Headers.ContentType?.MediaType);
+ Assert.Equal(contentBytes.Length, response.Content.Headers.ContentLength);
+ Assert.Equal(contentBytes, responseBytes);
+ Assert.Equal("9", response.Headers.GetValues(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME).Single());
+ Assert.Equal("6.5", response.Headers.GetValues(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME).Single());
+ Assert.Equal("300", response.Headers.GetValues(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME).Single());
+ Assert.Contains("private", response.Headers.CacheControl?.ToString());
+ Assert.DoesNotContain("public", response.Headers.CacheControl?.ToString());
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
+ Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]);
+ }
+
+ [Fact]
+ public async Task StreamMusicTrackSegment_WhenDeliveryIdIsInvalid_ShouldReturnNotFoundWithoutCallingTheApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.StreamingApiClientStub.Reset();
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N").ToUpperInvariant(), 0));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ Assert.Equal(string.Empty, content);
+ Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
+ }
+
+ [Theory]
+ [InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition
+ [InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached
+ public async Task StreamMusicTrackSegment_WhenApiReportsATransientCondition_ShouldReturnABareStatus(HttpStatusCode statusCode)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.StreamingApiClientStub.Reset();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ string deliveryId = Guid.NewGuid().ToString("N");
+ string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId, deliveryId, 0);
+ _apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException(
+ new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode },
+ statusCode,
+ expectedEndpoint));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal(string.Empty, content);
+ }
+
+ [Fact]
+ public async Task StreamMusicTrackSegment_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.StreamingApiClientStub.Reset();
+ HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N"), 0));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
+ }
+
+ ///
+ /// Builds the browser facing route of a single segment of the normalized audio of a track.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The opaque handle of the normalized delivery.
+ /// The zero based index of the segment.
+ /// The browser facing route of the requested segment.
+ private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
+ {
+ return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}?libraryId={libraryId}";
+ }
+
+ ///
+ /// Builds the upstream endpoint the segment request is expected to be sent to.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The opaque handle of the normalized delivery.
+ /// The zero based index of the segment.
+ /// The expected upstream endpoint.
+ private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
+ {
+ return ApiRoutes.Music.STREAM_TRACK_SEGMENT
+ .Replace("{libraryId}", libraryId.ToString())
+ .Replace("{artistId}", artistId.ToString())
+ .Replace("{albumId}", albumId.ToString())
+ .Replace("{trackId}", trackId.ToString())
+ .Replace("{deliveryId}", deliveryId)
+ .Replace("{segmentIndex}", segmentIndex.ToString(CultureInfo.InvariantCulture));
+ }
+
+ ///
+ /// Creates a streamed API response with a partial content status, a body and the segment headers.
+ ///
+ /// The bytes of the content of the response.
+ /// The created streamed response.
+ private static async Task CreateStreamResultAsync(byte[] contentBytes)
+ {
+ HttpResponseMessage response = new(HttpStatusCode.PartialContent)
+ {
+ Content = new ByteArrayContent(contentBytes)
+ };
+ response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp4");
+ response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(60) };
+ response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, "9");
+ response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, "6.5");
+ response.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, "300");
+ return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
+ }
+
+ ///
+ /// Creates a deterministic byte array that stands in for the content of a segment.
+ ///
+ /// The number of bytes to create.
+ /// The created bytes.
+ private static byte[] CreateBytes(int length)
+ {
+ return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs
new file mode 100644
index 00000000..69860c5d
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs
@@ -0,0 +1,316 @@
+#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.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+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.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
+
+///
+/// Contains security tests for the class.
+///
+///
+/// The concurrency rate limiter of the segment route is not exercised, because it requires four concurrent long lived streams, which needs a real
+/// normalization pipeline and ffmpeg, neither of which is available in the test environment.
+///
+[ExcludeFromCodeCoverage]
+public class GetTrackSegmentEndpointTests : IClassFixture, IDisposable
+{
+ private const int DEFAULT_SEGMENT_INDEX = 0;
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-security-tests-{Guid.NewGuid():N}");
+ 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();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetTrackSegmentEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ Directory.CreateDirectory(_contentRootPath);
+ }
+
+ [Fact]
+ public async Task GetTrackSegment_WhenCalledWithoutCredentials_ShouldReturnUnauthorizedResult()
+ {
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N"), 0));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal("Unauthorized", problemDetails!["title"].GetString());
+ }
+
+ [Theory]
+ [InlineData("libraryId", "'; DROP TABLE Tracks; --")] // destructive injection in the library Id
+ [InlineData("libraryId", "' OR '1'='1")] // boolean based injection in the library Id
+ [InlineData("artistId", "'; DROP TABLE Tracks; --")] // destructive injection in the artist Id
+ [InlineData("artistId", "'; EXEC xp_cmdshell('dir'); --")] // command execution attempt in the artist Id
+ [InlineData("albumId", "' OR '1'='1")] // boolean based injection in the album Id
+ [InlineData("albumId", "'; DROP TABLE Tracks; --")] // destructive injection in the album Id
+ [InlineData("trackId", "' OR '1'='1")] // boolean based injection in the track Id
+ [InlineData("trackId", "'; EXEC xp_cmdshell('dir'); --")] // command execution attempt in the track Id
+ [InlineData("deliveryId", "'; DROP TABLE Tracks; --")] // destructive injection in the delivery handle
+ [InlineData("deliveryId", "' OR '1'='1")] // boolean based injection in the delivery handle
+ [InlineData("segmentIndex", "'; DROP TABLE Tracks; --")] // destructive injection in the segment index
+ [InlineData("segmentIndex", "' OR '1'='1")] // boolean based injection in the segment index
+ [InlineData("libraryId", "../../etc/passwd")] // path traversal in the library Id
+ [InlineData("artistId", "../../etc/passwd")] // path traversal in the artist Id
+ [InlineData("albumId", "../../etc/passwd")] // path traversal in the album Id
+ [InlineData("trackId", "../../etc/passwd")] // path traversal in the track Id
+ [InlineData("deliveryId", "../../etc/passwd")] // path traversal in the delivery handle
+ [InlineData("segmentIndex", "../../etc/passwd")] // path traversal in the segment index
+ public async Task GetTrackSegment_WithAnInjectionPayloadInARouteValue_ShouldNotFailOrLeakData(string routeValue, string payload)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ string path = BuildSegmentPathWithPayload(routeValue, payload);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(path);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("/etc/passwd", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("C:\\", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetTrackSegment_WhenDeliveryIdIsWellFormedButUnknown_ShouldReturnGenericNotFound()
+ {
+ // Arrange
+ (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ // A library owned by the authenticated user keeps the ownership check passing, so the unknown handle is what rejects the request.
+ Guid libraryId = await SeedLibraryAsync(userId);
+ string unknownDeliveryId = Guid.NewGuid().ToString("N");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), unknownDeliveryId, 0));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal("General.NotFound", problemDetails!.Title);
+ Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetTrackSegment_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutLeakingTheTrackPath()
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ Guid otherUserId = await SeedOtherUserAsync();
+ string secretTrackPath = Path.Combine(_contentRootPath, $"secret-{Guid.NewGuid():N}.flac");
+ (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, secretTrackPath);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, Guid.NewGuid().ToString("N"), 0));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ Assert.DoesNotContain("secret-", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(secretTrackPath, content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ }
+
+ [Fact]
+ public async Task GetTrackSegment_WhenManifestHandleIsUsedForAnotherTrack_ShouldReturnNotFound()
+ {
+ // Arrange
+ (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ string trackPath = Path.Combine(_contentRootPath, $"delivered-{Guid.NewGuid():N}.ogg");
+ await File.WriteAllBytesAsync(trackPath, [1, 2, 3, 4, 5, 6, 7, 8]);
+ (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
+ string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
+ Guid otherTrackId = Guid.NewGuid();
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, otherTrackId, deliveryId, 0));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal("General.NotFound", problemDetails!.Title);
+ Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
+ Assert.DoesNotContain(trackPath, content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded other user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Seeds a music library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album.
+ ///
+ /// The Id of the user that owns the library.
+ /// The file system path of the audio file of the track.
+ /// The Ids of the seeded library, artist, album and track.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ 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, contentLocations: [_contentRootPath]));
+ 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,
+ path: trackPath,
+ container: "OGG",
+ audioCodec: "OPUS",
+ title: "A Track",
+ includeMetadata: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId, trackId);
+ }
+
+ ///
+ /// Requests a transcoded playback manifest for the seeded track and returns the delivery handle it reports.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The delivery handle of the normalized delivery.
+ private async Task GetDeliveryIdAsync(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
+ {
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ PlaybackManifestResponse? manifest = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(manifest);
+ Assert.NotNull(manifest!.DeliveryId);
+ return manifest.DeliveryId;
+ }
+
+ ///
+ /// Builds the route of a single segment of the normalized audio of a track.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The opaque handle of the normalized delivery.
+ /// The zero based index of the segment.
+ /// The route of the requested segment.
+ private static string BuildSegmentPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
+ {
+ return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}";
+ }
+
+ ///
+ /// Builds the route of a single segment of the normalized audio of a track, with a malicious payload in one of its route values.
+ ///
+ /// The name of the route value that carries the payload.
+ /// The malicious payload.
+ /// The route of the requested segment, with the payload URL-escaped.
+ private static string BuildSegmentPathWithPayload(string routeValue, string payload)
+ {
+ string libraryId = routeValue == "libraryId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
+ string artistId = routeValue == "artistId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
+ string albumId = routeValue == "albumId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
+ string trackId = routeValue == "trackId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
+ string deliveryId = routeValue == "deliveryId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString("N");
+ string segmentIndex = routeValue == "segmentIndex" ? Uri.EscapeDataString(payload) : DEFAULT_SEGMENT_INDEX.ToString();
+ return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}";
+ }
+
+ ///
+ /// Disposes the API factory resources, the seeded users and the temporary files of the test.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ if (Directory.Exists(_contentRootPath))
+ Directory.Delete(_contentRootPath, recursive: true);
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs
index ba24862e..b3c19509 100644
--- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Common/Setup/LuminaWebFactory.cs
@@ -1,15 +1,11 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Fixtures.Common.Api;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
-using System;
-using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Common.Setup;
@@ -27,6 +23,11 @@ public class LuminaWebFactory : WebApplicationFactory, IDisposable
///
public StubApiHttpClient ApiClientStub { get; } = new();
+ ///
+ /// Gets the stub used in place of the remote streaming API client.
+ ///
+ public StubStreamingApiHttpClient StreamingApiClientStub { get; } = new();
+
///
/// Initializes a new instance of the class.
///
@@ -42,7 +43,7 @@ public class LuminaWebFactory : WebApplicationFactory, IDisposable
{
builder.ConfigureAppConfiguration((context, config) =>
{
- // provide the application configuration values that the Web app validates on startup
+ // Provide the application configuration values that the Web app validates on startup.
config.AddInMemoryCollection(initialData: new Dictionary
{
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY,
@@ -53,11 +54,17 @@ public class LuminaWebFactory : WebApplicationFactory, IDisposable
});
builder.ConfigureServices(services =>
{
- // remove the typed HTTP client registration, so that the stub can take its place
- ServiceDescriptor[] apiClientDescriptors = services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient)).ToArray();
+ // Remove the typed HTTP client registration, so that the stub can take its place.
+ ServiceDescriptor[] apiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient))];
foreach (ServiceDescriptor descriptor in apiClientDescriptors)
services.Remove(descriptor);
services.AddSingleton(ApiClientStub);
+
+ // Remove the typed streaming HTTP client registration, so that the streaming stub can take its place.
+ ServiceDescriptor[] streamingApiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IStreamingApiHttpClient))];
+ foreach (ServiceDescriptor descriptor in streamingApiClientDescriptors)
+ services.Remove(descriptor);
+ services.AddSingleton(StreamingApiClientStub);
});
}
}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs
new file mode 100644
index 00000000..7852091e
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs
@@ -0,0 +1,201 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.SecurityTests.Common.Setup;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment;
+
+///
+/// Contains security tests for the class.
+///
+///
+/// The concurrency rate limiter of the segment route is not exercised, because it requires four concurrent long lived streams, which needs a real
+/// normalization pipeline and ffmpeg, neither of which is available in the test environment.
+///
+[ExcludeFromCodeCoverage]
+public class StreamMusicTrackSegmentEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public StreamMusicTrackSegmentEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task StreamMusicTrackSegment_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.StreamingApiClientStub.Reset();
+ HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N"), 0));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection in the delivery handle
+ [InlineData("' OR '1'='1")] // boolean based injection in the delivery handle
+ [InlineData("../../etc/passwd")] // path traversal in the delivery handle
+ public async Task StreamMusicTrackSegment_WithAnInjectionPayloadInDeliveryId_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.StreamingApiClientStub.Reset();
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(
+ Guid.NewGuid(),
+ Guid.NewGuid(),
+ Guid.NewGuid(),
+ Guid.NewGuid(),
+ Uri.EscapeDataString(payload),
+ 0));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ Assert.Equal(string.Empty, content);
+ Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
+ Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
+ }
+
+ [Theory]
+ [InlineData("artistId")] // injection in the artist Id
+ [InlineData("albumId")] // injection in the album Id
+ [InlineData("trackId")] // injection in the track Id
+ public async Task StreamMusicTrackSegment_WithAnInjectionPayloadInATrackRouteId_ShouldNormalizeTheIdWithoutLeakingData(string routeValue)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.StreamingApiClientStub.Reset();
+ const string PAYLOAD = "'; DROP TABLE Tracks; --";
+ Guid libraryId = Guid.NewGuid();
+ string validArtistId = Guid.NewGuid().ToString();
+ string validAlbumId = Guid.NewGuid().ToString();
+ string validTrackId = Guid.NewGuid().ToString();
+ string deliveryId = Guid.NewGuid().ToString("N");
+ string artistId = routeValue == "artistId" ? Uri.EscapeDataString(PAYLOAD) : validArtistId;
+ string albumId = routeValue == "albumId" ? Uri.EscapeDataString(PAYLOAD) : validAlbumId;
+ string trackId = routeValue == "trackId" ? Uri.EscapeDataString(PAYLOAD) : validTrackId;
+ string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT
+ .Replace("{libraryId}", libraryId.ToString())
+ .Replace("{artistId}", routeValue == "artistId" ? Guid.Empty.ToString() : validArtistId)
+ .Replace("{albumId}", routeValue == "albumId" ? Guid.Empty.ToString() : validAlbumId)
+ .Replace("{trackId}", routeValue == "trackId" ? Guid.Empty.ToString() : validTrackId)
+ .Replace("{deliveryId}", deliveryId)
+ .Replace("{segmentIndex}", "0");
+ byte[] contentBytes = CreateBytes(128);
+ _apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(contentBytes));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(
+ $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/0?libraryId={libraryId}");
+ byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
+ Assert.Equal(contentBytes, responseBytes);
+ Assert.DoesNotContain("SQL", System.Text.Encoding.UTF8.GetString(responseBytes), StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", System.Text.Encoding.UTF8.GetString(responseBytes), StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("at Lumina", System.Text.Encoding.UTF8.GetString(responseBytes), StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(PAYLOAD, System.Text.Encoding.UTF8.GetString(responseBytes), StringComparison.Ordinal);
+ Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
+ Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]);
+ }
+
+ [Fact]
+ public async Task StreamMusicTrackSegment_WhenTheApiDeclaresAPublicCache_ShouldNeverExposeAPublicCacheControl()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.StreamingApiClientStub.Reset();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ string deliveryId = Guid.NewGuid().ToString("N");
+ string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT
+ .Replace("{libraryId}", libraryId.ToString())
+ .Replace("{artistId}", artistId.ToString())
+ .Replace("{albumId}", albumId.ToString())
+ .Replace("{trackId}", trackId.ToString())
+ .Replace("{deliveryId}", deliveryId)
+ .Replace("{segmentIndex}", "0");
+ _apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(CreateBytes(64)));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId, deliveryId, 0));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
+ string cacheControl = response.Headers.CacheControl?.ToString() ?? string.Empty;
+ Assert.DoesNotContain("public", cacheControl, StringComparison.OrdinalIgnoreCase);
+ Assert.Contains("private", cacheControl);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ }
+
+ ///
+ /// Builds the browser facing route of a single segment of the normalized audio of a track.
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The Id of the album the track belongs to.
+ /// The Id of the track.
+ /// The opaque handle of the normalized delivery.
+ /// The zero based index of the segment.
+ /// The browser facing route of the requested segment.
+ private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
+ {
+ return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}?libraryId={libraryId}";
+ }
+
+ ///
+ /// Creates a streamed API response with a partial content status and a body.
+ ///
+ /// The bytes of the content of the response.
+ /// The created streamed response.
+ private static async Task CreateStreamResultAsync(byte[] contentBytes)
+ {
+ HttpResponseMessage response = new(HttpStatusCode.PartialContent)
+ {
+ Content = new ByteArrayContent(contentBytes)
+ };
+ response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp4");
+ response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(120) };
+ return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
+ }
+
+ ///
+ /// Creates a deterministic byte array that stands in for the content of a segment.
+ ///
+ /// The number of bytes to create.
+ /// The created bytes.
+ private static byte[] CreateBytes(int length)
+ {
+ return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryIdTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryIdTests.cs
new file mode 100644
index 00000000..ad8a36a9
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryIdTests.cs
@@ -0,0 +1,70 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using System;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackDeliveryIdTests
+{
+ [Fact]
+ public void CHARACTER_COUNT_WhenAccessed_ShouldBeThirtyTwo()
+ {
+ // Act
+ int characterCount = PlaybackDeliveryId.CHARACTER_COUNT;
+
+ // Assert
+ Assert.Equal(32, characterCount);
+ }
+
+ [Fact]
+ public void IsValid_WhenValueIsTheNFormatOfAGuid_ShouldReturnTrue()
+ {
+ // Arrange
+ string value = Guid.NewGuid().ToString("N");
+
+ // Act
+ bool isValid = PlaybackDeliveryId.IsValid(value);
+
+ // Assert
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void IsValid_WhenValueIsTheLowestPossibleHandle_ShouldReturnTrue()
+ {
+ // Arrange
+ string value = Guid.Empty.ToString("N");
+
+ // Act
+ bool isValid = PlaybackDeliveryId.IsValid(value);
+
+ // Assert
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData(null)] // an absent handle cannot address a delivery
+ [InlineData("")] // an empty handle has the wrong length
+ [InlineData(" ")] // a whitespace handle has the wrong length
+ [InlineData(" ")] // a handle made only of whitespace has the right length but is not hexadecimal
+ [InlineData("0123456789abcdef0123456789abcde")] // 31 characters, one short of a handle
+ [InlineData("0123456789abcdef0123456789abcdef0")] // 33 characters, one over a handle
+ [InlineData("0123456789ABCDEF0123456789ABCDEF")] // uppercase hexadecimal is not the canonical lowercase form
+ [InlineData("01234567-89ab-cdef-0123-456789abcdef")] // the D format of a Guid carries dashes
+ [InlineData("0123456789abcdef0123456789abcdeg")] // the last character is not a hexadecimal digit
+ [InlineData("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")] // no character is a hexadecimal digit
+ public void IsValid_WhenValueIsNotACanonicalHandle_ShouldReturnFalse(string? value)
+ {
+ // Act
+ bool isValid = PlaybackDeliveryId.IsValid(value);
+
+ // Assert
+ Assert.False(isValid);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandlerTests.cs
new file mode 100644
index 00000000..d3d95c94
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandlerTests.cs
@@ -0,0 +1,650 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
+using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Repositories.Users;
+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.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetPlaybackManifestQueryHandlerTests : IDisposable
+{
+ private readonly IUnitOfWork _mockUnitOfWork;
+ private readonly ITrackRepository _mockTrackRepository;
+ private readonly IUserSettingsRepository _mockUserSettingsRepository;
+ private readonly ILibraryRepository _mockLibraryRepository;
+ private readonly IPlaybackFormatService _mockPlaybackFormatService;
+ private readonly IPlaybackDeliveryHandleService _mockPlaybackDeliveryHandleService;
+ private readonly IAuthorizationService _mockAuthorizationService;
+ private readonly ICurrentUserService _mockCurrentUserService;
+ private readonly IPathService _mockPathService;
+ private readonly IValidator _mockValidator;
+ private readonly GetPlaybackManifestQueryHandler _sut;
+ private readonly Guid _userId;
+ private readonly string _issuedDeliveryId;
+ private readonly string _sandboxRoot;
+ private readonly string _libraryRoot;
+ private readonly string _sourcePath;
+ private PlaybackDeliveryHandleDto? _issuedDelivery;
+ private readonly GetPlaybackManifestQueryFixture _getPlaybackManifestQueryFixture = new();
+ private readonly TrackPlaybackManifestDtoFixture _trackPlaybackManifestDtoFixture = new();
+ private readonly PlaybackDeliveryDecisionDtoFixture _playbackDeliveryDecisionDtoFixture = new();
+ private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetPlaybackManifestQueryHandlerTests()
+ {
+ _mockTrackRepository = Substitute.For();
+ _mockUserSettingsRepository = Substitute.For();
+ _mockLibraryRepository = Substitute.For();
+ _mockUnitOfWork = Substitute.For();
+ _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
+ _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
+ _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
+ _mockPlaybackFormatService = Substitute.For();
+ _mockPlaybackDeliveryHandleService = Substitute.For();
+ _mockAuthorizationService = Substitute.For();
+ _mockCurrentUserService = Substitute.For();
+ _mockPathService = Substitute.For();
+ _mockValidator = Substitute.For>();
+ _userId = Guid.NewGuid();
+ _issuedDeliveryId = Guid.NewGuid().ToString("N");
+ _sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-playback-manifest-tests-" + Guid.NewGuid().ToString("N"));
+ _libraryRoot = Path.Combine(_sandboxRoot, "library");
+ _sourcePath = Path.Combine(_libraryRoot, "track.flac");
+ Directory.CreateDirectory(_libraryRoot);
+
+ // Default stubs: the user is authenticated, the library ownership policy allows access, the query validates and every path is inside its content location.
+ _mockCurrentUserService.UserId.Returns(_userId);
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(true);
+ _mockValidator.Validate(Arg.Any()).Returns([]);
+ _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true);
+
+ _sut = new GetPlaybackManifestQueryHandler(
+ _mockUnitOfWork,
+ _mockPlaybackFormatService,
+ _mockPlaybackDeliveryHandleService,
+ _mockAuthorizationService,
+ _mockCurrentUserService,
+ _mockPathService,
+ _mockValidator);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutReadingAnything()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryIdCannotBeEmpty]);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockTrackRepository.DidNotReceive().GetPlaybackManifestInfoAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ _mockCurrentUserService.UserId.Returns((Guid?)null);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenLibraryOwnershipIsDenied_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(false);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockTrackRepository.DidNotReceive().GetPlaybackManifestInfoAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheTrackLookupFails_ShouldReturnItsError()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ Guid libraryId = Guid.Parse(query.LibraryId!);
+ Guid albumId = Guid.Parse(query.AlbumId!);
+ Guid artistId = Guid.Parse(query.ArtistId!);
+ Guid trackId = Guid.Parse(query.TrackId!);
+ _mockTrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, Arg.Any())
+ .Returns(Errors.Music.TrackFileNotFound);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
+ _mockPlaybackFormatService.DidNotReceive().DecideDelivery(Arg.Any(), Arg.Any>());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheTrackIsNotFound_ShouldReturnTrackNotFoundError()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ Guid libraryId = Guid.Parse(query.LibraryId!);
+ Guid albumId = Guid.Parse(query.AlbumId!);
+ Guid artistId = Guid.Parse(query.ArtistId!);
+ Guid trackId = Guid.Parse(query.TrackId!);
+ _mockTrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, Arg.Any())
+ .Returns(Result.From(null));
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
+ _mockPlaybackFormatService.DidNotReceive().DecideDelivery(Arg.Any(), Arg.Any>());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheDeliveryDecisionFails_ShouldReturnItsError()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(
+ path: _sourcePath, container: "AIFF", audioCodec: "PCM");
+ StubTrackLookup(query, track);
+ _mockPlaybackFormatService.DecideDelivery(Arg.Any(), Arg.Any>())
+ .Returns(Errors.Playback.NoSupportedPlaybackFormat);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Playback.NoSupportedPlaybackFormat, result.FirstError);
+ await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheStoredAudioIsPlayedDirectly_ShouldReturnTheStoredFieldsWithoutIssuingADelivery()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(
+ path: _sourcePath,
+ container: "FLAC",
+ audioCodec: "FLAC",
+ durationInSeconds: 245,
+ sampleRate: 48000,
+ channels: 2,
+ bitDepth: 24,
+ replayGainTrackGain: -6.5m,
+ replayGainTrackPeak: 0.98m,
+ replayGainAlbumGain: -7.1m,
+ replayGainAlbumPeak: 0.97m);
+ PlaybackDeliveryDecisionDto decision = _playbackDeliveryDecisionDtoFixture.Create(
+ mode: PlaybackDeliveryMode.DirectPlay,
+ container: "FLAC",
+ codec: "FLAC",
+ shape: PlaybackDeliveryShape.ByteRangeSeekable,
+ segmentDurationSeconds: 0);
+ StubTrackLookup(query, track);
+ _mockPlaybackFormatService.DecideDelivery(Arg.Any(), Arg.Any>())
+ .Returns(Result.From(decision));
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Guid.Parse(query.TrackId!), result.Value.TrackId);
+ Assert.Equal(245, result.Value.DurationInSeconds);
+ Assert.Equal("FLAC", result.Value.SourceContainer);
+ Assert.Equal("FLAC", result.Value.SourceCodec);
+ Assert.Equal(48000, result.Value.SampleRate);
+ Assert.Equal(2, result.Value.Channels);
+ Assert.Equal(24, result.Value.BitDepth);
+ Assert.Equal(-6.5m, result.Value.ReplayGainTrackGain);
+ Assert.Equal(0.98m, result.Value.ReplayGainTrackPeak);
+ Assert.Equal(-7.1m, result.Value.ReplayGainAlbumGain);
+ Assert.Equal(0.97m, result.Value.ReplayGainAlbumPeak);
+ Assert.True(result.Value.IsDirectPlay);
+ Assert.Null(result.Value.DeliveryContainer);
+ Assert.Null(result.Value.DeliveryCodec);
+ Assert.Null(result.Value.DeliveryShape);
+ Assert.Null(result.Value.SegmentDurationSeconds);
+ Assert.True(result.Value.IsSeekable);
+ Assert.Equal(query.StreamPath, result.Value.StreamPath);
+ Assert.Null(result.Value.DeliveryId);
+ Assert.Null(result.Value.SegmentStreamPathTemplate);
+ _mockPlaybackDeliveryHandleService.DidNotReceive().IssueDeliveryId(Arg.Any());
+ await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any());
+ await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheUserHasNoSettings_ShouldCapTheNormalizedDeliveryAtAutoQuality()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ StubNormalizedDelivery(query, track, settings: null);
+ CaptureIssuedDelivery();
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.NotNull(_issuedDelivery);
+ Assert.Equal(PlaybackStreamingQuality.Auto, _issuedDelivery.Request.Quality);
+ await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheUserSettingsCannotBeRead_ShouldReturnTheirError()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ StubTrackLookup(query, track);
+ StubNormalizedDecision();
+ _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any())
+ .Returns(Errors.UserSettings.UserSettingsNotFound);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.UserSettings.UserSettingsNotFound, result.FirstError);
+ _mockPlaybackDeliveryHandleService.DidNotReceive().IssueDeliveryId(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheUserHasSettings_ShouldCaptureTheirStreamingQualityInTheDelivery()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, streamingQuality: PlaybackStreamingQuality.High);
+ StubNormalizedDelivery(query, track, settings: settings);
+ CaptureIssuedDelivery();
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.NotNull(_issuedDelivery);
+ Assert.Equal(PlaybackStreamingQuality.High, _issuedDelivery.Request.Quality);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheLibraryCannotBeRead_ShouldReturnItsError()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ Guid libraryId = Guid.Parse(query.LibraryId!);
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ StubTrackLookup(query, track);
+ StubNormalizedDecision();
+ _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()).Returns(Result.From(null));
+ _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Errors.Library.LibraryIdCannotBeEmpty);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
+ _mockPlaybackDeliveryHandleService.DidNotReceive().IssueDeliveryId(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheLibraryIsNotFound_ShouldReturnLibraryNotFoundError()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ Guid libraryId = Guid.Parse(query.LibraryId!);
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ StubTrackLookup(query, track);
+ StubNormalizedDecision();
+ _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()).Returns(Result.From(null));
+ _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(null));
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
+ _mockPlaybackDeliveryHandleService.DidNotReceive().IssueDeliveryId(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheSourceFileIsInsideAContentLocation_ShouldCaptureItsIdentityInTheDelivery()
+ {
+ // Arrange
+ byte[] sourceBytes = new byte[1234];
+ await File.WriteAllBytesAsync(_sourcePath, sourceBytes);
+ DateTime sourceLastModifiedUtc = new(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc);
+ File.SetLastWriteTimeUtc(_sourcePath, sourceLastModifiedUtc);
+ DateTime expectedLastModifiedUtc = File.GetLastWriteTimeUtc(_sourcePath);
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ StubNormalizedDelivery(query, track, settings: null);
+ CaptureIssuedDelivery();
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.NotNull(_issuedDelivery);
+ Assert.Equal(sourceBytes.Length, _issuedDelivery.Request.SourceLength);
+ Assert.Equal(expectedLastModifiedUtc, _issuedDelivery.Request.SourceLastModifiedUtc);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheSourceFileIsOutsideEveryContentLocation_ShouldNotCaptureItsIdentity()
+ {
+ // Arrange
+ await File.WriteAllBytesAsync(_sourcePath, new byte[1234]);
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ StubNormalizedDelivery(query, track, settings: null);
+ CaptureIssuedDelivery();
+ _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(false);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.NotNull(_issuedDelivery);
+ Assert.Equal(0, _issuedDelivery.Request.SourceLength);
+ Assert.Equal(DateTime.MinValue, _issuedDelivery.Request.SourceLastModifiedUtc);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenANormalizedDeliveryIsIssued_ShouldIssueTheExactDeclaredDelivery()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create(capabilities: "mp3/mp3,flac/flac");
+ Guid libraryId = Guid.Parse(query.LibraryId!);
+ Guid albumId = Guid.Parse(query.AlbumId!);
+ Guid artistId = Guid.Parse(query.ArtistId!);
+ Guid trackId = Guid.Parse(query.TrackId!);
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(
+ path: _sourcePath,
+ container: "FLAC",
+ audioCodec: "FLAC",
+ durationInSeconds: 245,
+ sampleRate: 48000,
+ channels: 2,
+ bitDepth: 24,
+ bitrate: 900);
+ PlaybackDeliveryDecisionDto decision = _playbackDeliveryDecisionDtoFixture.Create(
+ mode: PlaybackDeliveryMode.Transcode,
+ container: "MP3",
+ codec: "MP3",
+ shape: PlaybackDeliveryShape.TimeAddressedSegments,
+ segmentDurationSeconds: 6);
+ UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, streamingQuality: PlaybackStreamingQuality.High);
+ LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, contentLocations: [_libraryRoot]);
+ StubTrackLookup(query, track);
+ _mockPlaybackFormatService.DecideDelivery(Arg.Any(), Arg.Any>())
+ .Returns(Result.From(decision));
+ _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()).Returns(Result.From(settings));
+ _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(library));
+ CaptureIssuedDelivery();
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.NotNull(_issuedDelivery);
+ Assert.Equal(trackId, _issuedDelivery.Request.TrackId);
+ Assert.Equal(_userId, _issuedDelivery.Request.UserId);
+ Assert.Equal(PlaybackDeliveryMode.Transcode, _issuedDelivery.Request.Mode);
+ Assert.Equal("MP3", _issuedDelivery.Request.Container);
+ Assert.Equal("MP3", _issuedDelivery.Request.Codec);
+ Assert.Equal(6, _issuedDelivery.Request.SegmentDurationSeconds);
+ Assert.Equal(245, _issuedDelivery.Request.DurationInSeconds);
+ Assert.Equal(900, _issuedDelivery.Request.Bitrate);
+ Assert.Equal(48000, _issuedDelivery.Request.SampleRate);
+ Assert.Equal(2, _issuedDelivery.Request.Channels);
+ Assert.Equal(24, _issuedDelivery.Request.BitDepth);
+ Assert.Equal(PlaybackStreamingQuality.High, _issuedDelivery.Request.Quality);
+ Assert.Equal(_sourcePath, _issuedDelivery.Request.SourcePath);
+ Assert.Equal([_libraryRoot], _issuedDelivery.Request.AllowedRoots);
+ Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, _issuedDelivery.Shape);
+ Assert.Equal(libraryId, _issuedDelivery.LibraryId);
+ Assert.Equal(albumId, _issuedDelivery.AlbumId);
+ Assert.Equal(artistId, _issuedDelivery.ArtistId);
+ _mockPlaybackFormatService.Received(1).DecideDelivery(
+ Arg.Is(format => format.Container == "FLAC" && format.Codec == "FLAC"),
+ Arg.Is>(capabilities => capabilities.Count == 2));
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenATimeAddressedDeliveryIsIssued_ShouldReturnItsDeliveryShapeAndSeekMap()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ StubNormalizedDelivery(query, track, settings: null);
+ CaptureIssuedDelivery();
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.False(result.Value.IsDirectPlay);
+ Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.DeliveryShape);
+ Assert.Equal(6, result.Value.SegmentDurationSeconds);
+ Assert.True(result.Value.IsSeekable);
+ Assert.Equal(_issuedDeliveryId, result.Value.DeliveryId);
+ Assert.Equal(query.SegmentStreamPathTemplate, result.Value.SegmentStreamPathTemplate);
+ Assert.Equal(query.StreamPath, result.Value.StreamPath);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenANonTimeAddressedDeliveryIsIssued_ShouldNotReportASegmentDuration()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ TrackPlaybackManifestDto track = _trackPlaybackManifestDtoFixture.Create(path: _sourcePath);
+ PlaybackDeliveryDecisionDto decision = _playbackDeliveryDecisionDtoFixture.Create(
+ mode: PlaybackDeliveryMode.Remux,
+ container: "WAV",
+ codec: "PCM",
+ shape: PlaybackDeliveryShape.ByteRangeSeekable,
+ segmentDurationSeconds: 0);
+ StubTrackLookup(query, track);
+ _mockPlaybackFormatService.DecideDelivery(Arg.Any(), Arg.Any>())
+ .Returns(Result.From(decision));
+ StubSettings(null);
+ StubLibrary(Guid.Parse(query.LibraryId!));
+ CaptureIssuedDelivery();
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.False(result.Value.IsDirectPlay);
+ Assert.Equal(PlaybackDeliveryShape.ByteRangeSeekable, result.Value.DeliveryShape);
+ Assert.Null(result.Value.SegmentDurationSeconds);
+ Assert.True(result.Value.IsSeekable);
+ Assert.Equal(_issuedDeliveryId, result.Value.DeliveryId);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenCancellationIsRequestedWhileLookingUpTheTrack_ShouldCancelTheOperation()
+ {
+ // Arrange
+ GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create();
+ Guid libraryId = Guid.Parse(query.LibraryId!);
+ Guid albumId = Guid.Parse(query.AlbumId!);
+ Guid artistId = Guid.Parse(query.ArtistId!);
+ Guid trackId = Guid.Parse(query.TrackId!);
+ using CancellationTokenSource cancellationTokenSource = new();
+ cancellationTokenSource.Cancel();
+ _mockTrackRepository.GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, cancellationTokenSource.Token)
+ .Returns(Task.FromCanceled>(cancellationTokenSource.Token));
+
+ // Act & Assert
+ await Assert.ThrowsAsync(() => _sut.HandleAsync(query, cancellationTokenSource.Token));
+ await _mockTrackRepository.Received(1).GetPlaybackManifestInfoAsync(libraryId, albumId, artistId, trackId, cancellationTokenSource.Token);
+ }
+
+ ///
+ /// Stubs the track projection lookup of the query's route with the provided track.
+ ///
+ /// The query whose route identifiers are looked up.
+ /// The track projection the lookup returns.
+ private void StubTrackLookup(GetPlaybackManifestQuery query, TrackPlaybackManifestDto track)
+ {
+ _mockTrackRepository.GetPlaybackManifestInfoAsync(
+ Guid.Parse(query.LibraryId!),
+ Guid.Parse(query.AlbumId!),
+ Guid.Parse(query.ArtistId!),
+ Guid.Parse(query.TrackId!),
+ Arg.Any())
+ .Returns(Result.From(track));
+ }
+
+ ///
+ /// Stubs a non direct play delivery decision that produces time addressed six second segments.
+ ///
+ private void StubNormalizedDecision()
+ {
+ PlaybackDeliveryDecisionDto decision = _playbackDeliveryDecisionDtoFixture.Create(
+ mode: PlaybackDeliveryMode.Transcode,
+ container: "MP3",
+ codec: "MP3",
+ shape: PlaybackDeliveryShape.TimeAddressedSegments,
+ segmentDurationSeconds: 6);
+ _mockPlaybackFormatService.DecideDelivery(Arg.Any(), Arg.Any>())
+ .Returns(Result.From(decision));
+ }
+
+ ///
+ /// Stubs the user settings lookup with the provided settings, or with no settings when it is .
+ ///
+ /// The settings the lookup returns.
+ private void StubSettings(UserSettingsEntity? settings)
+ {
+ _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()).Returns(Result.From(settings));
+ }
+
+ ///
+ /// Stubs the library lookup with a library that has the test source directory as its content location.
+ ///
+ /// The Id of the library the lookup returns.
+ private void StubLibrary(Guid libraryId)
+ {
+ LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, contentLocations: [_libraryRoot]);
+ _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(library));
+ }
+
+ ///
+ /// Stubs the complete non direct play chain of the handler.
+ ///
+ /// The query whose route identifiers are looked up.
+ /// The track projection the lookup returns.
+ /// The settings the user settings lookup returns.
+ private void StubNormalizedDelivery(GetPlaybackManifestQuery query, TrackPlaybackManifestDto track, UserSettingsEntity? settings)
+ {
+ StubTrackLookup(query, track);
+ StubNormalizedDecision();
+ StubSettings(settings);
+ StubLibrary(Guid.Parse(query.LibraryId!));
+ }
+
+ ///
+ /// Configures the delivery handle service so that the delivery it is asked to issue is captured and a fixed handle is returned.
+ ///
+ private void CaptureIssuedDelivery()
+ {
+ _mockPlaybackDeliveryHandleService.IssueDeliveryId(Arg.Do(delivery => _issuedDelivery = delivery))
+ .Returns(_issuedDeliveryId);
+ }
+
+ ///
+ /// Releases the temporary directory the containment tests use.
+ ///
+ public void Dispose()
+ {
+ try
+ {
+ if (Directory.Exists(_sandboxRoot))
+ Directory.Delete(_sandboxRoot, recursive: true);
+ }
+ catch (IOException)
+ {
+ // A temporary directory that cannot be removed does not fail the test.
+ }
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandlerTests.cs
new file mode 100644
index 00000000..916fa44d
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandlerTests.cs
@@ -0,0 +1,411 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+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.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
+using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using NSubstitute;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetTrackSegmentQueryHandlerTests
+{
+ private readonly ITrackNormalizationService _mockTrackNormalizationService;
+ private readonly IPlaybackDeliveryHandleService _mockPlaybackDeliveryHandleService;
+ private readonly IAuthorizationService _mockAuthorizationService;
+ private readonly ICurrentUserService _mockCurrentUserService;
+ private readonly IPathService _mockPathService;
+ private readonly IValidator _mockValidator;
+ private readonly GetTrackSegmentQueryHandler _sut;
+ private readonly Guid _userId;
+ private readonly string _allowedRoot;
+ private readonly GetTrackSegmentQueryFixture _getTrackSegmentQueryFixture = new();
+ private readonly PlaybackDeliveryHandleDtoFixture _playbackDeliveryHandleDtoFixture = new();
+ private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
+ private readonly NormalizedTrackDtoFixture _normalizedTrackDtoFixture = new();
+ private readonly NormalizedTrackSegmentDtoFixture _normalizedTrackSegmentDtoFixture = new();
+
+ public static TheoryData DeliveryMismatchCases => ["Library", "Album", "Artist"];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetTrackSegmentQueryHandlerTests()
+ {
+ _mockTrackNormalizationService = Substitute.For();
+ _mockPlaybackDeliveryHandleService = Substitute.For();
+ _mockAuthorizationService = Substitute.For();
+ _mockCurrentUserService = Substitute.For();
+ _mockPathService = Substitute.For();
+ _mockValidator = Substitute.For>();
+ _userId = Guid.NewGuid();
+ _allowedRoot = Path.Combine(Path.GetTempPath(), "lumina-tests", "music");
+
+ // Default stubs: the user is authenticated, the library ownership policy allows access, the query validates and the source path is inside an allowed root.
+ _mockCurrentUserService.UserId.Returns(_userId);
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(true);
+ _mockValidator.Validate(Arg.Any()).Returns([]);
+ _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true);
+
+ _sut = new GetTrackSegmentQueryHandler(
+ _mockTrackNormalizationService,
+ _mockPlaybackDeliveryHandleService,
+ _mockAuthorizationService,
+ _mockCurrentUserService,
+ _mockPathService,
+ _mockValidator);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutResolvingTheDelivery()
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ _mockValidator.Validate(Arg.Any()).Returns([Errors.Playback.SegmentIndexMustBeValid]);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Playback.SegmentIndexMustBeValid, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ _mockPlaybackDeliveryHandleService.DidNotReceive().GetDelivery(Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ _mockCurrentUserService.UserId.Returns((Guid?)null);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ _mockPlaybackDeliveryHandleService.DidNotReceive().GetDelivery(Arg.Any(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenLibraryOwnershipIsDenied_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(false);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ _mockPlaybackDeliveryHandleService.DidNotReceive().GetDelivery(Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheDeliveryCannotBeResolved_ShouldReturnItsErrorWithoutProducingAudio()
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ Guid trackId = Guid.Parse(query.TrackId!);
+ _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Errors.Playback.PlaybackDeliveryNotFound);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
+ await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Theory]
+ [MemberData(nameof(DeliveryMismatchCases))]
+ public async Task HandleAsync_WhenTheDeliveryDoesNotDescribeTheRoute_ShouldReturnPlaybackDeliveryNotFoundError(string mismatch)
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ Guid trackId = Guid.Parse(query.TrackId!);
+ PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
+ delivery = mismatch switch
+ {
+ "Library" => delivery with { LibraryId = Guid.NewGuid() },
+ "Album" => delivery with { AlbumId = Guid.NewGuid() },
+ _ => delivery with { ArtistId = Guid.NewGuid() }
+ };
+ _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
+ await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheDeliveryIsADirectPlay_ShouldReturnNormalizationIsNotRequiredForDirectPlayError()
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ Guid trackId = Guid.Parse(query.TrackId!);
+ PlaybackDeliveryHandleDto delivery = CreateDelivery(query, mode: PlaybackDeliveryMode.DirectPlay);
+ _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Playback.NormalizationIsNotRequiredForDirectPlay, result.FirstError);
+ await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any(), Arg.Any());
+ }
+
+ public static TheoryData NonSegmentDeliveryCases => new()
+ {
+ { PlaybackDeliveryShape.ByteRangeSeekable, 6 }, // a byte range delivery has no indexable segment
+ { PlaybackDeliveryShape.TimeAddressedSegments, 0 } // a time addressed delivery without a positive segment duration has nothing to index
+ };
+
+ [Theory]
+ [MemberData(nameof(NonSegmentDeliveryCases))]
+ public async Task HandleAsync_WhenTheDeliveryIsNotAddressedAsTimeAddressedSegments_ShouldReturnPlaybackDeliveryChangedError(PlaybackDeliveryShape shape, int segmentDurationSeconds)
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ Guid trackId = Guid.Parse(query.TrackId!);
+ PlaybackDeliveryHandleDto delivery = CreateDelivery(query, shape: shape, segmentDurationSeconds: segmentDurationSeconds);
+ _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Playback.PlaybackDeliveryChanged, result.FirstError);
+ await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTheSourcePathIsOutsideEveryAllowedRoot_ShouldReturnTrackFileNotFoundError()
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ Guid trackId = Guid.Parse(query.TrackId!);
+ PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
+ _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
+ _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(false);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
+ await _mockTrackNormalizationService.DidNotReceive().GetOrCreateNormalizedTrackAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenNormalizationFails_ShouldReturnItsErrorWithoutOpeningASegment()
+ {
+ // Arrange
+ GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create();
+ Guid trackId = Guid.Parse(query.TrackId!);
+ PlaybackDeliveryHandleDto delivery = CreateDelivery(query);
+ _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery));
+ _mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, Arg.Any