mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 23:11:10 +00:00
Captures the audio container of the music tracks
Adds a Container to the audio metadata, captured with TagLibSharp from the concrete type of the parsed file during the music library scan and stored on the track through a new column and an EF migration. The container is refreshed when a file changes, survives track and artist edits and provider enrichment, and is exposed read-only in the track responses, never settable through a request. Extracts the container resolution into a testable resolver used by the scan pipeline and the ID3 plugin, refuses to read a file that is itself a reparse point during extraction, and updates the endpoint summaries, the API and domain documentation, and the tests.
This commit is contained in:
1 parent
4ffa81fffe
commit
f29f89f31f
60 files changed
+4483
-68
No files matched your search
+4
-1
@@ -39,6 +39,7 @@ public class MusicLibraryScanItemMetadataEntityFixture
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work.</param>
|
||||
/// <param name="workTitle">Optional. The title of the work.</param>
|
||||
/// <param name="includeMusicBrainzTags">Whether the MusicBrainz identifiers and the work title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="MusicLibraryScanItemMetadataEntity"/>.</returns>
|
||||
public MusicLibraryScanItemMetadataEntity Create(
|
||||
Guid? id = null,
|
||||
@@ -58,7 +59,8 @@ public class MusicLibraryScanItemMetadataEntityFixture
|
||||
Guid? musicBrainzTrackId = null,
|
||||
Guid? musicBrainzWorkId = null,
|
||||
string? workTitle = null,
|
||||
bool includeMusicBrainzTags = true)
|
||||
bool includeMusicBrainzTags = true,
|
||||
bool includeContainer = true)
|
||||
{
|
||||
return new MusicLibraryScanItemMetadataEntity
|
||||
{
|
||||
@@ -78,6 +80,7 @@ public class MusicLibraryScanItemMetadataEntityFixture
|
||||
Channels = _faker.PickRandom(1, 2, 6),
|
||||
BitDepth = Random.Shared.Next(8, 32),
|
||||
AudioCodec = _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC"),
|
||||
Container = includeContainer ? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV") : null,
|
||||
Bitrate = Random.Shared.Next(96, 1411),
|
||||
MusicBrainzArtistId = includeMusicBrainzTags ? musicBrainzArtistId ?? Guid.NewGuid() : null,
|
||||
MusicBrainzReleaseArtistId = includeMusicBrainzTags ? musicBrainzReleaseArtistId ?? Guid.NewGuid() : null,
|
||||
|
||||
+5
@@ -37,6 +37,7 @@ public class TrackEntityFixture
|
||||
/// <param name="libraryId">Optional. The Id of the media library that owns the track.</param>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="container">Optional. The container of the audio file of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="originalReleaseDate">Optional. The original release date of the track.</param>
|
||||
/// <param name="originalReleaseYear">Optional. The original release year of the track.</param>
|
||||
@@ -47,6 +48,7 @@ public class TrackEntityFixture
|
||||
/// <param name="includeOriginalReleaseYear">Whether the original release year should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReReleaseDate">Whether the re-release date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeReReleaseYear">Whether the re-release year should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="metadataStatus">Optional. The metadata enrichment status of the track.</param>
|
||||
/// <returns>The created <see cref="TrackEntity"/>.</returns>
|
||||
public TrackEntity Create(
|
||||
@@ -55,6 +57,7 @@ public class TrackEntityFixture
|
||||
Guid? libraryId = null,
|
||||
string? path = null,
|
||||
string? title = null,
|
||||
string? container = null,
|
||||
int? trackNumber = null,
|
||||
DateOnly? originalReleaseDate = null,
|
||||
int? originalReleaseYear = null,
|
||||
@@ -65,6 +68,7 @@ public class TrackEntityFixture
|
||||
bool includeOriginalReleaseYear = true,
|
||||
bool includeReReleaseDate = true,
|
||||
bool includeReReleaseYear = true,
|
||||
bool includeContainer = true,
|
||||
MetadataStatus? metadataStatus = null)
|
||||
{
|
||||
Guid resolvedId = id ?? Guid.NewGuid();
|
||||
@@ -111,6 +115,7 @@ public class TrackEntityFixture
|
||||
.RuleFor(x => x.Channels, f => f.PickRandom(1, 2, 6))
|
||||
.RuleFor(x => x.BitDepth, Random.Shared.Next(8, 32))
|
||||
.RuleFor(x => x.AudioCodec, f => f.PickRandom("FLAC", "MP3", "AAC", "ALAC"))
|
||||
.RuleFor(x => x.Container, f => includeContainer ? (container ?? f.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV")) : null)
|
||||
.RuleFor(x => x.Bitrate, Random.Shared.Next(96, 1411))
|
||||
.RuleFor(x => x.TrackNumber, f => trackNumber ?? f.Random.Int(1, 20))
|
||||
.RuleFor(x => x.DiscNumber, Random.Shared.Next(1, 3))
|
||||
|
||||
+5
@@ -61,6 +61,7 @@ public class AudioMetadataDtoFixture
|
||||
/// <param name="channels">Optional. The number of audio channels.</param>
|
||||
/// <param name="bitDepth">Optional. The bit depth of the audio.</param>
|
||||
/// <param name="audioCodec">Optional. The audio codec used.</param>
|
||||
/// <param name="container">Optional. The container of the audio file.</param>
|
||||
/// <param name="bitrate">Optional. The bitrate of the audio, in kbps.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording.</param>
|
||||
/// <param name="musicBrainzTrackId">Optional. The MusicBrainz identifier of the track.</param>
|
||||
@@ -86,6 +87,7 @@ public class AudioMetadataDtoFixture
|
||||
/// <param name="includeChannels">Whether the channels should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeAudioCodec">Whether the audio codec should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeBitrate">Whether the bitrate should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
@@ -114,6 +116,7 @@ public class AudioMetadataDtoFixture
|
||||
int? channels = null,
|
||||
int? bitDepth = null,
|
||||
string? audioCodec = null,
|
||||
string? container = null,
|
||||
int? bitrate = null,
|
||||
Guid? musicBrainzRecordingId = null,
|
||||
Guid? musicBrainzTrackId = null,
|
||||
@@ -139,6 +142,7 @@ public class AudioMetadataDtoFixture
|
||||
bool includeChannels = true,
|
||||
bool includeBitDepth = true,
|
||||
bool includeAudioCodec = true,
|
||||
bool includeContainer = true,
|
||||
bool includeBitrate = true,
|
||||
bool includeMusicBrainzRecordingId = true,
|
||||
bool includeMusicBrainzTrackId = true,
|
||||
@@ -167,6 +171,7 @@ public class AudioMetadataDtoFixture
|
||||
includeChannels ? (channels ?? _faker.Random.Int(1, 8)) : null,
|
||||
includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null,
|
||||
includeAudioCodec ? (audioCodec ?? _faker.Random.ArrayElement(["FLAC", "MP3", "AAC", "ALAC"])) : null,
|
||||
includeContainer ? (container ?? _faker.Random.ArrayElement(["MP3", "FLAC", "OGG", "MP4", "AAC", "WAV"])) : null,
|
||||
includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : null,
|
||||
includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
|
||||
includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
|
||||
|
||||
+7
-2
@@ -39,6 +39,7 @@ public class TrackResponseFixture
|
||||
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library this track belongs to.</param>
|
||||
/// <param name="path">Optional. The file system path of the track.</param>
|
||||
/// <param name="container">Optional. The container of the audio file of the track.</param>
|
||||
/// <param name="metadata">Optional. The audio metadata of the track.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
|
||||
@@ -56,6 +57,7 @@ public class TrackResponseFixture
|
||||
/// <param name="ratings">Optional. The list of ratings of the track.</param>
|
||||
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMusicBrainzTrackId">Whether the MusicBrainz track Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="TrackResponse"/>.</returns>
|
||||
public TrackResponse Create(
|
||||
Guid? id = null,
|
||||
@@ -78,7 +80,9 @@ public class TrackResponseFixture
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<AudioRatingDto>? ratings = null,
|
||||
bool includeMusicBrainzRecordingId = true,
|
||||
bool includeMusicBrainzTrackId = true)
|
||||
bool includeMusicBrainzTrackId = true,
|
||||
bool includeContainer = true,
|
||||
string? container = null)
|
||||
{
|
||||
return new TrackResponse(
|
||||
id ?? Guid.NewGuid(),
|
||||
@@ -99,7 +103,8 @@ public class TrackResponseFixture
|
||||
moods ?? _moodDtoFixture.CreateMany(1),
|
||||
isrcs ?? _isrcDtoFixture.CreateMany(1),
|
||||
contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1),
|
||||
ratings ?? _audioRatingDtoFixture.CreateMany(1));
|
||||
ratings ?? _audioRatingDtoFixture.CreateMany(1),
|
||||
includeContainer ? (container ?? _faker.Random.ArrayElement(["MP3", "FLAC", "OGG", "MP4", "AAC", "WAV"])) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+3
@@ -39,6 +39,7 @@ public class AudioMetadataFixture
|
||||
/// <param name="originalLanguage">Optional. The original language of the audio.</param>
|
||||
/// <param name="bitDepth">Optional. The bit depth of the audio.</param>
|
||||
/// <param name="audioCodec">Optional. The audio codec used.</param>
|
||||
/// <param name="container">Optional. The container of the audio.</param>
|
||||
/// <param name="bitrate">Optional. The bitrate of the audio, in kbps.</param>
|
||||
/// <param name="acoustId">Optional. The AcoustID fingerprint identifier of the audio file.</param>
|
||||
/// <param name="replayGainTrackGain">Optional. The ReplayGain track gain, in decibels.</param>
|
||||
@@ -60,6 +61,7 @@ public class AudioMetadataFixture
|
||||
Optional<LanguageInfo>? originalLanguage = null,
|
||||
Optional<int>? bitDepth = null,
|
||||
Optional<string>? audioCodec = null,
|
||||
Optional<string>? container = null,
|
||||
Optional<int>? bitrate = null,
|
||||
Optional<string>? acoustId = null,
|
||||
Optional<decimal>? replayGainTrackGain = null,
|
||||
@@ -81,6 +83,7 @@ public class AudioMetadataFixture
|
||||
originalLanguage ?? Optional<LanguageInfo>.None(),
|
||||
bitDepth ?? Optional<int>.Some(_faker.Random.Int(8, 32)),
|
||||
audioCodec ?? Optional<string>.Some("PCM"),
|
||||
container ?? Optional<string>.Some(_faker.PickRandom("MP3", "FLAC", "OGG", "MP4", "AAC", "WAV")),
|
||||
bitrate ?? Optional<int>.Some(_faker.Random.Int(128, 320)),
|
||||
acoustId ?? Optional<string>.None(),
|
||||
replayGainTrackGain ?? Optional<decimal>.None(),
|
||||
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="MusicMetadataExtractionJob"/> class, probing real audio containers through the tagging library.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMetadataExtractionJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMusicLibraryScanItemMetadataRepository _mockMusicMetadataRepository;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly ILibraryPathTemplateService _mockPathTemplateService;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MusicMetadataExtractionJob _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryId _libraryId;
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicMetadataExtractionJobTests"/> class.
|
||||
/// </summary>
|
||||
public MusicMetadataExtractionJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMusicMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicMetadataRepository);
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
_mockServiceProvider.GetService(typeof(ILibraryPathTemplateService)).Returns(_mockPathTemplateService);
|
||||
_mockServiceProvider.GetService(typeof(IPathService)).Returns(_mockPathService);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
// Default stubs that keep the happy path working, overridden per test where needed.
|
||||
_mockMusicMetadataRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(_libraryPathTemplateFixture.Create()));
|
||||
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>()).Returns(Result.From<Optional<ParsedLibraryPath>>(Optional<ParsedLibraryPath>.None()));
|
||||
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
|
||||
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("tone");
|
||||
_mockPathService.GetFileName(Arg.Any<string>()).Returns("tone.wav");
|
||||
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_sut = new MusicMetadataExtractionJob(_mockServiceScopeFactory, Substitute.For<Microsoft.Extensions.Logging.ILogger<MusicMetadataExtractionJob>>())
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheFileIsARealAudioFile_ShouldCaptureItsContainerAndAudioProperties()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryMediaDirectory temporaryMediaDirectory = new();
|
||||
string audioFilePath = temporaryMediaDirectory.CreateWavFile("tone.wav");
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
contentLocations: [temporaryMediaDirectory.Path]);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([audioFilePath]));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
|
||||
&& items.First().Container == "WAV"
|
||||
&& items.First().SampleRate == 8000
|
||||
&& items.First().Channels == 1
|
||||
&& items.First().BitDepth == 16),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheContainerHasNoDedicatedParser_ShouldFallBackToTheMimeTypeName()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryMediaDirectory temporaryMediaDirectory = new();
|
||||
string imageFilePath = temporaryMediaDirectory.CreatePngFile("cover.png");
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
contentLocations: [temporaryMediaDirectory.Path]);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([imageFilePath]));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
|
||||
&& items.First().Container == "PNG"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheFileIsAReparsePoint_ShouldNotReadTheLinkedFile()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryMediaDirectory temporaryMediaDirectory = new();
|
||||
using TemporaryMediaDirectory outsideMediaDirectory = new();
|
||||
string targetFilePath = outsideMediaDirectory.CreateWavFile("target.wav");
|
||||
string linkFilePath = System.IO.Path.Combine(temporaryMediaDirectory.Path, "link.wav");
|
||||
if (!TryCreateFileSymbolicLink(linkFilePath, targetFilePath))
|
||||
return; // The environment does not support creating file symbolic links.
|
||||
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
contentLocations: [temporaryMediaDirectory.Path]);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([linkFilePath]));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The linked file lives outside the content location, so its audio metadata must not be read: the container stays unrecognized.
|
||||
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
|
||||
&& items.First().Container == null
|
||||
&& items.First().SampleRate == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a file system symbolic link that points to the target file.
|
||||
/// </summary>
|
||||
/// <param name="linkPath">The file system path of the symbolic link to create.</param>
|
||||
/// <param name="targetPath">The file system path of the file the link points to.</param>
|
||||
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
|
||||
private static bool TryCreateFileSymbolicLink(string linkPath, string targetPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.CreateSymbolicLink(linkPath, targetPath);
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Creating a file symbolic link requires elevated privileges on Windows, so the environment may not support it.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test helper managing a temporary directory holding real media files, deleted when the test finishes.
|
||||
/// </summary>
|
||||
private sealed class TemporaryMediaDirectory : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// A minimal, valid, one by one pixel PNG image, used to exercise a container that has no dedicated parser.
|
||||
/// </summary>
|
||||
private const string PNG_BYTES = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAANSURBVBhXY2BgYGAAAAAFAAGKM+MAAAAAAElFTkSuQmCC";
|
||||
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TemporaryMediaDirectory"/> class.
|
||||
/// </summary>
|
||||
public TemporaryMediaDirectory()
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-music-probe-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the full path of the temporary directory.
|
||||
/// </summary>
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Writes a minimal, valid, one second long 16 bit PCM mono 8000 Hz WAV file into the temporary directory.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the WAV file to create.</param>
|
||||
/// <returns>The full path of the created WAV file.</returns>
|
||||
public string CreateWavFile(string fileName)
|
||||
{
|
||||
const int SAMPLE_RATE = 8000;
|
||||
const short CHANNELS = 1;
|
||||
const short BITS_PER_SAMPLE = 16;
|
||||
int blockAlign = CHANNELS * (BITS_PER_SAMPLE / 8);
|
||||
int dataSize = SAMPLE_RATE * blockAlign;
|
||||
string filePath = System.IO.Path.Combine(Path, fileName);
|
||||
|
||||
using (FileStream stream = new(filePath, FileMode.Create, FileAccess.Write))
|
||||
using (BinaryWriter writer = new(stream))
|
||||
{
|
||||
writer.Write("RIFF"u8.ToArray());
|
||||
writer.Write(36 + dataSize);
|
||||
writer.Write("WAVE"u8.ToArray());
|
||||
writer.Write("fmt "u8.ToArray());
|
||||
writer.Write(16);
|
||||
writer.Write((short)1);
|
||||
writer.Write(CHANNELS);
|
||||
writer.Write(SAMPLE_RATE);
|
||||
writer.Write(SAMPLE_RATE * blockAlign);
|
||||
writer.Write((short)blockAlign);
|
||||
writer.Write(BITS_PER_SAMPLE);
|
||||
writer.Write("data"u8.ToArray());
|
||||
writer.Write(dataSize);
|
||||
writer.Write(new byte[dataSize]);
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a minimal, valid PNG image into the temporary directory.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the PNG file to create.</param>
|
||||
/// <returns>The full path of the created PNG file.</returns>
|
||||
public string CreatePngFile(string fileName)
|
||||
{
|
||||
string filePath = System.IO.Path.Combine(Path, fileName);
|
||||
File.WriteAllBytes(filePath, Convert.FromBase64String(PNG_BYTES));
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the temporary directory, ignoring the failures of the files that are still in use.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
try
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Best effort cleanup of the temporary directory.
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -56,6 +56,7 @@ public class Id3TrackMetadataProviderTests : IDisposable
|
||||
Assert.Equal("The Track", result.Title);
|
||||
Assert.Equal(MusicKey.CSharpMinor, result.Key);
|
||||
Assert.Equal(128, result.Bpm);
|
||||
Assert.Equal("WAV", result.Container);
|
||||
Assert.NotNull(result.Contributors);
|
||||
Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Artist");
|
||||
}
|
||||
|
||||
+22
@@ -15,6 +15,11 @@ namespace Lumina.Plugins.ID3.IntegrationTests.Core.Tags;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Id3TagReaderTests : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// A minimal, valid, one by one pixel PNG image, used to exercise a container that has no dedicated parser.
|
||||
/// </summary>
|
||||
private const string PNG_BYTES = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAANSURBVBhXY2BgYGAAAAAFAAGKM+MAAAAAAElFTkSuQmCC";
|
||||
|
||||
private readonly Id3TagReader _sut = new();
|
||||
private readonly string _temporaryDirectory;
|
||||
|
||||
@@ -131,6 +136,7 @@ public class Id3TagReaderTests : IDisposable
|
||||
Assert.Equal(16, result.BitDepth);
|
||||
Assert.True(result.Bitrate > 0);
|
||||
Assert.Equal("PCM Audio", result.AudioCodec);
|
||||
Assert.Equal("WAV", result.Container);
|
||||
Assert.Equal("https://artist.example", result.Website);
|
||||
Assert.Equal(artistId.ToString(), result.MusicBrainzArtistId);
|
||||
Assert.Equal(releaseArtistId.ToString(), result.MusicBrainzReleaseArtistId);
|
||||
@@ -192,6 +198,7 @@ public class Id3TagReaderTests : IDisposable
|
||||
Assert.Equal(1, result.Channels);
|
||||
Assert.Equal(16, result.BitDepth);
|
||||
Assert.Equal("PCM Audio", result.AudioCodec);
|
||||
Assert.Equal("WAV", result.Container);
|
||||
Assert.Null(result.Website);
|
||||
Assert.Null(result.MusicBrainzArtistId);
|
||||
Assert.Null(result.MusicBrainzReleaseArtistId);
|
||||
@@ -216,6 +223,21 @@ public class Id3TagReaderTests : IDisposable
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenTheContainerHasNoDedicatedParser_ShouldFallBackToTheMimeTypeName()
|
||||
{
|
||||
// Arrange
|
||||
string path = Path.Combine(_temporaryDirectory, "cover.png");
|
||||
File.WriteAllBytes(path, Convert.FromBase64String(PNG_BYTES));
|
||||
|
||||
// Act
|
||||
Id3TagDto? result = _sut.Read(path);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("PNG", result.Container);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenCalledTwiceForTheSamePath_ShouldReturnTheCachedSnapshot()
|
||||
{
|
||||
|
||||
+25
-1
@@ -284,6 +284,30 @@ public class UpdateArtistCommandMappingTests
|
||||
Assert.Equal(disambiguation, updatedTrack.Disambiguation.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTheTrackMetadataCarriesNoContainer_ShouldKeepTheTrackContainer()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId);
|
||||
AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]);
|
||||
UpdateArtistCommand command = _updateArtistCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albums: [albumCommand]);
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
|
||||
// The stored container is pinned to a known value, so the assertion cannot pass by coincidence.
|
||||
// The container is captured from the file itself, so reconciling a track during an artist edit keeps the stored container.
|
||||
Assert.Equal("FLAC", updatedTrack.Metadata.Container.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
@@ -296,7 +320,7 @@ public class UpdateArtistCommandMappingTests
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
libraryId: libraryId,
|
||||
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]);
|
||||
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, container: "FLAC")]);
|
||||
ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]);
|
||||
Result<Artist> artistResult = artistEntity.ToDomainEntity();
|
||||
return (artistResult.Value, albumId, trackId);
|
||||
|
||||
+4
@@ -50,6 +50,7 @@ public class AudioMetadataDtoMappingTests
|
||||
Assert.Equal(dto.Channels, track.Metadata.Channels);
|
||||
Assert.Equal(dto.BitDepth, track.Metadata.BitDepth.Value);
|
||||
Assert.Equal(dto.AudioCodec, track.Metadata.AudioCodec.Value);
|
||||
Assert.Equal(dto.Container, track.Metadata.Container.Value);
|
||||
Assert.Equal(dto.Bitrate, track.Metadata.Bitrate.Value);
|
||||
Assert.True(track.Script.HasValue);
|
||||
Assert.Equal(dto.Script, track.Script.Value);
|
||||
@@ -80,12 +81,14 @@ public class AudioMetadataDtoMappingTests
|
||||
int storedChannels = track.Metadata.Channels;
|
||||
bool hadStoredWork = track.Work.HasValue;
|
||||
int storedIsrcCount = track.Isrcs.Count;
|
||||
string? storedContainer = track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null;
|
||||
AudioMetadataDto dto = _audioMetadataDtoFixture.Create(
|
||||
includeDurationInSeconds: false,
|
||||
includeSampleRate: false,
|
||||
includeChannels: false,
|
||||
includeBitDepth: false,
|
||||
includeAudioCodec: false,
|
||||
includeContainer: false,
|
||||
includeBitrate: false,
|
||||
includeWork: false,
|
||||
includeIsrcs: false,
|
||||
@@ -99,6 +102,7 @@ public class AudioMetadataDtoMappingTests
|
||||
Assert.Equal(storedDuration, track.Metadata.DurationInSeconds);
|
||||
Assert.Equal(storedSampleRate, track.Metadata.SampleRate);
|
||||
Assert.Equal(storedChannels, track.Metadata.Channels);
|
||||
Assert.Equal(storedContainer, track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null);
|
||||
Assert.Equal(hadStoredWork, track.Work.HasValue);
|
||||
Assert.Equal(storedIsrcCount, track.Isrcs.Count);
|
||||
}
|
||||
|
||||
+8
-6
@@ -27,7 +27,7 @@ public class MusicTrackMetadataDtoMappingTests
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly()
|
||||
public void ToDomainValueObject_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create();
|
||||
@@ -70,6 +70,8 @@ public class MusicTrackMetadataDtoMappingTests
|
||||
Assert.Equal(dto.BitDepth, metadata.BitDepth.Value);
|
||||
Assert.True(metadata.AudioCodec.HasValue);
|
||||
Assert.Equal(dto.AudioCodec, metadata.AudioCodec.Value);
|
||||
// The container is captured locally from the file itself, so it can never be set through the metadata of a request.
|
||||
Assert.False(metadata.Container.HasValue);
|
||||
Assert.True(metadata.Bitrate.HasValue);
|
||||
Assert.Equal(dto.Bitrate, metadata.Bitrate.Value);
|
||||
Assert.Equal(dto.Genres!.Select(genre => genre.Name), metadata.Genres.Select(genre => genre.Name));
|
||||
@@ -77,7 +79,7 @@ public class MusicTrackMetadataDtoMappingTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults()
|
||||
public void ToDomainValueObject_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults()
|
||||
{
|
||||
// Arrange
|
||||
MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(
|
||||
@@ -123,7 +125,7 @@ public class MusicTrackMetadataDtoMappingTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone()
|
||||
public void ToDomainValueObject_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone()
|
||||
{
|
||||
// Arrange
|
||||
LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false);
|
||||
@@ -141,7 +143,7 @@ public class MusicTrackMetadataDtoMappingTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError()
|
||||
public void ToDomainValueObject_WhenReleaseInfoIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfoDto releaseInfo = _releaseInfoDtoFixture.Create(
|
||||
@@ -158,7 +160,7 @@ public class MusicTrackMetadataDtoMappingTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError()
|
||||
public void ToDomainValueObject_WhenGenreIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]);
|
||||
@@ -172,7 +174,7 @@ public class MusicTrackMetadataDtoMappingTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError()
|
||||
public void ToDomainValueObject_WhenTagIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
MusicTrackMetadataDto dto = _musicTrackMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]);
|
||||
|
||||
+16
@@ -74,6 +74,7 @@ public class TrackEntityMappingTests
|
||||
Assert.Equal(entity.Channels, track.Metadata.Channels);
|
||||
Assert.Equal(entity.BitDepth, track.Metadata.BitDepth.Value);
|
||||
Assert.Equal(entity.AudioCodec, track.Metadata.AudioCodec.Value);
|
||||
Assert.Equal(entity.Container, track.Metadata.Container.Value);
|
||||
Assert.Equal(entity.Bitrate, track.Metadata.Bitrate.Value);
|
||||
Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), track.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name));
|
||||
Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), track.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name));
|
||||
@@ -95,6 +96,20 @@ public class TrackEntityMappingTests
|
||||
Assert.Equal(entity.UpdatedOnUtc, track.UpdatedOnUtc.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTheEntityHasNoContainer_ShouldMapMetadataWithoutAContainer()
|
||||
{
|
||||
// Arrange
|
||||
TrackEntity entity = _trackEntityFixture.Create(includeContainer: false);
|
||||
|
||||
// Act
|
||||
Result<Track> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.Metadata.Container.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenReleaseDateAndYearDoNotMatch_ShouldReturnError()
|
||||
{
|
||||
@@ -226,6 +241,7 @@ public class TrackEntityMappingTests
|
||||
Assert.Equal(entity.Bitrate, result.Metadata.Bitrate);
|
||||
Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), result.Metadata.Tags!.Select(tag => tag.Name).OrderBy(name => name));
|
||||
Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), result.Metadata.Genres!.Select(genre => genre.Name).OrderBy(name => name));
|
||||
Assert.Equal(entity.Container, result.Container);
|
||||
Assert.Equal(entity.TrackNumber, result.TrackNumber);
|
||||
Assert.Equal(entity.DiscNumber, result.DiscNumber);
|
||||
Assert.Equal(entity.Script, result.Script);
|
||||
|
||||
+3
@@ -68,6 +68,7 @@ public class TrackMappingTests
|
||||
Assert.Equal(track.Metadata.Channels, result.Channels);
|
||||
Assert.Equal(track.Metadata.BitDepth.HasValue ? track.Metadata.BitDepth.Value : null, result.BitDepth);
|
||||
Assert.Equal(track.Metadata.AudioCodec.HasValue ? track.Metadata.AudioCodec.Value : null, result.AudioCodec);
|
||||
Assert.Equal(track.Metadata.Container.HasValue ? track.Metadata.Container.Value : null, result.Container);
|
||||
Assert.Equal(track.Metadata.Bitrate.HasValue ? track.Metadata.Bitrate.Value : null, result.Bitrate);
|
||||
Assert.Equal(track.TrackNumber, result.TrackNumber);
|
||||
Assert.Equal(track.DiscNumber.HasValue ? track.DiscNumber.Value : null, result.DiscNumber);
|
||||
@@ -134,6 +135,7 @@ public class TrackMappingTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
Track track = _trackFixture.Create(
|
||||
metadata: metadata,
|
||||
@@ -169,6 +171,7 @@ public class TrackMappingTests
|
||||
Assert.Null(result.OriginalLanguageNativeName);
|
||||
Assert.Null(result.BitDepth);
|
||||
Assert.Null(result.AudioCodec);
|
||||
Assert.Null(result.Container);
|
||||
Assert.Null(result.Bitrate);
|
||||
Assert.Null(result.DiscNumber);
|
||||
Assert.Null(result.Script);
|
||||
|
||||
+27
-1
@@ -286,6 +286,32 @@ public class UpdateTrackCommandMappingTests
|
||||
Assert.False(updatedTrack.Disambiguation.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTheMetadataCarriesNoContainer_ShouldKeepTheTrackContainer()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
(Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId);
|
||||
Track storedTrack = artist.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
|
||||
Optional<string> storedContainer = storedTrack.Metadata.Container;
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
artistId: artist.Id.Value.ToString(),
|
||||
albumId: albumId.ToString(),
|
||||
trackId: trackId.ToString());
|
||||
|
||||
// Act
|
||||
Result<Artist> result = command.ToDomainEntity(artist);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId);
|
||||
// The stored container is pinned to a known value, so the assertion cannot pass by coincidence.
|
||||
Assert.Equal("FLAC", storedContainer.Value);
|
||||
// The container is captured from the file itself and is never part of the edit metadata, so an update keeps the stored container.
|
||||
Assert.Equal("FLAC", updatedTrack.Metadata.Container.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
@@ -298,7 +324,7 @@ public class UpdateTrackCommandMappingTests
|
||||
AlbumEntity albumEntity = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
libraryId: libraryId,
|
||||
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]);
|
||||
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, container: "FLAC")]);
|
||||
ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]);
|
||||
Result<Artist> artistResult = artistEntity.ToDomainEntity();
|
||||
return (artistResult.Value, albumId, trackId);
|
||||
|
||||
+58
@@ -41,6 +41,7 @@ public class AudioMetadataTests
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<int>.Some(16),
|
||||
Optional<string>.Some("PCM"),
|
||||
Optional<string>.Some("WAV"),
|
||||
Optional<int>.Some(1411),
|
||||
Optional<string>.Some("f0e9c1a2-0000-0000-0000-000000000000"),
|
||||
Optional<decimal>.Some(-6.53m),
|
||||
@@ -57,6 +58,7 @@ public class AudioMetadataTests
|
||||
Assert.Equal("A song by the British rock band Queen.", result.Value.Description.Value);
|
||||
Assert.Equal(16, result.Value.BitDepth.Value);
|
||||
Assert.Equal("PCM", result.Value.AudioCodec.Value);
|
||||
Assert.Equal("WAV", result.Value.Container.Value);
|
||||
Assert.Equal(1411, result.Value.Bitrate.Value);
|
||||
Assert.Single(result.Value.Genres);
|
||||
Assert.Single(result.Value.Tags);
|
||||
@@ -80,6 +82,7 @@ public class AudioMetadataTests
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<decimal>.None(),
|
||||
@@ -91,6 +94,7 @@ public class AudioMetadataTests
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.BitDepth.HasValue);
|
||||
Assert.False(result.Value.AudioCodec.HasValue);
|
||||
Assert.False(result.Value.Container.HasValue);
|
||||
Assert.False(result.Value.Bitrate.HasValue);
|
||||
}
|
||||
|
||||
@@ -115,6 +119,7 @@ public class AudioMetadataTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
@@ -130,6 +135,7 @@ public class AudioMetadataTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
@@ -157,6 +163,7 @@ public class AudioMetadataTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
@@ -172,6 +179,7 @@ public class AudioMetadataTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
@@ -200,6 +208,7 @@ public class AudioMetadataTests
|
||||
Optional<LanguageInfo>.Some(originalLanguage),
|
||||
Optional<int>.Some(16),
|
||||
Optional<string>.Some("PCM"),
|
||||
Optional<string>.Some("WAV"),
|
||||
Optional<int>.Some(1411),
|
||||
Optional<string>.Some("f0e9c1a2-0000-0000-0000-000000000000"),
|
||||
Optional<decimal>.Some(-6.53m),
|
||||
@@ -237,6 +246,7 @@ public class AudioMetadataTests
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<decimal>.None(),
|
||||
@@ -271,6 +281,7 @@ public class AudioMetadataTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Love of My Life",
|
||||
@@ -286,6 +297,7 @@ public class AudioMetadataTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
@@ -334,6 +346,50 @@ public class AudioMetadataTests
|
||||
Assert.NotEqual(firstResult, secondResult);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentContainer_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AudioMetadata firstResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 355,
|
||||
sampleRate: 44100,
|
||||
channels: 2,
|
||||
releaseInfo: releaseInfo,
|
||||
description: Optional<string>.None(),
|
||||
genres: [],
|
||||
tags: [],
|
||||
language: Optional<LanguageInfo>.None(),
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.Some("MP3"),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 355,
|
||||
sampleRate: 44100,
|
||||
channels: 2,
|
||||
releaseInfo: releaseInfo,
|
||||
description: Optional<string>.None(),
|
||||
genres: [],
|
||||
tags: [],
|
||||
language: Optional<LanguageInfo>.None(),
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.Some("FLAC"),
|
||||
bitrate: Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstResult, secondResult);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentGenres_ShouldReturnFalse()
|
||||
{
|
||||
@@ -355,6 +411,7 @@ public class AudioMetadataTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
@@ -370,6 +427,7 @@ public class AudioMetadataTests
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
bitDepth: Optional<int>.None(),
|
||||
audioCodec: Optional<string>.None(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
|
||||
+56
@@ -239,6 +239,62 @@ public class TrackTests
|
||||
Assert.Equal(originalMoods, track.Moods);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenTheMetadataCarriesNoContainer_ShouldKeepTheStoredContainer()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
Optional<string> storedContainer = track.Metadata.Container;
|
||||
AudioMetadata metadata = _audioMetadataFixture.Create(container: Optional<string>.None());
|
||||
|
||||
// Act
|
||||
Result<Updated> result = track.UpdateDetails(
|
||||
metadata,
|
||||
track.Disambiguation,
|
||||
track.TrackNumber,
|
||||
track.DiscNumber,
|
||||
track.Script,
|
||||
track.Key,
|
||||
track.Bpm,
|
||||
track.IsVideo,
|
||||
track.Work,
|
||||
track.MusicBrainzRecordingId,
|
||||
track.MusicBrainzTrackId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The container is captured from the file itself and is never part of an edit, so an update that does not carry one keeps the stored container.
|
||||
Assert.Equal(storedContainer, track.Metadata.Container);
|
||||
// The rest of the metadata still comes from the update.
|
||||
Assert.Equal(metadata.Title, track.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenTheMetadataCarriesAContainer_ShouldReplaceTheStoredContainer()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
AudioMetadata metadata = _audioMetadataFixture.Create(container: Optional<string>.Some("OGG"));
|
||||
|
||||
// Act
|
||||
Result<Updated> result = track.UpdateDetails(
|
||||
metadata,
|
||||
track.Disambiguation,
|
||||
track.TrackNumber,
|
||||
track.DiscNumber,
|
||||
track.Script,
|
||||
track.Key,
|
||||
track.Bpm,
|
||||
track.IsVideo,
|
||||
track.Work,
|
||||
track.MusicBrainzRecordingId,
|
||||
track.MusicBrainzTrackId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("OGG", track.Metadata.Container.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAndCollectionsAreEmpty_ShouldCreateTrackWithoutThem()
|
||||
{
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioContainerResolver"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioContainerResolverTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(null, null)] // an absent mime type leaves the container unrecognized
|
||||
[InlineData("", null)] // an empty mime type leaves the container unrecognized
|
||||
[InlineData(" ", null)] // a blank mime type leaves the container unrecognized
|
||||
[InlineData("taglib/wav", "WAV")] // the taglib prefix is dropped and the container is upper cased
|
||||
[InlineData("taglib/png", "PNG")] // a container the resolver has no dedicated parser for still yields its name
|
||||
[InlineData("audio/x-wavpack", "X-WAVPACK")] // the last segment of a standard mime type names the container
|
||||
public void ResolveFromMimeType_WhenCalled_ShouldReturnTheContainerNamedByTheMimeType(string? mimeType, string? expectedContainer)
|
||||
{
|
||||
// Act
|
||||
string? container = AudioContainerResolver.ResolveFromMimeType(mimeType);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedContainer, container);
|
||||
}
|
||||
}
|
||||
+28
@@ -91,6 +91,34 @@ public class MusicMetadataAggregatorTests
|
||||
Assert.Equal(360, merged.DurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenTheFirstAudioMetadataHasAContainer_ShouldKeepTheFirstContainer()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto first = _audioMetadataDtoFixture.Create(container: "MP3");
|
||||
AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MP3", merged.Container);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenTheFirstAudioMetadataHasNoContainer_ShouldTakeTheSecondContainer()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto first = _audioMetadataDtoFixture.Create(includeContainer: false);
|
||||
AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("FLAC", merged.Container);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenTheFirstMetadataHasOnlyAReleaseYearAndTheSecondHasAReleaseDate_ShouldDeriveTheYearFromTheDate()
|
||||
{
|
||||
|
||||
+27
@@ -116,6 +116,33 @@ public class MusicMediaLibraryScanItemMaterializerTests
|
||||
AlbumEntity secondAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == secondReleaseId);
|
||||
Assert.Equal(firstRecordingId, Assert.Single(firstAlbum.Tracks).MusicBrainzRecordingId);
|
||||
Assert.Equal(secondRecordingId, Assert.Single(secondAlbum.Tracks).MusicBrainzRecordingId);
|
||||
// The container read from the file itself is carried from the staged metadata to the materialized track.
|
||||
Assert.Equal(firstStagedItem.Container, Assert.Single(firstAlbum.Tracks).Container);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenTheStagedItemHasNoContainer_ShouldMaterializeTheTrackWithoutAContainer()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryScanItemMetadataEntity stagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Some Artist",
|
||||
releaseName: "Some Release",
|
||||
path: "/music/some-artist/some-release/track.mp3",
|
||||
includeMusicBrainzTags: false,
|
||||
includeContainer: false);
|
||||
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([stagedItem]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [stagedItem.Path], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
ArtistEntity artist = Assert.Single(_insertedArtists);
|
||||
AlbumEntity album = Assert.Single(artist.Albums);
|
||||
// A file whose container the scan could not recognize materializes its track without a container, rather than failing the scan.
|
||||
Assert.Null(Assert.Single(album.Tracks).Container);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.ID3.Core.Tags;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.ID3.UnitTests.Core.Tags;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioContainerResolver"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioContainerResolverTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(null, null)] // an absent mime type leaves the container unrecognized
|
||||
[InlineData("", null)] // an empty mime type leaves the container unrecognized
|
||||
[InlineData(" ", null)] // a blank mime type leaves the container unrecognized
|
||||
[InlineData("taglib/wav", "WAV")] // the taglib prefix is dropped and the container is upper cased
|
||||
[InlineData("taglib/png", "PNG")] // a container the resolver has no dedicated parser for still yields its name
|
||||
[InlineData("audio/x-wavpack", "X-WAVPACK")] // the last segment of a standard mime type names the container
|
||||
public void ResolveFromMimeType_WhenCalled_ShouldReturnTheContainerNamedByTheMimeType(string? mimeType, string? expectedContainer)
|
||||
{
|
||||
// Act
|
||||
string? container = AudioContainerResolver.ResolveFromMimeType(mimeType);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedContainer, container);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user