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()) + .Returns(Errors.Playback.NormalizationFailed); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.NormalizationFailed, result.FirstError); + _mockTrackNormalizationService.DidNotReceive().OpenNormalizedSegment(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheNormalizedTrackHasNoRequestedSegment_ShouldReturnNormalizedTrackSegmentNotFoundError() + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "5"); + Guid trackId = Guid.Parse(query.TrackId!); + PlaybackDeliveryHandleDto delivery = CreateDelivery(query); + NormalizedTrackDto normalizedTrack = _normalizedTrackDtoFixture.Create( + trackId: trackId, + segments: [_normalizedTrackSegmentDtoFixture.Create(index: 0)]); + _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery)); + _mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, Arg.Any()) + .Returns(Result.From(normalizedTrack)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.NormalizedTrackSegmentNotFound, result.FirstError); + _mockTrackNormalizationService.DidNotReceive().OpenNormalizedSegment(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheSegmentCannotBeOpened_ShouldReturnItsError() + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "0"); + Guid trackId = Guid.Parse(query.TrackId!); + PlaybackDeliveryHandleDto delivery = CreateDelivery(query); + NormalizedTrackDto normalizedTrack = _normalizedTrackDtoFixture.Create( + trackId: trackId, + segments: [_normalizedTrackSegmentDtoFixture.Create(index: 0)]); + _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery)); + _mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, Arg.Any()) + .Returns(Result.From(normalizedTrack)); + _mockTrackNormalizationService.OpenNormalizedSegment(normalizedTrack.CacheId, trackId, 0) + .Returns(Errors.Playback.NormalizedTrackCacheEntryNotFound); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.NormalizedTrackCacheEntryNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldReturnTheSegmentDataOfTheProducedTrack() + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "2"); + Guid trackId = Guid.Parse(query.TrackId!); + PlaybackDeliveryHandleDto delivery = CreateDelivery(query); + NormalizedTrackSegmentDto segment = _normalizedTrackSegmentDtoFixture.Create(index: 2, startSeconds: 12.5m, durationSeconds: 6m, length: 4096); + NormalizedTrackDto normalizedTrack = _normalizedTrackDtoFixture.Create( + trackId: trackId, + container: "MP3", + segmentDurationSeconds: 6, + durationInSeconds: 121, + segments: [_normalizedTrackSegmentDtoFixture.Create(index: 0), _normalizedTrackSegmentDtoFixture.Create(index: 1), segment]); + MemoryStream stream = new([1, 2, 3, 4]); + _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery)); + _mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, Arg.Any()) + .Returns(Result.From(normalizedTrack)); + _mockTrackNormalizationService.OpenNormalizedSegment(normalizedTrack.CacheId, trackId, 2) + .Returns(Result.Success(stream)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(stream, result.Value.Content); + Assert.Equal(segment.Length, result.Value.Length); + Assert.Equal(segment.StartSeconds, result.Value.StartSeconds); + Assert.Equal(normalizedTrack.Container, result.Value.Container); + Assert.Equal(normalizedTrack.Segments.Count, result.Value.SegmentCount); + Assert.Equal(normalizedTrack.DurationInSeconds, result.Value.DurationInSeconds); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldNormalizeTheDeliveryRequestAndOpenTheRequestedSegment() + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "3"); + Guid trackId = Guid.Parse(query.TrackId!); + PlaybackDeliveryHandleDto delivery = CreateDelivery(query); + NormalizedTrackSegmentDto segment = _normalizedTrackSegmentDtoFixture.Create(index: 3); + NormalizedTrackDto normalizedTrack = _normalizedTrackDtoFixture.Create( + trackId: trackId, + segmentDurationSeconds: 6, + segments: [_normalizedTrackSegmentDtoFixture.Create(index: 3)]); + _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery)); + _mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(normalizedTrack)); + _mockTrackNormalizationService.OpenNormalizedSegment(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Success(new MemoryStream())); + + // Act + await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + await _mockTrackNormalizationService.Received(1).GetOrCreateNormalizedTrackAsync( + Arg.Is(request => ReferenceEquals(request, delivery.Request)), + Arg.Any()); + _mockTrackNormalizationService.Received(1).OpenNormalizedSegment(normalizedTrack.CacheId, trackId, segment.Index); + } + + [Fact] + public async Task HandleAsync_WhenCancellationIsRequestedWhileNormalizing_ShouldCancelTheOperation() + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(segmentIndex: "0"); + Guid trackId = Guid.Parse(query.TrackId!); + PlaybackDeliveryHandleDto delivery = CreateDelivery(query); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + _mockPlaybackDeliveryHandleService.GetDelivery(query.DeliveryId, _userId, trackId).Returns(Result.From(delivery)); + _mockTrackNormalizationService.GetOrCreateNormalizedTrackAsync(delivery.Request, cancellationTokenSource.Token) + .Returns(Task.FromCanceled>(cancellationTokenSource.Token)); + + // Act & Assert + await Assert.ThrowsAsync(() => _sut.HandleAsync(query, cancellationTokenSource.Token)); + await _mockTrackNormalizationService.Received(1).GetOrCreateNormalizedTrackAsync(delivery.Request, cancellationTokenSource.Token); + } + + /// + /// Creates a delivery that matches the library, album, artist and track named by the provided query. + /// + /// The query whose route identifiers the delivery must describe. + /// The way the audio is delivered. + /// The shape the delivered audio is addressed by. + /// The duration of each segment of the delivered audio, in seconds. + /// The created delivery. + private PlaybackDeliveryHandleDto CreateDelivery( + GetTrackSegmentQuery query, + PlaybackDeliveryMode mode = PlaybackDeliveryMode.Transcode, + PlaybackDeliveryShape shape = PlaybackDeliveryShape.TimeAddressedSegments, + int segmentDurationSeconds = 6) + { + return _playbackDeliveryHandleDtoFixture.Create( + request: _normalizedTrackRequestDtoFixture.Create( + trackId: Guid.Parse(query.TrackId!), + userId: _userId, + sourcePath: Path.Combine(_allowedRoot, "track.flac"), + allowedRoots: [_allowedRoot], + mode: mode, + segmentDurationSeconds: segmentDurationSeconds, + durationInSeconds: 120), + shape: shape, + libraryId: Guid.Parse(query.LibraryId!), + albumId: Guid.Parse(query.AlbumId!), + artistId: Guid.Parse(query.ArtistId!)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidatorTests.cs new file mode 100644 index 00000000..5479bd90 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidatorTests.cs @@ -0,0 +1,218 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackSegmentQueryValidatorTests +{ + private const string VALID_DELIVERY_ID = "0123456789abcdef0123456789abcdef"; + + private readonly GetTrackSegmentQueryFixture _getTrackSegmentQueryFixture = new(); + private readonly GetTrackSegmentQueryValidator _validator = new(); + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: VALID_DELIVERY_ID, segmentIndex: "0"); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveLibraryIdError(string? libraryId) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveArtistIdError(string? artistId) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveAlbumIdError(string? albumId) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-a-track-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveTrackIdError(string? trackId) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(trackId: trackId, includeTrackId: trackId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + public void Validate_WhenDeliveryIdIsEmpty_ShouldHaveDeliveryIdCannotBeEmptyError(string? deliveryId) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: deliveryId, includeDeliveryId: deliveryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Playback.DeliveryIdCannotBeEmpty); + } + + [Theory] + [InlineData("0123456789ABCDEF0123456789ABCDEF")] // uppercase hexadecimal is not the canonical lowercase handle + [InlineData("01234567-89ab-cdef-0123-456789abcdef")] // the D format of a Guid carries dashes + [InlineData("0123456789abcdef0123456789abcde")] // 31 characters, one short of a handle + [InlineData("0123456789abcdef0123456789abcdef0")] // 33 characters, one over a handle + [InlineData("0123456789abcdef0123456789abcdeg")] // the last character is not a hexadecimal digit + public void Validate_WhenDeliveryIdShapeIsInvalid_ShouldHaveDeliveryIdIsInvalidError(string deliveryId) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: deliveryId); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Playback.DeliveryIdIsInvalid); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + public void Validate_WhenSegmentIndexIsEmpty_ShouldHaveSegmentIndexCannotBeEmptyError(string? segmentIndex) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: VALID_DELIVERY_ID, segmentIndex: segmentIndex, includeSegmentIndex: segmentIndex is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Playback.SegmentIndexCannotBeEmpty); + } + + [Theory] + [InlineData("-1")] // a negative index does not address a segment + [InlineData("abc")] // a non-numeric index does not address a segment + [InlineData("1.5")] // a fractional index does not address a segment + [InlineData("2147483648")] // a value above the range of an integer + public void Validate_WhenSegmentIndexIsNotANonNegativeInteger_ShouldHaveSegmentIndexMustBeValidError(string segmentIndex) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: VALID_DELIVERY_ID, segmentIndex: segmentIndex); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Playback.SegmentIndexMustBeValid); + } + + [Theory] + [InlineData("0")] // the first segment of the audio + [InlineData("2147483647")] // the largest index an integer can address + public void Validate_WhenSegmentIndexIsANonNegativeInteger_ShouldNotHaveSegmentIndexMustBeValidError(string segmentIndex) + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create(deliveryId: VALID_DELIVERY_ID, segmentIndex: segmentIndex); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Playback.SegmentIndexMustBeValid); + result.ShouldNotHaveValidationError(Errors.Playback.SegmentIndexCannotBeEmpty); + } + + [Fact] + public void Validate_WhenSeveralFieldsAreInvalid_ShouldReportEachSpecificError() + { + // Arrange + GetTrackSegmentQuery query = _getTrackSegmentQueryFixture.Create( + libraryId: "not-a-library-guid", + artistId: null, + includeArtistId: false, + albumId: Guid.Empty.ToString(), + trackId: "not-a-track-guid", + deliveryId: "0123456789ABCDEF0123456789ABCDEF", + segmentIndex: "-1"); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Playback.DeliveryIdIsInvalid); + result.ShouldHaveValidationError(Errors.Playback.SegmentIndexMustBeValid); + Assert.Equal(6, result.Count); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/TranscodingSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/TranscodingSettingsDtoValidatorTests.cs new file mode 100644 index 00000000..1d50352d --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/TranscodingSettingsDtoValidatorTests.cs @@ -0,0 +1,454 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Common.Validators; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Abstractions; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TranscodingSettingsDtoValidatorTests : IDisposable +{ + private readonly TranscodingSettingsDtoValidator _validator; + private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new(); + private readonly string _sandboxRoot; + private readonly string _mediaRoot; + private readonly string _validCacheDirectory; + private readonly string _pluginsDirectory; + + /// + /// Initializes a new instance of the class. + /// + public TranscodingSettingsDtoValidatorTests() + { + _sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-transcoding-validator-tests-" + Guid.NewGuid().ToString("N")); + _mediaRoot = Path.Combine(_sandboxRoot, "media"); + _validCacheDirectory = Path.Combine(_sandboxRoot, "cache"); + _pluginsDirectory = Path.Combine(_sandboxRoot, "plugins"); + Directory.CreateDirectory(_mediaRoot); + Directory.CreateDirectory(_validCacheDirectory); + Directory.CreateDirectory(_pluginsDirectory); + + // The real path service is used, with the real path strategy of the current platform, so containment follows the file system rules of the host. + IPlatformContext platformContext = Substitute.For(); + IPathStrategy pathStrategy = OperatingSystem.IsWindows() + ? new WindowsPathStrategy(new FileSystem()) + : new UnixPathStrategy(new FileSystem()); + platformContext.PathStrategy.Returns(pathStrategy); + IPlatformContextManager platformContextManager = Substitute.For(); + platformContextManager.GetCurrentContext().Returns(platformContext); + IPathService pathService = new PathService(platformContextManager); + + // An absolute root directory pins the media root that is served by the media route, because Path.Combine returns its second argument when it is rooted. + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: _mediaRoot); + PluginsSettingsDto pluginsSettings = _pluginsSettingsDtoFixture.Create(directory: _pluginsDirectory); + _validator = new TranscodingSettingsDtoValidator(Options.Create(mediaSettings), Options.Create(pluginsSettings), pathService); + } + + [Fact] + public void Validate_WhenSettingsAreValid_ShouldNotHaveAnyValidationError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a missing ffmpeg path + [InlineData("")] // an empty ffmpeg path + [InlineData(" ")] // a whitespace ffmpeg path + public void Validate_WhenFfmpegPathIsEmpty_ShouldHaveFfmpegPathCannotBeEmptyError(string? ffmpegPath) + { + // Arrange + TranscodingSettingsDto model = CreateSettings(ffmpegPath: ffmpegPath, includeFfmpegPath: ffmpegPath is not null); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingFfmpegPathCannotBeEmpty.Description); + } + + [Theory] + [InlineData(0)] // a job count of zero disables normalization + [InlineData(-1)] // a negative job count disables normalization + public void Validate_WhenMaxConcurrentJobsIsNotPositive_ShouldHaveMaxConcurrentJobsMustBePositiveError(int maxConcurrentJobs) + { + // Arrange + TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: maxConcurrentJobs, maxConcurrentJobsPerUser: 1); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive.Description); + } + + [Fact] + public void Validate_WhenMaxConcurrentJobsIsTooLarge_ShouldHaveMaxConcurrentJobsIsTooLargeError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 65, maxConcurrentJobsPerUser: 1); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge.Description); + } + + [Fact] + public void Validate_WhenMaxConcurrentJobsIsTheMaximum_ShouldNotHaveMaxConcurrentJobsErrors() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 64, maxConcurrentJobsPerUser: 64); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive.Description); + } + + [Theory] + [InlineData(0)] // a per-user job count of zero never admits a normalization + [InlineData(-1)] // a negative per-user job count never admits a normalization + public void Validate_WhenMaxConcurrentJobsPerUserIsNotPositive_ShouldHaveMaxConcurrentJobsPerUserMustBePositiveError(int maxConcurrentJobsPerUser) + { + // Arrange + TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 8, maxConcurrentJobsPerUser: maxConcurrentJobsPerUser); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserMustBePositive.Description); + } + + [Fact] + public void Validate_WhenMaxConcurrentJobsPerUserIsTooLarge_ShouldHaveMaxConcurrentJobsPerUserIsTooLargeError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 64, maxConcurrentJobsPerUser: 65); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge.Description); + } + + [Fact] + public void Validate_WhenMaxConcurrentJobsPerUserExceedsTheGlobalLimit_ShouldHaveMaxConcurrentJobsPerUserExceedsGlobalError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 8, maxConcurrentJobsPerUser: 16); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserExceedsGlobal.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge.Description); + } + + [Theory] + [InlineData(0)] // a cache with no capacity cannot hold a normalized track + [InlineData(-1)] // a negative cache size is not a capacity + public void Validate_WhenMaxCacheBytesIsNotPositive_ShouldHaveMaxCacheBytesMustBePositiveError(long maxCacheBytes) + { + // Arrange + TranscodingSettingsDto model = CreateSettings(maxCacheBytes: maxCacheBytes); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxCacheBytesMustBePositive.Description); + } + + [Theory] + [InlineData(0)] // a job timeout of zero stops every job immediately + [InlineData(-1)] // a negative job timeout stops every job immediately + public void Validate_WhenJobTimeoutSecondsIsNotPositive_ShouldHaveJobTimeoutMustBePositiveError(int jobTimeoutSeconds) + { + // Arrange + TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: jobTimeoutSeconds); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutMustBePositive.Description); + } + + [Fact] + public void Validate_WhenJobTimeoutSecondsIsTooLong_ShouldHaveJobTimeoutIsTooLongError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: 86_401); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutIsTooLong.Description); + } + + [Fact] + public void Validate_WhenJobTimeoutSecondsIsTheMaximum_ShouldNotHaveJobTimeoutErrors() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: 86_400); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutIsTooLong.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutMustBePositive.Description); + } + + [Theory] + [InlineData(0)] // an eviction grace of zero protects nothing + [InlineData(-1)] // a negative eviction grace protects nothing + public void Validate_WhenEvictionGraceSecondsIsNotPositive_ShouldHaveEvictionGraceSecondsMustBePositiveError(int evictionGraceSeconds) + { + // Arrange + TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: evictionGraceSeconds); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive.Description); + } + + [Fact] + public void Validate_WhenEvictionGraceSecondsIsTooLong_ShouldHaveEvictionGraceSecondsIsTooLongError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: 86_401); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong.Description); + } + + [Fact] + public void Validate_WhenEvictionGraceSecondsIsTheMaximum_ShouldNotHaveEvictionGraceSecondsErrors() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: 86_400); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive.Description); + } + + [Fact] + public void Validate_WhenCacheDirectoryIsMalformed_ShouldHaveCacheDirectoryIsInvalidError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: "bad\0path"); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInvalid.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description); + } + + [Fact] + public void Validate_WhenCacheDirectoryIsInsideTheMediaRoot_ShouldHaveCacheDirectoryIsInsideMediaRootError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.Combine(_mediaRoot, "cache")); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description); + } + + [Fact] + public void Validate_WhenCacheDirectoryContainsTheMediaRoot_ShouldHaveCacheDirectoryContainsMediaRootError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: _sandboxRoot); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description); + Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description); + } + + [Fact] + public void Validate_WhenCacheDirectoryIsAFileSystemRoot_ShouldHaveCacheDirectoryIsUnsafeLocationError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.GetPathRoot(_mediaRoot)!); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description); + } + + [Fact] + public void Validate_WhenCacheDirectoryIsTheApplicationBaseDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: AppContext.BaseDirectory); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description); + } + + [Fact] + public void Validate_WhenCacheDirectoryIsTheLogsDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.Combine(AppContext.BaseDirectory, "logs")); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description); + } + + [Fact] + public void Validate_WhenCacheDirectoryIsThePluginsDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: _pluginsDirectory); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description); + } + + [Fact] + public void Validate_WhenCacheDirectoryIsAValidExternalDirectory_ShouldNotHaveCacheDirectoryErrors() + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: _validCacheDirectory); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // no configured directory, so the default temporary directory is used + [InlineData(" ")] // a whitespace directory, so the default temporary directory is used + public void Validate_WhenCacheDirectoryIsNotConfigured_ShouldOnlyValidateTheDefaultDirectory(string? cacheDirectory) + { + // Arrange + TranscodingSettingsDto model = CreateSettings(cacheDirectory: cacheDirectory, includeCacheDirectory: cacheDirectory is not null); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Empty(result); + } + + /// + /// Releases the temporary directories 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. + } + } + + /// + /// Creates settings that are valid unless an argument overrides a single rule under test. + /// + /// The file name or path of the ffmpeg binary. + /// The maximum number of normalization jobs that may run at the same time. + /// The maximum number of normalization jobs a single user may have running at the same time. + /// The maximum total size of the normalized audio cache, in bytes. + /// The maximum duration of a single normalization job, in seconds. + /// The period during which a cache entry is protected from eviction, in seconds. + /// The directory where normalized audio is cached. + /// Whether the cache directory should be included, or forced to . + /// Whether the ffmpeg path should be included, or forced to . + /// The created settings. + private TranscodingSettingsDto CreateSettings( + string? ffmpegPath = "ffmpeg", + int? maxConcurrentJobs = 8, + int? maxConcurrentJobsPerUser = 4, + long? maxCacheBytes = 2L * 1024 * 1024 * 1024, + int? jobTimeoutSeconds = 900, + int? evictionGraceSeconds = 120, + string? cacheDirectory = null, + bool includeCacheDirectory = true, + bool includeFfmpegPath = true) + { + return _transcodingSettingsDtoFixture.Create( + ffmpegPath: ffmpegPath, + maxConcurrentJobs: maxConcurrentJobs, + maxConcurrentJobsPerUser: maxConcurrentJobsPerUser, + maxCacheBytes: maxCacheBytes, + jobTimeoutSeconds: jobTimeoutSeconds, + evictionGraceSeconds: evictionGraceSeconds, + cacheDirectory: cacheDirectory ?? _validCacheDirectory, + includeCacheDirectory: includeCacheDirectory, + includeFfmpegPath: includeFfmpegPath); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleServiceTests.cs new file mode 100644 index 00000000..8363c47d --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleServiceTests.cs @@ -0,0 +1,444 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaybackDeliveryHandleServiceTests +{ + private readonly PlaybackDeliveryHandleService _sut; + private readonly PlaybackDeliveryHandleDtoFixture _playbackDeliveryHandleDtoFixture = new(); + private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public PlaybackDeliveryHandleServiceTests() + { + _sut = new PlaybackDeliveryHandleService(); + } + + [Fact] + public void IssueDeliveryId_WhenCalled_ShouldReturnA32CharacterLowercaseHexadecimalHandle() + { + // Arrange + PlaybackDeliveryHandleDto delivery = CreateBaseDelivery(); + + // Act + string handle = _sut.IssueDeliveryId(delivery); + + // Assert + Assert.Equal(32, handle.Length); + Assert.Matches("^[0-9a-f]{32}$", handle); + Assert.True(PlaybackDeliveryId.IsValid(handle)); + } + + [Fact] + public void IssueDeliveryId_WhenDeliveriesDiffer_ShouldReturnDistinctHandles() + { + // Arrange + PlaybackDeliveryHandleDto firstDelivery = CreateBaseDelivery(); + PlaybackDeliveryHandleDto secondDelivery = CreateBaseDelivery(); + + // Act + string firstHandle = _sut.IssueDeliveryId(firstDelivery); + string secondHandle = _sut.IssueDeliveryId(secondDelivery); + + // Assert + Assert.NotEqual(firstHandle, secondHandle); + } + + [Fact] + public void IssueDeliveryId_WhenTheSameDeliveryIsIssuedAgain_ShouldReturnTheSameHandle() + { + // Arrange + PlaybackDeliveryHandleDto delivery = CreateBaseDelivery(); + + // Act + string firstHandle = _sut.IssueDeliveryId(delivery); + string secondHandle = _sut.IssueDeliveryId(delivery); + + // Assert + Assert.Equal(firstHandle, secondHandle); + } + + [Fact] + public void IssueDeliveryId_WhenAnEqualDeliveryIsIssuedAgainAtThePerUserLimit_ShouldReuseTheExistingHandle() + { + // Arrange + PlaybackDeliveryHandleDto delivery = CreateBaseDelivery(); + string handle = _sut.IssueDeliveryId(delivery); + // Fill the rest of the per user bound with distinct deliveries, so the next issue would evict this one if it did not reuse it. + for (int index = 0; index < 63; index++) + _sut.IssueDeliveryId(CreateDeliveryFor(delivery.Request.UserId)); + PlaybackDeliveryHandleDto equalDelivery = delivery with { Request = delivery.Request with { AllowedRoots = [.. delivery.Request.AllowedRoots] } }; + + // Act + string reusedHandle = _sut.IssueDeliveryId(equalDelivery); + + // Assert + Assert.Equal(handle, reusedHandle); + Result result = _sut.GetDelivery(handle, delivery.Request.UserId, delivery.Request.TrackId); + Assert.False(result.IsFailure); + Assert.Same(delivery, result.Value); + } + + public static TheoryData SignatureVariations => new() + { + DeliveryVariation.UserId, + DeliveryVariation.TrackId, + DeliveryVariation.LibraryId, + DeliveryVariation.AlbumId, + DeliveryVariation.ArtistId, + DeliveryVariation.Mode, + DeliveryVariation.Shape, + DeliveryVariation.SourceContainer, + DeliveryVariation.SourceContainerNull, + DeliveryVariation.Container, + DeliveryVariation.Codec, + DeliveryVariation.SegmentDurationSeconds, + DeliveryVariation.DurationInSeconds, + DeliveryVariation.Bitrate, + DeliveryVariation.BitrateNull, + DeliveryVariation.SampleRate, + DeliveryVariation.Channels, + DeliveryVariation.BitDepth, + DeliveryVariation.BitDepthNull, + DeliveryVariation.Quality, + DeliveryVariation.SourcePath, + DeliveryVariation.SourceLength, + DeliveryVariation.SourceLastModifiedUtc, + DeliveryVariation.AllowedRoots + }; + + [Theory] + [MemberData(nameof(SignatureVariations))] + public void IssueDeliveryId_WhenOneSignatureInputChanges_ShouldReturnADifferentHandle(DeliveryVariation variation) + { + // Arrange + PlaybackDeliveryHandleDto delivery = CreateBaseDelivery(); + string handle = _sut.IssueDeliveryId(delivery); + PlaybackDeliveryHandleDto variedDelivery = Vary(delivery, variation); + + // Act + string variedHandle = _sut.IssueDeliveryId(variedDelivery); + + // Assert + Assert.NotEqual(handle, variedHandle); + } + + [Theory] + [InlineData(null)] // an absent handle cannot address a delivery + [InlineData("")] // an empty handle cannot address a delivery + [InlineData(" ")] // a whitespace handle cannot address a delivery + [InlineData("0123456789abcdef0123456789abcdef")] // a well formed handle that was never issued + public void GetDelivery_WhenTheHandleIsMissingOrUnknown_ShouldReturnPlaybackDeliveryNotFoundError(string? deliveryId) + { + // Act + Result result = _sut.GetDelivery(deliveryId, Guid.NewGuid(), Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError); + } + + [Fact] + public void GetDelivery_WhenTheHandleWasIssuedToAnotherUser_ShouldReturnPlaybackDeliveryNotFoundError() + { + // Arrange + PlaybackDeliveryHandleDto delivery = CreateBaseDelivery(); + string handle = _sut.IssueDeliveryId(delivery); + + // Act + Result result = _sut.GetDelivery(handle, Guid.NewGuid(), delivery.Request.TrackId); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError); + } + + [Fact] + public void GetDelivery_WhenTheHandleDescribesAnotherTrack_ShouldReturnPlaybackDeliveryNotFoundError() + { + // Arrange + PlaybackDeliveryHandleDto delivery = CreateBaseDelivery(); + string handle = _sut.IssueDeliveryId(delivery); + + // Act + Result result = _sut.GetDelivery(handle, delivery.Request.UserId, Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError); + } + + [Fact] + public void GetDelivery_WhenTheHandleWasIssuedToTheUserForTheTrack_ShouldReturnTheIssuedDelivery() + { + // Arrange + PlaybackDeliveryHandleDto delivery = CreateBaseDelivery(); + string handle = _sut.IssueDeliveryId(delivery); + + // Act + Result result = _sut.GetDelivery(handle, delivery.Request.UserId, delivery.Request.TrackId); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(delivery, result.Value); + Assert.Equal(delivery.Request.TrackId, result.Value.Request.TrackId); + Assert.Equal(delivery.Request.UserId, result.Value.Request.UserId); + Assert.Equal(delivery.Shape, result.Value.Shape); + Assert.Equal(delivery.LibraryId, result.Value.LibraryId); + Assert.Equal(delivery.AlbumId, result.Value.AlbumId); + Assert.Equal(delivery.ArtistId, result.Value.ArtistId); + } + + [Fact] + public void IssueDeliveryId_WhenAUserExceedsThePerUserLimit_ShouldEvictOnlyTheOldestHandleOfThatUser() + { + // Arrange + Guid userId = Guid.NewGuid(); + Guid otherUserId = Guid.NewGuid(); + PlaybackDeliveryHandleDto otherUserDelivery = CreateDeliveryFor(otherUserId); + string otherUserHandle = _sut.IssueDeliveryId(otherUserDelivery); + List<(string Handle, Guid TrackId)> handles = []; + for (int index = 0; index < 64; index++) + { + PlaybackDeliveryHandleDto delivery = CreateDeliveryFor(userId); + handles.Add((_sut.IssueDeliveryId(delivery), delivery.Request.TrackId)); + } + + // Act + PlaybackDeliveryHandleDto newestDelivery = CreateDeliveryFor(userId); + string newestHandle = _sut.IssueDeliveryId(newestDelivery); + + // Assert + Assert.True(_sut.GetDelivery(handles[0].Handle, userId, handles[0].TrackId).IsFailure); + for (int index = 1; index < handles.Count; index++) + Assert.True(_sut.GetDelivery(handles[index].Handle, userId, handles[index].TrackId).IsSuccess); + Assert.True(_sut.GetDelivery(newestHandle, userId, newestDelivery.Request.TrackId).IsSuccess); + Assert.True(_sut.GetDelivery(otherUserHandle, otherUserId, otherUserDelivery.Request.TrackId).IsSuccess); + } + + [Fact] + public void IssueDeliveryId_WhenTheGlobalLimitIsExceeded_ShouldEvictOnlyTheOldestHandle() + { + // Arrange + PlaybackDeliveryHandleService sut = new(); + Guid[] users = [.. Enumerable.Range(0, 400).Select(_ => Guid.NewGuid())]; + string? oldestHandle = null; + Guid oldestUserId = Guid.Empty; + Guid oldestTrackId = Guid.Empty; + string? secondOldestHandle = null; + Guid secondOldestUserId = Guid.Empty; + Guid secondOldestTrackId = Guid.Empty; + string? newestHandle = null; + Guid newestUserId = Guid.Empty; + Guid newestTrackId = Guid.Empty; + for (int index = 0; index < 20_000; index++) + { + // The per user bound is 64, so each user is given exactly 64 deliveries and never triggers a per user eviction. + Guid userId = users[index / 64]; + PlaybackDeliveryHandleDto delivery = CreateDeliveryFor(userId); + string handle = sut.IssueDeliveryId(delivery); + if (index == 0) + { + oldestHandle = handle; + oldestUserId = userId; + oldestTrackId = delivery.Request.TrackId; + } + else if (index == 1) + { + secondOldestHandle = handle; + secondOldestUserId = userId; + secondOldestTrackId = delivery.Request.TrackId; + } + if (index == 19_999) + { + newestHandle = handle; + newestUserId = userId; + newestTrackId = delivery.Request.TrackId; + } + } + PlaybackDeliveryHandleDto extraDelivery = CreateDeliveryFor(Guid.NewGuid()); + + // Act + string extraHandle = sut.IssueDeliveryId(extraDelivery); + + // Assert + Assert.True(sut.GetDelivery(oldestHandle, oldestUserId, oldestTrackId).IsFailure); + Assert.True(sut.GetDelivery(secondOldestHandle, secondOldestUserId, secondOldestTrackId).IsSuccess); + Assert.True(sut.GetDelivery(newestHandle, newestUserId, newestTrackId).IsSuccess); + Assert.True(sut.GetDelivery(extraHandle, extraDelivery.Request.UserId, extraDelivery.Request.TrackId).IsSuccess); + } + + [Fact] + public async Task IssueDeliveryId_WhenTheSameDeliveryIsIssuedConcurrently_ShouldReturnOneIdenticalHandle() + { + // Arrange + PlaybackDeliveryHandleDto delivery = CreateBaseDelivery(); + + // Act + string[] handles = await Task.WhenAll(Enumerable.Range(0, 32).Select(_ => Task.Run(() => _sut.IssueDeliveryId(delivery)))); + + // Assert + Assert.Single(handles.Distinct()); + Assert.True(_sut.GetDelivery(handles[0], delivery.Request.UserId, delivery.Request.TrackId).IsSuccess); + } + + [Fact] + public async Task IssueDeliveryId_WhenDifferentDeliveriesAreIssuedConcurrently_ShouldMakeEveryHandleResolvable() + { + // Arrange + PlaybackDeliveryHandleDto[] deliveries = [.. Enumerable.Range(0, 32).Select(_ => CreateDeliveryFor(Guid.NewGuid()))]; + + // Act + string[] handles = await Task.WhenAll(deliveries.Select(delivery => Task.Run(() => _sut.IssueDeliveryId(delivery)))); + + // Assert + Assert.Equal(deliveries.Length, handles.Distinct().Count()); + for (int index = 0; index < deliveries.Length; index++) + Assert.True(_sut.GetDelivery(handles[index], deliveries[index].Request.UserId, deliveries[index].Request.TrackId).IsSuccess); + } + + /// + /// The single input of the delivery signature that a variation changes. + /// + public enum DeliveryVariation + { + UserId, + TrackId, + LibraryId, + AlbumId, + ArtistId, + Mode, + Shape, + SourceContainer, + SourceContainerNull, + Container, + Codec, + SegmentDurationSeconds, + DurationInSeconds, + Bitrate, + BitrateNull, + SampleRate, + Channels, + BitDepth, + BitDepthNull, + Quality, + SourcePath, + SourceLength, + SourceLastModifiedUtc, + AllowedRoots + } + + /// + /// Creates a delivery with every signature input explicitly pinned. + /// + /// The created delivery. + private PlaybackDeliveryHandleDto CreateBaseDelivery() + { + return _playbackDeliveryHandleDtoFixture.Create( + request: CreateRequest(userId: Guid.NewGuid(), trackId: Guid.NewGuid()), + shape: PlaybackDeliveryShape.TimeAddressedSegments, + libraryId: Guid.Parse("11111111-1111-1111-1111-111111111111"), + albumId: Guid.Parse("22222222-2222-2222-2222-222222222222"), + artistId: Guid.Parse("33333333-3333-3333-3333-333333333333")); + } + + /// + /// Creates a delivery for a user whose track is unique to the delivery. + /// + /// The Id of the user the delivery is issued to. + /// The created delivery. + private PlaybackDeliveryHandleDto CreateDeliveryFor(Guid userId) + { + return _playbackDeliveryHandleDtoFixture.Create( + request: CreateRequest(userId: userId, trackId: Guid.NewGuid()), + shape: PlaybackDeliveryShape.TimeAddressedSegments, + libraryId: Guid.NewGuid(), + albumId: Guid.NewGuid(), + artistId: Guid.NewGuid()); + } + + /// + /// Changes exactly one input of the delivery signature. + /// + /// The delivery to vary. + /// The input to change. + /// The varied delivery. + private static PlaybackDeliveryHandleDto Vary(PlaybackDeliveryHandleDto delivery, DeliveryVariation variation) + { + return variation switch + { + DeliveryVariation.UserId => delivery with { Request = delivery.Request with { UserId = Guid.NewGuid() } }, + DeliveryVariation.TrackId => delivery with { Request = delivery.Request with { TrackId = Guid.NewGuid() } }, + DeliveryVariation.LibraryId => delivery with { LibraryId = Guid.NewGuid() }, + DeliveryVariation.AlbumId => delivery with { AlbumId = Guid.NewGuid() }, + DeliveryVariation.ArtistId => delivery with { ArtistId = Guid.NewGuid() }, + DeliveryVariation.Mode => delivery with { Request = delivery.Request with { Mode = PlaybackDeliveryMode.Remux } }, + DeliveryVariation.Shape => delivery with { Shape = PlaybackDeliveryShape.ByteRangeSeekable }, + DeliveryVariation.SourceContainer => delivery with { Request = delivery.Request with { SourceContainer = "WAV" } }, + DeliveryVariation.SourceContainerNull => delivery with { Request = delivery.Request with { SourceContainer = null } }, + DeliveryVariation.Container => delivery with { Request = delivery.Request with { Container = "AAC" } }, + DeliveryVariation.Codec => delivery with { Request = delivery.Request with { Codec = "AAC" } }, + DeliveryVariation.SegmentDurationSeconds => delivery with { Request = delivery.Request with { SegmentDurationSeconds = 10 } }, + DeliveryVariation.DurationInSeconds => delivery with { Request = delivery.Request with { DurationInSeconds = 300 } }, + DeliveryVariation.Bitrate => delivery with { Request = delivery.Request with { Bitrate = 320 } }, + DeliveryVariation.BitrateNull => delivery with { Request = delivery.Request with { Bitrate = null } }, + DeliveryVariation.SampleRate => delivery with { Request = delivery.Request with { SampleRate = 96000 } }, + DeliveryVariation.Channels => delivery with { Request = delivery.Request with { Channels = 6 } }, + DeliveryVariation.BitDepth => delivery with { Request = delivery.Request with { BitDepth = 16 } }, + DeliveryVariation.BitDepthNull => delivery with { Request = delivery.Request with { BitDepth = null } }, + DeliveryVariation.Quality => delivery with { Request = delivery.Request with { Quality = PlaybackStreamingQuality.Low } }, + DeliveryVariation.SourcePath => delivery with { Request = delivery.Request with { SourcePath = "/music/incoming/other.flac" } }, + DeliveryVariation.SourceLength => delivery with { Request = delivery.Request with { SourceLength = 999 } }, + DeliveryVariation.SourceLastModifiedUtc => delivery with { Request = delivery.Request with { SourceLastModifiedUtc = new DateTime(2026, 2, 3, 4, 5, 6, DateTimeKind.Utc) } }, + DeliveryVariation.AllowedRoots => delivery with { Request = delivery.Request with { AllowedRoots = [.. delivery.Request.AllowedRoots.Take(1), "/music/other"] } }, + _ => throw new ArgumentOutOfRangeException(nameof(variation), variation, "Unsupported delivery variation.") + }; + } + + /// + /// Creates a normalization request with every signature input explicitly pinned. + /// + /// The Id of the user the delivery is issued to. + /// The Id of the track the delivery describes. + /// The created request. + private NormalizedTrackRequestDto CreateRequest(Guid userId, Guid trackId) + { + return _normalizedTrackRequestDtoFixture.Create( + trackId: trackId, + userId: userId, + sourcePath: "/music/library/track.flac", + allowedRoots: ["/music/library", "/music/incoming"], + sourceContainer: "FLAC", + mode: PlaybackDeliveryMode.Transcode, + container: "MP3", + codec: "MP3", + segmentDurationSeconds: 6, + durationInSeconds: 245, + bitrate: 900, + sampleRate: 48000, + channels: 2, + bitDepth: 24, + quality: PlaybackStreamingQuality.High, + sourceLength: 123456, + sourceLastModifiedUtc: new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc)); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationServiceTests.cs new file mode 100644 index 00000000..953045ee --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationServiceTests.cs @@ -0,0 +1,207 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Fixtures.Common.DTO.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.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Abstractions; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TrackNormalizationServiceTests : IDisposable +{ + private readonly TrackNormalizationService _sut; + private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new(); + private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new(); + private readonly string _sandboxRoot; + private readonly string _cacheDirectory; + private readonly string _sourceRoot; + private readonly string _sourcePath; + private readonly long _sourceLength; + private readonly DateTime _sourceLastModifiedUtc; + + /// + /// Initializes a new instance of the class. + /// + public TrackNormalizationServiceTests() + { + _sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-track-normalization-tests-" + Guid.NewGuid().ToString("N")); + _cacheDirectory = Path.Combine(_sandboxRoot, "cache"); + _sourceRoot = Path.Combine(_sandboxRoot, "source"); + _sourcePath = Path.Combine(_sourceRoot, "track.flac"); + Directory.CreateDirectory(_cacheDirectory); + Directory.CreateDirectory(_sourceRoot); + File.WriteAllBytes(_sourcePath, new byte[512]); + _sourceLength = new FileInfo(_sourcePath).Length; + _sourceLastModifiedUtc = File.GetLastWriteTimeUtc(_sourcePath); + + // The real path service is used, with the real path strategy of the current platform, so containment follows the file system rules of the host. + IPlatformContext platformContext = Substitute.For(); + IPathStrategy pathStrategy = OperatingSystem.IsWindows() + ? new WindowsPathStrategy(new FileSystem()) + : new UnixPathStrategy(new FileSystem()); + platformContext.PathStrategy.Returns(pathStrategy); + IPlatformContextManager platformContextManager = Substitute.For(); + platformContextManager.GetCurrentContext().Returns(platformContext); + IPathService pathService = new PathService(platformContextManager); + + TranscodingSettingsDto settings = _transcodingSettingsDtoFixture.Create( + ffmpegPath: Path.Combine(_sandboxRoot, "missing-ffmpeg"), + maxConcurrentJobs: 2, + maxConcurrentJobsPerUser: 1, + maxCacheBytes: 100 * 1024 * 1024, + jobTimeoutSeconds: 60, + evictionGraceSeconds: 10, + cacheDirectory: _cacheDirectory); + TranscodingToolchainStatus toolchainStatus = new(); + _sut = new TrackNormalizationService(Options.Create(settings), NullLogger.Instance, pathService, toolchainStatus); + } + + [Fact] + public async Task GetOrCreateNormalizedTrackAsync_WhenTheUserIdIsEmpty_ShouldReturnNormalizationFailedError() + { + // Arrange + NormalizedTrackRequestDto request = CreateRequest(userId: Guid.Empty); + + // Act + Result result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.NormalizationFailed, result.FirstError); + } + + [Theory] + [InlineData(true)] // the source file length no longer matches the declared delivery + [InlineData(false)] // the source file modification time no longer matches the declared delivery + public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourceFileChangedSinceTheDeliveryWasDeclared_ShouldReturnPlaybackDeliveryChangedError(bool isLengthChanged) + { + // Arrange + NormalizedTrackRequestDto request = CreateRequest( + sourceLength: isLengthChanged ? _sourceLength + 1 : _sourceLength, + sourceLastModifiedUtc: isLengthChanged ? _sourceLastModifiedUtc : _sourceLastModifiedUtc.AddMinutes(-1)); + + // Act + Result result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.PlaybackDeliveryChanged, result.FirstError); + } + + [Fact(Skip = "Production bug: a missing source file inside an allowed root throws FileNotFoundException from HasReparsePointBelow (File.GetAttributes on the leaf) instead of returning Errors.Music.TrackFileNotFound. The exception escapes GetOrCreateNormalizedTrackAsync, so the contract of the method is violated for a track deleted between the manifest and the first segment request.")] + public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourceFileDoesNotExist_ShouldReturnTrackFileNotFoundError() + { + // Arrange + NormalizedTrackRequestDto request = CreateRequest(sourcePath: Path.Combine(_sourceRoot, "missing.flac")); + + // Act + Result result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError); + } + + [Fact] + public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourcePathIsOutsideEveryAllowedRoot_ShouldReturnTrackFileNotFoundError() + { + // Arrange + NormalizedTrackRequestDto request = CreateRequest(allowedRoots: [Path.Combine(_sandboxRoot, "other")]); + + // Act + Result result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError); + } + + [Fact] + public async Task GetOrCreateNormalizedTrackAsync_WhenTheServiceIsDisposed_ShouldReturnNormalizationUnavailableError() + { + // Arrange + NormalizedTrackRequestDto request = CreateRequest(); + _sut.Dispose(); + + // Act + Result result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playback.NormalizationUnavailable, result.FirstError); + } + + /// + /// Releases the service and the temporary directories of the test. + /// + public void Dispose() + { + _sut.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. + } + } + + /// + /// Creates a normalization request that matches the source file of the test. + /// + /// The Id of the user whose request starts the production. + /// The file system path of the stored audio file of the track. + /// The content locations the source path is allowed to be inside. + /// The length the source file had when the delivery was declared, in bytes. + /// The last modification time the source file had when the delivery was declared. + /// The created request. + private NormalizedTrackRequestDto CreateRequest( + Guid? userId = null, + string? sourcePath = null, + IReadOnlyList? allowedRoots = null, + long? sourceLength = null, + DateTime? sourceLastModifiedUtc = null) + { + return _normalizedTrackRequestDtoFixture.Create( + trackId: Guid.NewGuid(), + userId: userId ?? Guid.NewGuid(), + sourcePath: sourcePath ?? _sourcePath, + allowedRoots: allowedRoots ?? [_sourceRoot], + sourceContainer: "FLAC", + mode: PlaybackDeliveryMode.Transcode, + container: "MP3", + codec: "MP3", + segmentDurationSeconds: 6, + durationInSeconds: 120, + bitrate: 900, + sampleRate: 44100, + channels: 2, + bitDepth: 16, + quality: PlaybackStreamingQuality.Auto, + sourceLength: sourceLength ?? _sourceLength, + sourceLastModifiedUtc: sourceLastModifiedUtc ?? _sourceLastModifiedUtc); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/MusicMimeTypesTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/MusicMimeTypesTests.cs index 20193aac..56e314f3 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/MusicMimeTypesTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/MimeTypes/MusicMimeTypesTests.cs @@ -47,4 +47,64 @@ public class MusicMimeTypesTests // Assert Assert.Equal("application/octet-stream", result); } + + [Theory] + [InlineData("MP3", "audio/mpeg")] // mp3 container + [InlineData("FLAC", "audio/flac")] // flac container + [InlineData("MP4", "audio/mp4")] // mp4 container + [InlineData("M4A", "audio/mp4")] // m4a container + [InlineData("AAC", "audio/aac")] // aac container + [InlineData("OGG", "audio/ogg")] // ogg container + [InlineData("OPUS", "audio/ogg")] // opus container + [InlineData("WAV", "audio/wav")] // wav container + public void GetContainerMimeType_WhenContainerIsMapped_ShouldReturnMappedMimeType(string container, string expectedMimeType) + { + // Act + string result = MusicMimeTypes.GetContainerMimeType(container); + + // Assert + Assert.Equal(expectedMimeType, result); + } + + [Theory] + [InlineData("mp3", "audio/mpeg")] // lowercase mp3 container + [InlineData("Flac", "audio/flac")] // mixed case flac container + [InlineData("mP4", "audio/mp4")] // mixed case mp4 container + [InlineData("opus", "audio/ogg")] // lowercase opus container + public void GetContainerMimeType_WhenContainerDiffersInCase_ShouldReturnMappedMimeType(string container, string expectedMimeType) + { + // Act + string result = MusicMimeTypes.GetContainerMimeType(container); + + // Assert + Assert.Equal(expectedMimeType, result); + } + + [Theory] + [InlineData(" MP3 ", "audio/mpeg")] // leading and trailing whitespace around mp3 + [InlineData("\tOGG", "audio/ogg")] // leading tab around ogg + [InlineData("WAV\n", "audio/wav")] // trailing newline around wav + public void GetContainerMimeType_WhenContainerHasSurroundingWhitespace_ShouldReturnMappedMimeType(string container, string expectedMimeType) + { + // Act + string result = MusicMimeTypes.GetContainerMimeType(container); + + // Assert + Assert.Equal(expectedMimeType, result); + } + + [Theory] + [InlineData(null)] // an absent container has no mime mapping + [InlineData("")] // an empty container has no mime mapping + [InlineData(" ")] // a whitespace only container has no mime mapping + [InlineData("WMA")] // a known file format that is not a mapped delivery container + [InlineData("not-a-container")] // an unknown container has no mime mapping + public void GetContainerMimeType_WhenContainerIsUnknown_ShouldReturnOpaqueBinaryMimeType(string? container) + { + // Act + string result = MusicMimeTypes.GetContainerMimeType(container); + + // Assert + Assert.Equal("application/octet-stream", result); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs index 9d0c009e..acc8adc6 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -206,6 +206,25 @@ public class BaseEndpointTests Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); } + [Fact] + public void Problem_WhenCalledWithResourceUnavailableError_ShouldReturnServiceUnavailableStatusCode() + { + // Arrange + List errors = [Error.ResourceUnavailable("ErrorCode", "ErrorDescription")]; + + // Act + IResult result = _sut.TestProblem(errors); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status503ServiceUnavailable, problemResult.StatusCode); + Assert.Equal(StatusCodes.Status503ServiceUnavailable, problemResult.ProblemDetails.Status); + Assert.Equal("ErrorCode", problemResult.ProblemDetails.Title); + Assert.Equal("ErrorDescription", problemResult.ProblemDetails.Detail); + Assert.NotNull(problemResult.ProblemDetails.Instance); + Assert.Contains("traceId", problemResult.ProblemDetails.Extensions.Keys); + } + [Fact] public void Problem_WhenCalledWithMixedErrorsStartingWithValidation_ShouldReturnTheValidationStatusCode() { diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/DisposingStreamResultTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/DisposingStreamResultTests.cs new file mode 100644 index 00000000..74efe035 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/DisposingStreamResultTests.cs @@ -0,0 +1,222 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DisposingStreamResultTests +{ + /// + /// Initializes a new instance of the class. + /// + public DisposingStreamResultTests() + { + } + + [Fact] + public async Task ExecuteAsync_WhenContentIsProvided_ShouldWriteEveryByteToResponseBody() + { + // Arrange + byte[] expectedBytes = CreateBytes(512); + using MemoryStream content = new(expectedBytes); + DisposingStreamResult sut = new(content, "audio/mpeg", expectedBytes.Length); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await sut.ExecuteAsync(httpContext); + + // Assert + httpContext.Response.Body.Position = 0; + using MemoryStream writtenBody = new(); + await httpContext.Response.Body.CopyToAsync(writtenBody); + Assert.Equal(expectedBytes, writtenBody.ToArray()); + } + + [Fact] + public async Task ExecuteAsync_WhenContentLengthIsProvided_ShouldSetContentTypeAndContentLength() + { + // Arrange + byte[] contentBytes = CreateBytes(128); + using MemoryStream content = new(contentBytes); + DisposingStreamResult sut = new(content, "audio/mp4", contentBytes.Length); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await sut.ExecuteAsync(httpContext); + + // Assert + Assert.Equal("audio/mp4", httpContext.Response.ContentType); + Assert.Equal(contentBytes.Length, httpContext.Response.ContentLength); + } + + [Fact] + public async Task ExecuteAsync_WhenContentLengthIsNull_ShouldLeaveResponseContentLengthUnset() + { + // Arrange + byte[] contentBytes = CreateBytes(64); + using MemoryStream content = new(contentBytes); + DisposingStreamResult sut = new(content, "audio/ogg", null); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await sut.ExecuteAsync(httpContext); + + // Assert + Assert.Equal("audio/ogg", httpContext.Response.ContentType); + Assert.Null(httpContext.Response.ContentLength); + } + + [Fact] + public async Task ExecuteAsync_WhenWriteCompletes_ShouldDisposeTheContentStream() + { + // Arrange + byte[] contentBytes = CreateBytes(32); + DisposalTrackingStream content = new(contentBytes); + DisposingStreamResult sut = new(content, "audio/mpeg", contentBytes.Length); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await sut.ExecuteAsync(httpContext); + + // Assert + Assert.True(content.IsDisposed); + } + + [Fact] + public async Task ExecuteAsync_WhenCopyToAsyncThrows_ShouldDisposeTheContentStreamAndPropagateTheException() + { + // Arrange + ThrowingCopyStream content = new(CreateBytes(32)); + DisposingStreamResult sut = new(content, "audio/mpeg", null); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + Task operationTask = sut.ExecuteAsync(httpContext); + + // Assert + await Assert.ThrowsAsync(() => operationTask); + Assert.True(content.IsDisposed); + } + + [Fact] + public async Task ExecuteAsync_WhenStreamWasPartiallyRead_ShouldCopyFromTheCurrentPosition() + { + // Arrange + byte[] contentBytes = CreateBytes(100); + using MemoryStream content = new(contentBytes); + content.Position = 37; + DisposingStreamResult sut = new(content, "audio/wav", contentBytes.Length - 37); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await sut.ExecuteAsync(httpContext); + + // Assert + httpContext.Response.Body.Position = 0; + using MemoryStream writtenBody = new(); + await httpContext.Response.Body.CopyToAsync(writtenBody); + Assert.Equal(contentBytes[37..], writtenBody.ToArray()); + } + + /// + /// Creates a with a writable response body. + /// + /// The configured HTTP context. + private static DefaultHttpContext CreateHttpContext() + { + DefaultHttpContext httpContext = new(); + httpContext.Response.Body = new MemoryStream(); + return httpContext; + } + + /// + /// Creates a deterministic byte array that stands in for streamed content. + /// + /// 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))]; + } + + /// + /// A memory stream that records whether it was disposed. + /// + private sealed class DisposalTrackingStream : MemoryStream + { + /// + /// Gets whether the stream was disposed. + /// + public bool IsDisposed { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The bytes of the stream. + public DisposalTrackingStream(byte[] content) : base(content) + { + } + + /// + /// Releases the resources of the stream and records the disposal. + /// + /// Whether managed resources are being disposed. + protected override void Dispose(bool disposing) + { + IsDisposed = true; + base.Dispose(disposing); + } + } + + /// + /// A memory stream whose copy operation always fails. + /// + private sealed class ThrowingCopyStream : MemoryStream + { + /// + /// Gets whether the stream was disposed. + /// + public bool IsDisposed { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The bytes of the stream. + public ThrowingCopyStream(byte[] content) : base(content) + { + } + + /// + /// Simulates a failed write to the destination stream. + /// + /// The destination stream. + /// The size of the buffer used by the copy. + /// Cancellation token that can be used to stop the execution. + /// This method never returns, it always throws. + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) + { + throw new IOException("The destination stream rejected the content."); + } + + /// + /// Releases the resources of the stream and records the disposal. + /// + /// Whether managed resources are being disposed. + protected override void Dispose(bool disposing) + { + IsDisposed = true; + base.Dispose(disposing); + } + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs new file mode 100644 index 00000000..0558bb62 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs @@ -0,0 +1,197 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackManifestEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetPlaybackManifestEndpoint _sut; + private readonly PlaybackManifestResponseFixture _playbackManifestResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackManifestEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTheManifest() + { + // Arrange + PlaybackManifestResponse expectedResponse = _playbackManifestResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playbackManifestResponseFixture.Create())); + SetRouteValues(); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + Error expectedError = DomainErrors.Music.TrackNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.ProblemDetails.Status); + Assert.Equal(expectedError.Code, problemResult.ProblemDetails.Title); + Assert.Equal(expectedError.Description, problemResult.ProblemDetails.Detail); + Assert.Contains("traceId", problemResult.ProblemDetails.Extensions.Keys); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteValuesAndTheStreamPathsToTheHandler() + { + // Arrange + string libraryId = "11111111-1111-1111-1111-111111111111"; + string artistId = "22222222-2222-2222-2222-222222222222"; + string albumId = "33333333-3333-3333-3333-333333333333"; + string trackId = "44444444-4444-4444-4444-444444444444"; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playbackManifestResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId; + _sut.HttpContext.Request.RouteValues["artistId"] = artistId; + _sut.HttpContext.Request.RouteValues["albumId"] = albumId; + _sut.HttpContext.Request.RouteValues["trackId"] = trackId; + _sut.HttpContext.Request.QueryString = new QueryString("?capabilities=mp3/mp3"); + string expectedStreamPath = ApiRoutes.Tracks.STREAM_TRACK + .Replace("{libraryId}", libraryId) + .Replace("{artistId}", artistId) + .Replace("{albumId}", albumId) + .Replace("{trackId}", trackId); + string expectedSegmentStreamPathTemplate = ApiRoutes.Tracks.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", libraryId) + .Replace("{artistId}", artistId) + .Replace("{albumId}", albumId) + .Replace("{trackId}", trackId); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId && + query.ArtistId == artistId && + query.AlbumId == albumId && + query.TrackId == trackId && + query.Capabilities == "mp3/mp3" && + query.StreamPath == expectedStreamPath && + query.SegmentStreamPathTemplate == expectedSegmentStreamPathTemplate && + query.SegmentStreamPathTemplate.Contains("{deliveryId}") && + query.SegmentStreamPathTemplate.Contains("{segmentIndex}")), + Arg.Is(cancellationToken)); + Assert.DoesNotContain("http", expectedStreamPath, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("http", expectedSegmentStreamPathTemplate, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task ExecuteAsync_WhenCapabilitiesAreAbsent_ShouldSendAnEmptyCapabilitiesValueToTheHandler() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playbackManifestResponseFixture.Create())); + SetRouteValues(); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.Capabilities == string.Empty), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_playbackManifestResponseFixture.Create()); + }, callInfo.Arg())); + SetRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token); + await operationStarted.Task; + cancellationTokenSource.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the four route values the endpoint reads from the route. + /// + private void SetRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs new file mode 100644 index 00000000..1271be84 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointTests.cs @@ -0,0 +1,286 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.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.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackSegmentEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetTrackSegmentEndpoint _sut; + private readonly NormalizedTrackSegmentDataDtoFixture _normalizedTrackSegmentDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetTrackSegmentEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Theory] + [InlineData("MP4", "audio/mp4")] // mp4 delivery container + [InlineData("OGG", "audio/ogg")] // ogg delivery container + [InlineData("MP3", "audio/mpeg")] // mp3 delivery container + [InlineData("not-a-container", "application/octet-stream")] // an unknown delivery container falls back to opaque binary + public async Task ExecuteAsync_WhenSegmentIsProduced_ShouldReturnDisposingStreamResultWithTheSegment(string container, string expectedContentType) + { + // Arrange + byte[] segmentBytes = CreateBytes(256); + MemoryStream segmentContent = new(segmentBytes); + NormalizedTrackSegmentDataDto segment = _normalizedTrackSegmentDataDtoFixture.Create( + content: segmentContent, + length: segmentBytes.Length, + startSeconds: 6.5m, + container: container, + segmentCount: 12, + durationInSeconds: 300); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(segment)); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + DisposingStreamResult streamResult = Assert.IsType(result); + Assert.Equal("nosniff", _sut.HttpContext.Response.Headers["X-Content-Type-Options"].ToString()); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + Assert.Equal("12", _sut.HttpContext.Response.Headers["X-Lumina-Segment-Count"].ToString()); + Assert.Equal("6.5", _sut.HttpContext.Response.Headers["X-Segment-Start-Seconds"].ToString()); + Assert.Equal("300", _sut.HttpContext.Response.Headers["X-Lumina-Track-Duration-Seconds"].ToString()); + _sut.HttpContext.Response.Body = new MemoryStream(); + await streamResult.ExecuteAsync(_sut.HttpContext); + Assert.Equal(expectedContentType, _sut.HttpContext.Response.ContentType); + Assert.Equal(segmentBytes.Length, _sut.HttpContext.Response.ContentLength); + Assert.Equal(segmentBytes, ReadResponseBody(_sut.HttpContext)); + Assert.Throws(() => segmentContent.ReadByte()); + } + + [Fact] + public async Task ExecuteAsync_WhenCurrentCultureUsesACommaDecimalSeparator_ShouldWriteTheSegmentStartInvariantly() + { + // Arrange + CultureInfo previousCulture = CultureInfo.CurrentCulture; + MemoryStream segmentContent = new(CreateBytes(16)); + NormalizedTrackSegmentDataDto segment = _normalizedTrackSegmentDataDtoFixture.Create(content: segmentContent, startSeconds: 3.25m); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(segment)); + SetRouteValues(); + + try + { + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("3.25", _sut.HttpContext.Response.Headers["X-Segment-Start-Seconds"].ToString()); + } + finally + { + CultureInfo.CurrentCulture = previousCulture; + } + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + List errors = [DomainErrors.Playback.DeliveryIdIsInvalid, DomainErrors.Playback.SegmentIndexMustBeValid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(errors); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Contains("General.Validation", validationProblemDetails.Errors.Keys); + Assert.Contains("DeliveryIdIsInvalid", validationProblemDetails.Errors["General.Validation"]); + Assert.Contains("SegmentIndexMustBeValid", validationProblemDetails.Errors["General.Validation"]); + } + + [Theory] + [InlineData("NotFound", StatusCodes.Status404NotFound)] // the delivery, track or segment does not exist + [InlineData("Conflict", StatusCodes.Status409Conflict)] // the delivery changed since the manifest declared it + [InlineData("ResourceUnavailable", StatusCodes.Status503ServiceUnavailable)] // the normalization pipeline is temporarily unavailable + public async Task ExecuteAsync_WhenHandlerReturnsAProblemError_ShouldReturnTheMappedStatusCode(string errorKind, int expectedStatusCode) + { + // Arrange + Error error = errorKind switch + { + "NotFound" => DomainErrors.Music.TrackFileNotFound, + "Conflict" => DomainErrors.Playback.PlaybackDeliveryChanged, + _ => DomainErrors.Playback.NormalizationUnavailable, + }; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(error); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(expectedStatusCode, problemResult.StatusCode); + Assert.Equal(expectedStatusCode, problemResult.ProblemDetails.Status); + Assert.Equal(error.Code, problemResult.ProblemDetails.Title); + Assert.Equal(error.Description, problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheExactRouteValuesToTheHandler() + { + // Arrange + string libraryId = "11111111-1111-1111-1111-111111111111"; + string artistId = "22222222-2222-2222-2222-222222222222"; + string albumId = "33333333-3333-3333-3333-333333333333"; + string trackId = "44444444-4444-4444-4444-444444444444"; + string deliveryId = "0123456789abcdef0123456789abcdef"; + string segmentIndex = "7"; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_normalizedTrackSegmentDataDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId; + _sut.HttpContext.Request.RouteValues["artistId"] = artistId; + _sut.HttpContext.Request.RouteValues["albumId"] = albumId; + _sut.HttpContext.Request.RouteValues["trackId"] = trackId; + _sut.HttpContext.Request.RouteValues["deliveryId"] = deliveryId; + _sut.HttpContext.Request.RouteValues["segmentIndex"] = segmentIndex; + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId && + query.ArtistId == artistId && + query.AlbumId == albumId && + query.TrackId == trackId && + query.DeliveryId == deliveryId && + query.SegmentIndex == segmentIndex), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendNullRouteValuesToTheHandler() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_normalizedTrackSegmentDataDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues.Clear(); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null && + query.AlbumId == null && + query.TrackId == null && + query.DeliveryId == null && + query.SegmentIndex == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_normalizedTrackSegmentDataDtoFixture.Create()); + }, callInfo.Arg())); + SetRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token); + await operationStarted.Task; + cancellationTokenSource.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the six route values the endpoint reads from the route. + /// + private void SetRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["deliveryId"] = Guid.NewGuid().ToString("N"); + _sut.HttpContext.Request.RouteValues["segmentIndex"] = "0"; + } + + /// + /// Reads the bytes written to the response body of the provided HTTP context. + /// + /// The HTTP context whose response body is read. + /// The bytes written to the response body. + private static byte[] ReadResponseBody(HttpContext httpContext) + { + httpContext.Response.Body.Position = 0; + using MemoryStream writtenBody = new(); + httpContext.Response.Body.CopyTo(writtenBody); + return writtenBody.ToArray(); + } + + /// + /// 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.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj index bc6531f0..b9bc7cd5 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Lumina.Presentation.Api.UnitTests.csproj @@ -40,6 +40,7 @@ + diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiStreamResultTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiStreamResultTests.cs new file mode 100644 index 00000000..68521337 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiStreamResultTests.cs @@ -0,0 +1,196 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +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.UnitTests.Common.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ApiStreamResultTests +{ + /// + /// Initializes a new instance of the class. + /// + public ApiStreamResultTests() + { + } + + [Fact] + public async Task CreateAsync_WhenResponseDeclaresHeaders_ShouldExposeTheStatusAndTheContentHeaders() + { + // Arrange + byte[] contentBytes = CreateBytes(64); + using HttpResponseMessage response = CreateResponse(contentBytes); + response.Content.Headers.ContentRange = new ContentRangeHeaderValue(0, contentBytes.Length - 1, 1024); + response.Headers.AcceptRanges.Add("bytes"); + response.Headers.ETag = new EntityTagHeaderValue("\"etag-value\""); + DateTimeOffset lastModified = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + response.Content.Headers.LastModified = lastModified; + response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(60) }; + + // Act + await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None); + + // Assert + Assert.Equal(HttpStatusCode.PartialContent, result.StatusCode); + Assert.Equal("audio/mp4", result.ContentType); + Assert.Equal(contentBytes.Length, result.ContentLength); + Assert.Equal("bytes 0-63/1024", result.ContentRange); + Assert.Equal("bytes", result.AcceptRanges); + Assert.Equal("\"etag-value\"", result.ETag); + Assert.Equal(lastModified, result.LastModified); + Assert.Contains("max-age=60", result.CacheControl); + } + + [Theory] + [InlineData("0")] // an empty production reports zero segments + [InlineData("1")] // a single segment production + [InlineData("42")] // a multi segment production + public async Task CreateAsync_WhenSegmentCountIsValid_ShouldExposeIt(string segmentCount) + { + // Arrange + using HttpResponseMessage response = CreateResponse(CreateBytes(8)); + response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, segmentCount); + + // Act + await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None); + + // Assert + Assert.Equal(int.Parse(segmentCount), result.SegmentCount); + } + + [Theory] + [InlineData(null)] // the header is absent + [InlineData("")] // the header is empty + [InlineData("not-a-number")] // the header is malformed + [InlineData("-1")] // a negative count is treated as absent + [InlineData("1.5")] // a fractional count is treated as absent + public async Task CreateAsync_WhenSegmentCountIsInvalid_ShouldReturnNull(string? segmentCount) + { + // Arrange + using HttpResponseMessage response = CreateResponse(CreateBytes(8)); + if (segmentCount is not null) + response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, segmentCount); + + // Act + await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None); + + // Assert + Assert.Null(result.SegmentCount); + } + + [Theory] + [InlineData("0")] // the first segment starts at the beginning of the track + [InlineData("6.5")] // a decimal with a dot is forwarded as the API wrote it + [InlineData("6,5")] // a decimal with a comma, which is not the invariant separator, is still forwarded verbatim + public async Task CreateAsync_WhenSegmentStartIsPresent_ShouldForwardItVerbatim(string segmentStart) + { + // Arrange + using HttpResponseMessage response = CreateResponse(CreateBytes(8)); + response.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, segmentStart); + + // Act + await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None); + + // Assert + Assert.Equal(segmentStart, result.SegmentStartSeconds); + } + + [Fact] + public async Task CreateAsync_WhenSegmentStartIsAbsent_ShouldReturnNull() + { + // Arrange + using HttpResponseMessage response = CreateResponse(CreateBytes(8)); + + // Act + await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None); + + // Assert + Assert.Null(result.SegmentStartSeconds); + } + + [Theory] + [InlineData("1")] // a one second production + [InlineData("300")] // a five minute production + public async Task CreateAsync_WhenTrackDurationIsPositive_ShouldExposeIt(string trackDuration) + { + // Arrange + using HttpResponseMessage response = CreateResponse(CreateBytes(8)); + response.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, trackDuration); + + // Act + await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None); + + // Assert + Assert.Equal(int.Parse(trackDuration), result.TrackDurationSeconds); + } + + [Theory] + [InlineData(null)] // the header is absent + [InlineData("0")] // a zero duration is treated as absent + [InlineData("-5")] // a negative duration is treated as absent + [InlineData("not-a-number")] // the header is malformed + public async Task CreateAsync_WhenTrackDurationIsInvalid_ShouldReturnNull(string? trackDuration) + { + // Arrange + using HttpResponseMessage response = CreateResponse(CreateBytes(8)); + if (trackDuration is not null) + response.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, trackDuration); + + // Act + await using ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None); + + // Assert + Assert.Null(result.TrackDurationSeconds); + } + + [Fact] + public async Task DisposeAsync_WhenCalled_ShouldDisposeTheContentStreamAndTheResponse() + { + // Arrange + HttpResponseMessage response = CreateResponse(CreateBytes(16)); + ApiStreamResult result = await ApiStreamResult.CreateAsync(response, CancellationToken.None); + + // Act + await result.DisposeAsync(); + + // Assert + Assert.Throws(() => result.Content.ReadByte()); + await Assert.ThrowsAsync(() => response.Content.ReadAsByteArrayAsync()); + } + + /// + /// Creates a streamed API response with a media type and a partial content status. + /// + /// The bytes of the content of the response. + /// The created HTTP response. + private static HttpResponseMessage CreateResponse(byte[] contentBytes) + { + HttpResponseMessage response = new(HttpStatusCode.PartialContent) + { + Content = new ByteArrayContent(contentBytes) + }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp4"); + return response; + } + + /// + /// Creates a deterministic byte array that stands in for streamed content. + /// + /// 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.Presentation.Web.UnitTests/Common/Http/ApiStreamProxyTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Http/ApiStreamProxyTests.cs new file mode 100644 index 00000000..fae8af76 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Http/ApiStreamProxyTests.cs @@ -0,0 +1,180 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Http; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +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.UnitTests.Common.Http; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ApiStreamProxyTests +{ + /// + /// Initializes a new instance of the class. + /// + public ApiStreamProxyTests() + { + } + + [Fact] + public async Task WriteAsync_WhenCalled_ShouldCopyTheStatusCodeAndTheContentHeaders() + { + // Arrange + byte[] contentBytes = CreateBytes(96); + using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.PartialContent, contentBytes); + apiResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mp4"); + apiResponse.Headers.AcceptRanges.Add("bytes"); + apiResponse.Headers.ETag = new EntityTagHeaderValue("\"etag-value\""); + DateTimeOffset lastModified = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + apiResponse.Content.Headers.LastModified = lastModified; + apiResponse.Content.Headers.ContentRange = new ContentRangeHeaderValue(10, 105, 1024); + apiResponse.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, "9"); + apiResponse.Headers.TryAddWithoutValidation(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, "6.5"); + apiResponse.Headers.TryAddWithoutValidation(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, "300"); + await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, CancellationToken.None); + + // Assert + Assert.Equal(StatusCodes.Status206PartialContent, httpContext.Response.StatusCode); + Assert.Equal("audio/mp4", httpContext.Response.ContentType); + Assert.Equal(contentBytes.Length, httpContext.Response.ContentLength); + Assert.Equal("bytes 10-105/1024", httpContext.Response.Headers["Content-Range"].ToString()); + Assert.Equal("bytes", httpContext.Response.Headers["Accept-Ranges"].ToString()); + Assert.Equal("\"etag-value\"", httpContext.Response.Headers["ETag"].ToString()); + Assert.Equal(lastModified.ToString("R"), httpContext.Response.Headers["Last-Modified"].ToString()); + Assert.Equal("9", httpContext.Response.Headers[ApiStreamResult.SEGMENT_COUNT_HEADER_NAME].ToString()); + Assert.Equal("6.5", httpContext.Response.Headers[ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME].ToString()); + Assert.Equal("300", httpContext.Response.Headers[ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME].ToString()); + Assert.Equal("Cookie", httpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task WriteAsync_WhenOptionalHeadersAreAbsent_ShouldNotAddThem() + { + // Arrange + using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.OK, CreateBytes(16)); + await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, CancellationToken.None); + + // Assert + Assert.False(httpContext.Response.Headers.ContainsKey("Content-Range")); + Assert.False(httpContext.Response.Headers.ContainsKey("Accept-Ranges")); + Assert.False(httpContext.Response.Headers.ContainsKey("ETag")); + Assert.False(httpContext.Response.Headers.ContainsKey("Last-Modified")); + Assert.False(httpContext.Response.Headers.ContainsKey(ApiStreamResult.SEGMENT_COUNT_HEADER_NAME)); + Assert.False(httpContext.Response.Headers.ContainsKey(ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME)); + Assert.False(httpContext.Response.Headers.ContainsKey(ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME)); + } + + [Theory] + [InlineData("public, max-age=60", new[] { "private", "max-age=60" })] // the public instruction is dropped and the max age is preserved + [InlineData("no-store", new[] { "private", "no-store" })] // the no store instruction is preserved and privacy is added + [InlineData(null, new[] { "private" })] // an absent API instruction becomes a private instruction + public async Task WriteAsync_WhenApiDeclaresCaching_ShouldAlwaysProduceAPrivateInstruction(string? apiCacheControl, string[] expectedFragments) + { + // Arrange + using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.OK, CreateBytes(16)); + if (apiCacheControl is not null) + apiResponse.Headers.CacheControl = CacheControlHeaderValue.Parse(apiCacheControl); + await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, CancellationToken.None); + + // Assert + string cacheControl = httpContext.Response.Headers["Cache-Control"].ToString(); + Assert.DoesNotContain("public", cacheControl, StringComparison.OrdinalIgnoreCase); + foreach (string fragment in expectedFragments) + Assert.Contains(fragment, cacheControl, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task WriteAsync_WhenCalled_ShouldCopyTheBodyExactly() + { + // Arrange + byte[] contentBytes = CreateBytes(2048); + using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.OK, contentBytes); + await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None); + DefaultHttpContext httpContext = CreateHttpContext(); + + // Act + await ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, CancellationToken.None); + + // Assert + httpContext.Response.Body.Position = 0; + using MemoryStream writtenBody = new(); + httpContext.Response.Body.CopyTo(writtenBody); + Assert.Equal(contentBytes, writtenBody.ToArray()); + } + + [Fact] + public async Task WriteAsync_WhenCancellationIsRequested_ShouldCancelTheCopy() + { + // Arrange + using HttpResponseMessage apiResponse = CreateResponse(HttpStatusCode.OK, CreateBytes(2048)); + await using ApiStreamResult streamResult = await ApiStreamResult.CreateAsync(apiResponse, CancellationToken.None); + DefaultHttpContext httpContext = CreateHttpContext(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operationTask = ApiStreamProxy.WriteAsync(httpContext.Response, streamResult, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with a writable response body. + /// + /// The configured HTTP context. + private static DefaultHttpContext CreateHttpContext() + { + DefaultHttpContext httpContext = new(); + httpContext.Response.Body = new MemoryStream(); + return httpContext; + } + + /// + /// Creates a streamed API response with a status code and a body. + /// + /// The status code of the response. + /// The bytes of the content of the response. + /// The created HTTP response. + private static HttpResponseMessage CreateResponse(HttpStatusCode statusCode, byte[] contentBytes) + { + return new HttpResponseMessage(statusCode) + { + Content = new ByteArrayContent(contentBytes) + }; + } + + /// + /// Creates a deterministic byte array that stands in for streamed content. + /// + /// 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.Presentation.Web.UnitTests/Common/Playback/PlaybackDeliveryIdTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Playback/PlaybackDeliveryIdTests.cs new file mode 100644 index 00000000..e0e63f53 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Playback/PlaybackDeliveryIdTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Playback; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaybackDeliveryIdTests +{ + [Theory] + [InlineData("0123456789abcdef0123456789abcdef")] // a lowercase hexadecimal handle + [InlineData("ffffffffffffffffffffffffffffffff")] // an all lowercase hexadecimal handle + [InlineData("00000000000000000000000000000000")] // an all zero handle + [InlineData("8f14e45fceea167a5a36dedd4bea2543")] // a random lowercase hexadecimal handle + public void IsValid_WhenValueIsThirtyTwoLowercaseHexadecimalCharacters_ShouldReturnTrue(string value) + { + // Act + bool result = PlaybackDeliveryId.IsValid(value); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(null)] // an absent handle is not valid + [InlineData("")] // an empty handle is not valid + [InlineData(" ")] // a whitespace only handle is not valid + [InlineData("0123456789abcdef0123456789abcde")] // a handle with 31 characters is too short + [InlineData("0123456789abcdef0123456789abcdef0")] // a handle with 33 characters is too long + [InlineData("0123456789ABCDEF0123456789ABCDEF")] // an uppercase handle is not accepted + [InlineData("01234567-89ab-cdef-0123-456789abcdef")] // a dashed GUID is not accepted + [InlineData("0123456789abcdef0123456789abcdeg")] // a non hexadecimal handle is not accepted + [InlineData("0123456789abcdef0123456789abcde ")] // a handle with a trailing space is not accepted + public void IsValid_WhenValueDoesNotMatchTheHandleFormat_ShouldReturnFalse(string? value) + { + // Act + bool result = PlaybackDeliveryId.IsValid(value); + + // Assert + Assert.False(result); + } + + [Fact] + public void CharacterCount_ShouldBeThirtyTwo() + { + // Act + int characterCount = PlaybackDeliveryId.CHARACTER_COUNT; + + // Assert + Assert.Equal(32, characterCount); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs new file mode 100644 index 00000000..13351596 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs @@ -0,0 +1,261 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +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.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetPlaybackManifest; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackManifestEndpointTests +{ + private const string VALID_DELIVERY_ID = "0123456789abcdef0123456789abcdef"; + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetPlaybackManifestEndpoint _sut; + private readonly GetPlaybackManifestRequestFixture _getPlaybackManifestRequestFixture = new(); + private readonly PlaybackManifestDtoFixture _playbackManifestDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackManifestEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenManifestIsNotADirectPlay_ShouldRewriteTheStreamPathsToTheWebProxyRoutes() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + string artistId = Guid.NewGuid().ToString(); + string albumId = Guid.NewGuid().ToString(); + string trackId = Guid.NewGuid().ToString(); + GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create( + artistId: artistId, + albumId: albumId, + trackId: trackId, + libraryId: libraryId, + includeCapabilities: false); + PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create( + isDirectPlay: false, + deliveryId: VALID_DELIVERY_ID, + streamPath: "/api/v1/libraries/ancient/stream", + segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(manifest); + 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 + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result)); + 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.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Theory] + [InlineData(true)] // a null template means the delivery has no segment route + [InlineData(false)] // an empty template means the delivery has no segment route + public async Task ExecuteAsync_WhenSegmentPathTemplateIsEmpty_ShouldClearTheDeliveryIdAndTheTemplate(bool useNullTemplate) + { + // Arrange + GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false); + PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create( + isDirectPlay: false, + deliveryId: VALID_DELIVERY_ID, + segmentStreamPathTemplate: useNullTemplate ? null : string.Empty, + includeSegmentStreamPathTemplate: !useNullTemplate); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(manifest); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result)); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(JsonValueKind.Null, data.GetProperty("deliveryId").ValueKind); + Assert.Equal(JsonValueKind.Null, data.GetProperty("segmentStreamPathTemplate").ValueKind); + Assert.NotEqual(JsonValueKind.Null, data.GetProperty("streamPath").ValueKind); + } + + [Fact] + public async Task ExecuteAsync_WhenSegmentPathTemplateIsPresentButDeliveryIdIsInvalid_ShouldThrowBadGatewayApiException() + { + // Arrange + GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false); + PlaybackManifestDto manifest = _playbackManifestDtoFixture.Create( + isDirectPlay: false, + deliveryId: "not-a-valid-handle", + segmentStreamPathTemplate: "/api/v1/libraries/ancient/stream/deliveries/{deliveryId}/segments/{segmentIndex}"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(manifest); + + // Act + Task operationTask = _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + ApiException apiException = await Assert.ThrowsAsync(() => operationTask); + Assert.Equal(HttpStatusCode.BadGateway, apiException.HttpStatusCode); + Assert.NotNull(apiException.ProblemDetails); + Assert.Equal("General.Failure", apiException.ProblemDetails!.Title); + Assert.Equal("InternalServerError", apiException.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status502BadGateway, apiException.ProblemDetails.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsNoManifest_ShouldThrowBadGatewayApiException() + { + // Arrange + GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult(null!)); + + // Act + Task operationTask = _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + ApiException apiException = await Assert.ThrowsAsync(() => operationTask); + Assert.Equal(HttpStatusCode.BadGateway, apiException.HttpStatusCode); + Assert.NotNull(apiException.ProblemDetails); + Assert.Equal("General.Failure", apiException.ProblemDetails!.Title); + Assert.Equal("InternalServerError", apiException.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status502BadGateway, apiException.ProblemDetails.Status); + } + + [Theory] + [InlineData("mp3/mp3", "?capabilities=mp3%2Fmp3")] // the capabilities are forwarded and URL-escaped + [InlineData("flac/flac,mp3/mp3", "?capabilities=flac%2Fflac%2Cmp3%2Fmp3")] // a capability list is forwarded as one escaped value + [InlineData(" ", "")] // whitespace only capabilities are not forwarded + [InlineData(null, "")] // absent capabilities are not forwarded + public async Task ExecuteAsync_WhenCapabilitiesAreProvided_ShouldForwardThemOnlyWhenTheyAreNotEmpty(string? capabilities, string expectedSuffix) + { + // Arrange + string artistId = Guid.NewGuid().ToString(); + string albumId = Guid.NewGuid().ToString(); + string trackId = Guid.NewGuid().ToString(); + Guid libraryId = Guid.NewGuid(); + GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create( + artistId: artistId, + albumId: albumId, + trackId: trackId, + libraryId: libraryId, + capabilities: capabilities, + includeCapabilities: capabilities is not null); + string expectedEndpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{artistId}", artistId) + .Replace("{albumId}", albumId) + .Replace("{trackId}", trackId) + expectedSuffix; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID)); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == expectedEndpoint), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi() + { + // Arrange + GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1", trackId: "'; DROP TABLE Tracks; --", includeCapabilities: false); + string expectedEndpoint = ApiRoutes.Music.GET_PLAYBACK_MANIFEST + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", Guid.Empty.ToString()) + .Replace("{albumId}", Guid.Empty.ToString()) + .Replace("{trackId}", Guid.Empty.ToString()); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID)); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == expectedEndpoint), + Arg.Any()); + } + + [Theory] + [InlineData("/lumina", "/lumina")] // a plain absolute path base is prefixed + [InlineData("//evil", "")] // a protocol relative path base would point the stream at another origin + [InlineData("/a?b", "")] // a path base with a query would truncate the built path + public async Task ExecuteAsync_WhenPathBaseIsPresent_ShouldUseItOnlyWhenItIsSafe(string pathBase, string expectedPrefix) + { + // Arrange + GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false); + _sut.HttpContext.Request.PathBase = pathBase; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(_playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + using JsonDocument json = JsonDocument.Parse(await JsonResultTestHelper.GetResponseBodyAsync(result)); + string? streamPath = json.RootElement.GetProperty("data").GetProperty("streamPath").GetString(); + Assert.NotNull(streamPath); + Assert.StartsWith($"{expectedPrefix}/en-US/library/audio-library/music-library/artists/", streamPath); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetPlaybackManifestRequest request = _getPlaybackManifestRequestFixture.Create(includeCapabilities: false); + CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return _playbackManifestDtoFixture.Create(deliveryId: VALID_DELIVERY_ID); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token); + await operationStarted.Task; + cancellationTokenSource.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs new file mode 100644 index 00000000..c3036b52 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs @@ -0,0 +1,223 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +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.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackEndpointTests +{ + private readonly IStreamingApiHttpClient _mockStreamingApiHttpClient; + private readonly StreamMusicTrackEndpoint _sut; + private readonly StreamMusicTrackRequestFixture _streamMusicTrackRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public StreamMusicTrackEndpointTests() + { + _mockStreamingApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockStreamingApiHttpClient); + _sut.HttpContext.Response.Body = new MemoryStream(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldStreamTheTrackAndReturnEmptyResult() + { + // Arrange + StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(); + string expectedEndpoint = BuildExpectedEndpoint(request); + byte[] contentBytes = CreateBytes(1024); + ApiStreamResult streamResult = await CreateStreamResultAsync(HttpStatusCode.OK, contentBytes, "audio/flac"); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(streamResult); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + Assert.IsType(result); + await _mockStreamingApiHttpClient.Received(1).GetStreamAsync( + Arg.Is(endpoint => endpoint == expectedEndpoint), + Arg.Any>(), + Arg.Any()); + Assert.Equal(StatusCodes.Status200OK, _sut.HttpContext.Response.StatusCode); + Assert.Equal("audio/flac", _sut.HttpContext.Response.ContentType); + Assert.Equal(contentBytes.Length, _sut.HttpContext.Response.ContentLength); + Assert.Equal(contentBytes, ReadResponseBody(_sut.HttpContext)); + Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString()); + Assert.Contains("private", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenConditionalHeadersArePresent_ShouldForwardThemExactly() + { + // Arrange + StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(); + _sut.HttpContext.Request.Headers["Range"] = "bytes=100-199"; + _sut.HttpContext.Request.Headers["If-Range"] = "\"etag-value\""; + _sut.HttpContext.Request.Headers["If-None-Match"] = "\"etag-value\""; + _sut.HttpContext.Request.Headers["If-Modified-Since"] = "Wed, 21 Oct 2015 07:28:00 GMT"; + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(16))); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockStreamingApiHttpClient.Received(1).GetStreamAsync( + Arg.Any(), + Arg.Is>(headers => + headers.Count == 4 && + headers["Range"] == "bytes=100-199" && + headers["If-Range"] == "\"etag-value\"" && + headers["If-None-Match"] == "\"etag-value\"" && + headers["If-Modified-Since"] == "Wed, 21 Oct 2015 07:28:00 GMT"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenConditionalHeadersAreAbsentOrWhitespace_ShouldNotForwardThem() + { + // Arrange + StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(); + _sut.HttpContext.Request.Headers["Range"] = " "; + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(16))); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockStreamingApiHttpClient.Received(1).GetStreamAsync( + Arg.Any(), + Arg.Is>(headers => headers.Count == 0), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi() + { + // Arrange + StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(artistId: "not-a-guid", albumId: "' OR '1'='1", trackId: "'; DROP TABLE Tracks; --"); + string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", Guid.Empty.ToString()) + .Replace("{albumId}", Guid.Empty.ToString()) + .Replace("{trackId}", Guid.Empty.ToString()); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8))); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockStreamingApiHttpClient.Received(1).GetStreamAsync( + Arg.Is(endpoint => endpoint == expectedEndpoint), + Arg.Any>(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token); + await operationStarted.Task; + cancellationTokenSource.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Builds the upstream endpoint the track stream request is expected to be sent to. + /// + /// The request to build the endpoint for. + /// The expected upstream endpoint. + private static string BuildExpectedEndpoint(StreamMusicTrackRequest request) + { + return ApiRoutes.Music.STREAM_TRACK + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", request.ArtistId) + .Replace("{albumId}", request.AlbumId) + .Replace("{trackId}", request.TrackId); + } + + /// + /// Creates a streamed API response with a status code, a body and an optional media type. + /// + /// The status code of the response. + /// The bytes of the content of the response. + /// The optional media type of the content. + /// The created streamed response. + private static async Task CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string? contentType = null) + { + HttpResponseMessage response = new(statusCode) + { + Content = new ByteArrayContent(contentBytes) + }; + if (contentType is not null) + response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + return await ApiStreamResult.CreateAsync(response, CancellationToken.None); + } + + /// + /// Reads the bytes written to the response body of the provided HTTP context. + /// + /// The HTTP context whose response body is read. + /// The bytes written to the response body. + private static byte[] ReadResponseBody(HttpContext httpContext) + { + httpContext.Response.Body.Position = 0; + using MemoryStream writtenBody = new(); + httpContext.Response.Body.CopyTo(writtenBody); + return writtenBody.ToArray(); + } + + /// + /// Creates a deterministic byte array that stands in for the content of a track. + /// + /// 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.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs new file mode 100644 index 00000000..4a0cc954 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointTests.cs @@ -0,0 +1,265 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +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.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackSegmentEndpointTests +{ + private readonly IStreamingApiHttpClient _mockStreamingApiHttpClient; + private readonly StreamMusicTrackSegmentEndpoint _sut; + private readonly StreamMusicTrackSegmentRequestFixture _streamMusicTrackSegmentRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public StreamMusicTrackSegmentEndpointTests() + { + _mockStreamingApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockStreamingApiHttpClient); + _sut.HttpContext.Response.Body = new MemoryStream(); + } + + [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 + [InlineData("short")] // a handle that is shorter than the format allows + public async Task ExecuteAsync_WhenDeliveryIdIsInvalid_ShouldReturnNotFoundWithoutCallingTheApi(string malformedHandleKind) + { + // Arrange + string validDeliveryId = Guid.NewGuid().ToString("N"); + string malformedDeliveryId = malformedHandleKind switch + { + "uppercase" => validDeliveryId.ToUpperInvariant(), + "dashed" => Guid.Parse(validDeliveryId).ToString("D"), + _ => validDeliveryId[..31], + }; + StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create(deliveryId: malformedDeliveryId); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, _sut.HttpContext.Response.StatusCode); + Assert.Equal(0, _sut.HttpContext.Response.ContentLength); + Assert.Equal(0, _sut.HttpContext.Response.Body.Length); + await _mockStreamingApiHttpClient.DidNotReceive().GetStreamAsync( + Arg.Any(), + Arg.Any>(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsValid_ShouldStreamTheSegmentFromTheApi() + { + // Arrange + StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create(); + string expectedEndpoint = BuildExpectedEndpoint(request); + byte[] contentBytes = CreateBytes(512); + ApiStreamResult streamResult = await CreateStreamResultAsync(HttpStatusCode.PartialContent, contentBytes, "audio/mp4"); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(streamResult); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + Assert.IsType(result); + await _mockStreamingApiHttpClient.Received(1).GetStreamAsync( + Arg.Is(endpoint => endpoint == expectedEndpoint), + Arg.Is>(headers => headers.Count == 0), + Arg.Any()); + Assert.Equal(StatusCodes.Status206PartialContent, _sut.HttpContext.Response.StatusCode); + Assert.Equal("audio/mp4", _sut.HttpContext.Response.ContentType); + Assert.Equal(contentBytes.Length, _sut.HttpContext.Response.ContentLength); + Assert.Equal(contentBytes, ReadResponseBody(_sut.HttpContext)); + Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString()); + Assert.Contains("private", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + } + + [Theory] + [InlineData("artistId", "' OR '1'='1")] // an unparseable artist Id is normalized to an empty GUID + [InlineData("albumId", "'; DROP TABLE Tracks; --")] // an unparseable album Id is normalized to an empty GUID + [InlineData("trackId", "not-a-guid")] // an unparseable track Id is normalized to an empty GUID + public async Task ExecuteAsync_WhenRouteIdsAreNotParseable_ShouldForwardEmptyGuidsToTheApi(string routeValue, string invalidValue) + { + // Arrange + StreamMusicTrackSegmentRequest request = routeValue switch + { + "artistId" => _streamMusicTrackSegmentRequestFixture.Create(artistId: invalidValue), + "albumId" => _streamMusicTrackSegmentRequestFixture.Create(albumId: invalidValue), + _ => _streamMusicTrackSegmentRequestFixture.Create(trackId: invalidValue), + }; + string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", routeValue == "artistId" ? Guid.Empty.ToString() : request.ArtistId) + .Replace("{albumId}", routeValue == "albumId" ? Guid.Empty.ToString() : request.AlbumId) + .Replace("{trackId}", routeValue == "trackId" ? Guid.Empty.ToString() : request.TrackId) + .Replace("{deliveryId}", request.DeliveryId) + .Replace("{segmentIndex}", request.SegmentIndex.ToString(CultureInfo.InvariantCulture)); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8), "audio/mpeg")); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockStreamingApiHttpClient.Received(1).GetStreamAsync( + Arg.Is(endpoint => endpoint == expectedEndpoint), + Arg.Any>(), + Arg.Any()); + } + + [Theory] + [InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition + [InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached + public async Task ExecuteAsync_WhenApiReportsATransientCondition_ShouldReturnABareStatusWithoutThrowing(HttpStatusCode statusCode) + { + // Arrange + StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create(); + ApiException apiException = new( + new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode }, + statusCode, + BuildExpectedEndpoint(request)); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Task.FromException(apiException)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + Assert.IsType(result); + Assert.Equal((int)statusCode, _sut.HttpContext.Response.StatusCode); + Assert.Equal(0, _sut.HttpContext.Response.ContentLength); + Assert.Equal(0, _sut.HttpContext.Response.Body.Length); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReportsAnUnexpectedFailure_ShouldPropagateTheApiException() + { + // Arrange + StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create(); + ApiException apiException = new( + new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = StatusCodes.Status500InternalServerError }, + HttpStatusCode.InternalServerError, + BuildExpectedEndpoint(request)); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Task.FromException(apiException)); + + // Act + Task operationTask = _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await Assert.ThrowsAsync(() => operationTask); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + StreamMusicTrackSegmentRequest request = _streamMusicTrackSegmentRequestFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return await CreateStreamResultAsync(HttpStatusCode.OK, CreateBytes(8)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cancellationTokenSource.Token); + await operationStarted.Task; + cancellationTokenSource.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Builds the upstream endpoint the segment request is expected to be sent to. + /// + /// The request to build the endpoint for. + /// The expected upstream endpoint. + private static string BuildExpectedEndpoint(StreamMusicTrackSegmentRequest request) + { + return ApiRoutes.Music.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", request.ArtistId) + .Replace("{albumId}", request.AlbumId) + .Replace("{trackId}", request.TrackId) + .Replace("{deliveryId}", request.DeliveryId) + .Replace("{segmentIndex}", request.SegmentIndex.ToString(CultureInfo.InvariantCulture)); + } + + /// + /// Creates a streamed API response with a status code, a body and an optional media type. + /// + /// The status code of the response. + /// The bytes of the content of the response. + /// The optional media type of the content. + /// The created streamed response. + private static async Task CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string? contentType = null) + { + HttpResponseMessage response = new(statusCode) + { + Content = new ByteArrayContent(contentBytes) + }; + if (contentType is not null) + response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + return await ApiStreamResult.CreateAsync(response, CancellationToken.None); + } + + /// + /// Reads the bytes written to the response body of the provided HTTP context. + /// + /// The HTTP context whose response body is read. + /// The bytes written to the response body. + private static byte[] ReadResponseBody(HttpContext httpContext) + { + httpContext.Response.Body.Position = 0; + using MemoryStream writtenBody = new(); + httpContext.Response.Body.CopyTo(writtenBody); + return writtenBody.ToArray(); + } + + /// + /// 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))]; + } +}