From 1ffa14cec44ce693cbaafaeb75d8d0674fc80176 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 30 Sep 2026 12:00:00 +0300 Subject: [PATCH] Adds the ID3 music metadata plugin and its unit and integration test suites --- .../Common/DependencyInjection/Id3Services.cs | 38 + .../Common/Models/DTO/Tags/Id3TagDto.cs | 258 ++++ .../Core/Id3AlbumMetadataProvider.cs | 87 ++ .../Core/Id3ArtistMetadataProvider.cs | 87 ++ plugins/Lumina.Plugins.ID3/Core/Id3Plugin.cs | 64 + .../Core/Id3TrackMetadataProvider.cs | 87 ++ .../Core/Mapping/Id3TagMapper.cs | 644 +++++++++ .../Core/Tags/Id3TagReader.cs | 434 ++++++ .../Lumina.Plugins.ID3.csproj | 35 + .../Properties/AssemblyInfo.cs | 6 + .../Models/DTO/Tags/Id3TagDtoFixture.cs | 253 ++++ .../Core/Tags/TestAudioFileFactory.cs | 124 ++ .../Lumina.Plugins.ID3.Fixtures.csproj | 27 + .../Properties/AssemblyInfo.cs | 21 + .../Core/Id3AlbumMetadataProviderTests.cs | 102 ++ .../Core/Id3ArtistMetadataProviderTests.cs | 100 ++ .../Core/Id3TrackMetadataProviderTests.cs | 103 ++ .../Core/Tags/Id3TagReaderTests.cs | 480 ++++++ ...Lumina.Plugins.ID3.IntegrationTests.csproj | 49 + .../DependencyInjection/Id3ServicesTests.cs | 74 + .../Core/Id3AlbumMetadataProviderTests.cs | 83 ++ .../Core/Id3ArtistMetadataProviderTests.cs | 83 ++ .../Core/Id3PluginTests.cs | 112 ++ .../Core/Id3TrackMetadataProviderTests.cs | 83 ++ .../Core/Mapping/Id3TagMapperTests.cs | 1286 +++++++++++++++++ .../Core/Tags/Id3TagReaderTests.cs | 73 + .../Lumina.Plugins.ID3.UnitTests.csproj | 49 + 27 files changed, 4842 insertions(+) create mode 100644 plugins/Lumina.Plugins.ID3/Common/DependencyInjection/Id3Services.cs create mode 100644 plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs create mode 100644 plugins/Lumina.Plugins.ID3/Core/Id3AlbumMetadataProvider.cs create mode 100644 plugins/Lumina.Plugins.ID3/Core/Id3ArtistMetadataProvider.cs create mode 100644 plugins/Lumina.Plugins.ID3/Core/Id3Plugin.cs create mode 100644 plugins/Lumina.Plugins.ID3/Core/Id3TrackMetadataProvider.cs create mode 100644 plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs create mode 100644 plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs create mode 100644 plugins/Lumina.Plugins.ID3/Lumina.Plugins.ID3.csproj create mode 100644 plugins/Lumina.Plugins.ID3/Properties/AssemblyInfo.cs create mode 100644 tests/Common/Lumina.Plugins.ID3.Fixtures/Common/Models/DTO/Tags/Id3TagDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.ID3.Fixtures/Core/Tags/TestAudioFileFactory.cs create mode 100644 tests/Common/Lumina.Plugins.ID3.Fixtures/Lumina.Plugins.ID3.Fixtures.csproj create mode 100644 tests/Common/Lumina.Plugins.ID3.Fixtures/Properties/AssemblyInfo.cs create mode 100644 tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3AlbumMetadataProviderTests.cs create mode 100644 tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3ArtistMetadataProviderTests.cs create mode 100644 tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs create mode 100644 tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs create mode 100644 tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Lumina.Plugins.ID3.IntegrationTests.csproj create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Common/DependencyInjection/Id3ServicesTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3AlbumMetadataProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3ArtistMetadataProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3PluginTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3TrackMetadataProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Mapping/Id3TagMapperTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/Id3TagReaderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Lumina.Plugins.ID3.UnitTests.csproj diff --git a/plugins/Lumina.Plugins.ID3/Common/DependencyInjection/Id3Services.cs b/plugins/Lumina.Plugins.ID3/Common/DependencyInjection/Id3Services.cs new file mode 100644 index 00000000..6b7ab3cc --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Common/DependencyInjection/Id3Services.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +#endregion + +namespace Lumina.Plugins.ID3.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the ID3 metadata provider into the Dependency Injection container. +/// +internal static class Id3Services +{ + /// + /// Registers the services of the ID3 metadata providers into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the metadata. + /// The updated . + internal static IServiceCollection AddId3MetadataProviders(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // The reader is scoped, so that the tags of a single file are read only once across the artist, album and track providers of the same enrichment scope. + services.TryAddScoped(); + + // Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations. + // A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair. + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs b/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs new file mode 100644 index 00000000..02897507 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Common/Models/DTO/Tags/Id3TagDto.cs @@ -0,0 +1,258 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.ID3.Common.Models.DTO.Tags; + +/// +/// Snapshot of the metadata read from the embedded tags of a single audio file. +/// Every audio property that the tags do not carry is left empty, so that the local values already extracted from the file are never overwritten with blanks. +/// +internal sealed class Id3TagDto +{ + /// + /// Gets or initializes the title of the track. + /// + public string? Title { get; init; } + + /// + /// Gets or initializes the title of the album the track belongs to. + /// + public string? Album { get; init; } + + /// + /// Gets or initializes the artists credited on the track. + /// + public List TrackArtists { get; init; } = []; + + /// + /// Gets or initializes the artists credited on the album. + /// + public List AlbumArtists { get; init; } = []; + + /// + /// Gets or initializes the sort name of the album artist. + /// + public string? AlbumArtistSortName { get; init; } + + /// + /// Gets or initializes the sort name of the track artist. + /// + public string? TrackArtistSortName { get; init; } + + /// + /// Gets or initializes the number of the track on its disc. + /// + public uint TrackNumber { get; init; } + + /// + /// Gets or initializes the number of tracks on the disc, as reported by the tags. + /// + public uint TrackCount { get; init; } + + /// + /// Gets or initializes the number of the disc the track belongs to. + /// + public uint DiscNumber { get; init; } + + /// + /// Gets or initializes the number of discs of the release, as reported by the tags. + /// + public uint DiscCount { get; init; } + + /// + /// Gets or initializes the year the track was released. + /// + public int? Year { get; init; } + + /// + /// Gets or initializes the original release date of the track. + /// + public DateOnly? OriginalReleaseDate { get; init; } + + /// + /// Gets or initializes the original release year of the track. + /// + public int? OriginalReleaseYear { get; init; } + + /// + /// Gets or initializes the genres the tags associate with the track. + /// + public List Genres { get; init; } = []; + + /// + /// Gets or initializes the composers credited on the track. + /// + public List Composers { get; init; } = []; + + /// + /// Gets or initializes the lyricists credited on the track. + /// + public List Lyricists { get; init; } = []; + + /// + /// Gets or initializes the conductors credited on the track. + /// + public List Conductors { get; init; } = []; + + /// + /// Gets or initializes the remixers credited on the track. + /// + public List Remixers { get; init; } = []; + + /// + /// Gets or initializes the people credited on the track, each with the free-form role read from the tags. + /// + public List<(string Role, string Name)> InvolvedPeople { get; init; } = []; + + /// + /// Gets or initializes the language of the track. + /// + public string? Language { get; init; } + + /// + /// Gets or initializes the script used by the language of the track. + /// + public string? Script { get; init; } + + /// + /// Gets or initializes the label that issued the album. + /// + public string? Label { get; init; } + + /// + /// Gets or initializes the catalog numbers of the album. + /// + public List CatalogNumbers { get; init; } = []; + + /// + /// Gets or initializes the barcode of the album. + /// + public string? Barcode { get; init; } + + /// + /// Gets or initializes the types of the release, as read from the tags. + /// + public List ReleaseTypes { get; init; } = []; + + /// + /// Gets or initializes the status of the release. + /// + public string? ReleaseStatus { get; init; } + + /// + /// Gets or initializes the country the release was issued in. + /// + public string? ReleaseCountry { get; init; } + + /// + /// Gets or initializes the physical or digital medium of the release. + /// + public string? MediaFormat { get; init; } + + /// + /// Gets or initializes the outermost packaging of the release. + /// + public string? Packaging { get; init; } + + /// + /// Gets or initializes the ASIN of the album. + /// + public string? Asin { get; init; } + + /// + /// Gets or initializes the ISRCs of the track. + /// + public List Isrcs { get; init; } = []; + + /// + /// Gets or initializes the moods of the track. + /// + public List Moods { get; init; } = []; + + /// + /// Gets or initializes the title of the work the track is a recording of. + /// + public string? WorkTitle { get; init; } + + /// + /// Gets or initializes the musical key of the track. + /// + public string? MusicKey { get; init; } + + /// + /// Gets or initializes the tempo of the track in beats per minute. + /// + public int? Bpm { get; init; } + + /// + /// Gets or initializes the duration of the audio of the track in seconds. + /// + public int? DurationInSeconds { get; init; } + + /// + /// Gets or initializes the sample rate of the audio of the track in Hz. + /// + public int? SampleRate { get; init; } + + /// + /// Gets or initializes the number of audio channels of the track. + /// + public int? Channels { get; init; } + + /// + /// Gets or initializes the bit depth of the audio of the track. + /// + public int? BitDepth { get; init; } + + /// + /// Gets or initializes the bitrate of the audio of the track in kbps. + /// + public int? Bitrate { get; init; } + + /// + /// Gets or initializes the description of the audio codec of the track. + /// + public string? AudioCodec { get; init; } + + /// + /// Gets or initializes the official website associated with the artist. + /// + public string? Website { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the artist. + /// + public string? MusicBrainzArtistId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the release artist. + /// + public string? MusicBrainzReleaseArtistId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the release group. + /// + public string? MusicBrainzReleaseGroupId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the release. + /// + public string? MusicBrainzReleaseId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the recording of the track. + /// + public string? MusicBrainzRecordingId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the track on its release. + /// + public string? MusicBrainzReleaseTrackId { get; init; } + + /// + /// Gets or initializes the MusicBrainz identifier of the work the track is a recording of. + /// + public string? MusicBrainzWorkId { get; init; } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Id3AlbumMetadataProvider.cs b/plugins/Lumina.Plugins.ID3/Core/Id3AlbumMetadataProvider.cs new file mode 100644 index 00000000..4dba963f --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Id3AlbumMetadataProvider.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Mapping; +using Lumina.Plugins.ID3.Core.Tags; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.Core; + +/// +/// Provides album metadata from the embedded tags of one of its audio files, by resolving lookups into album metadata DTOs. +/// +internal sealed class Id3AlbumMetadataProvider : IMetadataProvider +{ + private readonly Id3TagReader _tagReader; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "ID3"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => false; + + /// + /// Initializes a new instance of the class. + /// + /// The reader of the embedded tags of the audio files. + public Id3AlbumMetadataProvider(Id3TagReader tagReader) + { + _tagReader = tagReader; + } + + /// + /// Searches for the metadata of the album described by . + /// + /// The lookup describing the album to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of album metadata candidates found, which for embedded tags is at most the file of the lookup. + public async Task> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + AlbumMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false); + IReadOnlyList results = metadata is null ? [] : [metadata]; + return results; + } + + /// + /// Gets the metadata of the album described by . + /// + /// The lookup describing the album to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the album, or when the file carries none. + public Task GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + return ReadMetadataAsync(lookup.Path, cancellationToken); + } + + /// + /// Reads the metadata of the album from the embedded tags of the track stored at . + /// + /// The file system path of a track of the album. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the album, or when the tags carry no album title. + private Task ReadMetadataAsync(string path, CancellationToken cancellationToken) + { + // The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file. + return Task.Run(() => + { + Id3TagDto? data = _tagReader.Read(path); + if (data is null || string.IsNullOrWhiteSpace(data.Album)) + return null; + return Id3TagMapper.MapAlbum(data); + }, cancellationToken); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Id3ArtistMetadataProvider.cs b/plugins/Lumina.Plugins.ID3/Core/Id3ArtistMetadataProvider.cs new file mode 100644 index 00000000..c0a34ad0 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Id3ArtistMetadataProvider.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Mapping; +using Lumina.Plugins.ID3.Core.Tags; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.Core; + +/// +/// Provides music artist metadata from the embedded tags of one of its audio files, by resolving lookups into artist metadata DTOs. +/// +internal sealed class Id3ArtistMetadataProvider : IMetadataProvider +{ + private readonly Id3TagReader _tagReader; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "ID3"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => false; + + /// + /// Initializes a new instance of the class. + /// + /// The reader of the embedded tags of the audio files. + public Id3ArtistMetadataProvider(Id3TagReader tagReader) + { + _tagReader = tagReader; + } + + /// + /// Searches for the metadata of the artist described by . + /// + /// The lookup describing the artist to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of artist metadata candidates found, which for embedded tags is at most the file of the lookup. + public async Task> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + ArtistMetadataDto? metadata = await ReadMetadataAsync(lookup, cancellationToken).ConfigureAwait(false); + IReadOnlyList results = metadata is null ? [] : [metadata]; + return results; + } + + /// + /// Gets the metadata of the artist described by . + /// + /// The lookup describing the artist to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the artist, or when the file carries none. + public Task GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + return ReadMetadataAsync(lookup, cancellationToken); + } + + /// + /// Reads the metadata of the artist described by from the embedded tags of the track stored at its path. + /// + /// The lookup describing the artist. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the artist, or when the tags carry no artist name. + private Task ReadMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + // The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file. + return Task.Run(() => + { + Id3TagDto? data = _tagReader.Read(lookup.Path); + if (data is null || (data.AlbumArtists.Count == 0 && data.TrackArtists.Count == 0)) + return null; + return Id3TagMapper.MapArtist(data, lookup.Name); + }, cancellationToken); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Id3Plugin.cs b/plugins/Lumina.Plugins.ID3/Core/Id3Plugin.cs new file mode 100644 index 00000000..1492df15 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Id3Plugin.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.ID3.Common.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.ID3.Core; + +/// +/// Plugin that populates music metadata exclusively from the embedded tags of the audio files, without accessing the web. +/// +public sealed class Id3Plugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("a3f1c8d2-6b47-4e9a-8c15-2d7f9e4b6a03"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "ID3 Metadata"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Populates artist, album and track metadata from the embedded tags of the audio files, without accessing the web."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return []; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddId3MetadataProviders(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Id3TrackMetadataProvider.cs b/plugins/Lumina.Plugins.ID3/Core/Id3TrackMetadataProvider.cs new file mode 100644 index 00000000..da604fcc --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Id3TrackMetadataProvider.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Mapping; +using Lumina.Plugins.ID3.Core.Tags; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.Core; + +/// +/// Provides track metadata from the embedded tags of the audio file, by resolving lookups into audio metadata DTOs. +/// +internal sealed class Id3TrackMetadataProvider : IMetadataProvider +{ + private readonly Id3TagReader _tagReader; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "ID3"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => false; + + /// + /// Initializes a new instance of the class. + /// + /// The reader of the embedded tags of the audio files. + public Id3TrackMetadataProvider(Id3TagReader tagReader) + { + _tagReader = tagReader; + } + + /// + /// Searches for the metadata of the track described by . + /// + /// The lookup describing the track to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of track metadata candidates found, which for embedded tags is at most the file of the lookup. + public async Task> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + AudioMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false); + IReadOnlyList results = metadata is null ? [] : [metadata]; + return results; + } + + /// + /// Gets the metadata of the track described by . + /// + /// The lookup describing the track to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the track, or when the file carries none. + public Task GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + return ReadMetadataAsync(lookup.Path, cancellationToken); + } + + /// + /// Reads the metadata of the track stored at from its embedded tags. + /// + /// The file system path of the track. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the track, or when the tags carry no title. + private Task ReadMetadataAsync(string path, CancellationToken cancellationToken) + { + // The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file. + return Task.Run(() => + { + Id3TagDto? data = _tagReader.Read(path); + if (data is null || string.IsNullOrWhiteSpace(data.Title)) + return null; + return Id3TagMapper.MapTrack(data); + }, cancellationToken); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs b/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs new file mode 100644 index 00000000..df197b9a --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Mapping/Id3TagMapper.cs @@ -0,0 +1,644 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.Core.Mapping; + +/// +/// Maps the metadata read from the embedded tags of an audio file into the application's media metadata DTOs. +/// +internal static class Id3TagMapper +{ + /// + /// The neutral cultures of the application, keyed by both their two letter and three letter language codes, so that a language code is resolved without enumerating the cultures of the system for every mapped file. + /// + private static readonly Dictionary s_culturesByLanguageCode = BuildCulturesByLanguageCode(); + + /// + /// Builds the map of the neutral cultures of the application, keyed by their language codes. + /// + /// The cultures, keyed by both their two letter and three letter language codes. + private static Dictionary BuildCulturesByLanguageCode() + { + Dictionary cultures = new(StringComparer.OrdinalIgnoreCase); + foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) + { + if (culture.ThreeLetterISOLanguageName.Length == 3 && !cultures.ContainsKey(culture.ThreeLetterISOLanguageName)) + cultures[culture.ThreeLetterISOLanguageName] = culture; + if (culture.TwoLetterISOLanguageName.Length == 2 && !cultures.ContainsKey(culture.TwoLetterISOLanguageName)) + cultures[culture.TwoLetterISOLanguageName] = culture; + } + return cultures; + } + + /// + /// Maps the tags of an audio file into artist metadata. + /// + /// The tags of a track of the artist. + /// The name of the artist the metadata is mapped for, when known, used to select the matching credited artist. + /// The mapped artist metadata. + public static ArtistMetadataDto MapArtist(Id3TagDto data, string? artistName) + { + bool doesMatchTrackArtist = !string.IsNullOrWhiteSpace(artistName) && data.TrackArtists.Any(artist => string.Equals(artist, artistName, StringComparison.OrdinalIgnoreCase)); + bool doesMatchAlbumArtist = !string.IsNullOrWhiteSpace(artistName) && data.AlbumArtists.Any(artist => string.Equals(artist, artistName, StringComparison.OrdinalIgnoreCase)); + + string? mappedName; + string? mappedSortName; + Guid? musicBrainzArtistId; + if (doesMatchTrackArtist) + { + mappedName = NullIfWhiteSpace(artistName); + mappedSortName = data.TrackArtistSortName ?? data.AlbumArtistSortName; + musicBrainzArtistId = ParseGuid(data.MusicBrainzArtistId) ?? ParseGuid(data.MusicBrainzReleaseArtistId); + } + else if (doesMatchAlbumArtist) + { + mappedName = NullIfWhiteSpace(artistName); + mappedSortName = data.AlbumArtistSortName ?? data.TrackArtistSortName; + musicBrainzArtistId = ParseGuid(data.MusicBrainzReleaseArtistId) ?? ParseGuid(data.MusicBrainzArtistId); + } + else + { + mappedName = NullIfWhiteSpace(data.AlbumArtists.FirstOrDefault()) ?? NullIfWhiteSpace(data.TrackArtists.FirstOrDefault()); + mappedSortName = data.AlbumArtistSortName ?? data.TrackArtistSortName; + musicBrainzArtistId = ParseGuid(data.MusicBrainzArtistId) ?? ParseGuid(data.MusicBrainzReleaseArtistId); + } + + return new ArtistMetadataDto( + Name: mappedName, + SortName: mappedSortName, + Disambiguation: null, + Type: null, + Gender: null, + Country: null, + Area: null, + BeginArea: null, + EndArea: null, + LifeSpanBegin: null, + LifeSpanEnd: null, + IsEnded: false, + Website: data.Website, + MusicBrainzArtistId: musicBrainzArtistId, + Ipis: null, + Isnis: null, + Aliases: null, + Genres: null, + Tags: null, + Ratings: null, + Contributors: null); + } + + /// + /// Maps the tags of an audio file into album metadata. + /// + /// The tags of a track of the album. + /// The mapped album metadata. + public static AlbumMetadataDto MapAlbum(Id3TagDto data) + { + return new AlbumMetadataDto( + Title: NullIfWhiteSpace(data.Album), + OriginalTitle: null, + Description: null, + Disambiguation: null, + ReleaseInfo: BuildReleaseInfo(data), + Language: MapLanguage(data.Language), + OriginalLanguage: null, + Tags: null, + Genres: MapGenres(data.Genres), + Script: NullIfWhiteSpace(data.Script), + ReleaseTypes: MapReleaseTypes(data.ReleaseTypes), + ReleaseStatus: MapReleaseStatus(data.ReleaseStatus), + MediaFormat: MapMediaFormat(data.MediaFormat), + Packaging: MapPackaging(data.Packaging), + TotalDiscs: data.DiscCount > 0 ? (int)data.DiscCount : null, + TotalTracks: data.TrackCount > 0 ? (int)data.TrackCount : null, + Barcode: NullIfWhiteSpace(data.Barcode), + CatalogNumbers: data.CatalogNumbers.Count > 0 ? [.. data.CatalogNumbers] : null, + Label: NullIfWhiteSpace(data.Label), + ASIN: NullIfWhiteSpace(data.Asin), + MusicBrainzReleaseId: ParseGuid(data.MusicBrainzReleaseId), + MusicBrainzReleaseGroupId: ParseGuid(data.MusicBrainzReleaseGroupId), + MusicBrainzReleaseArtistId: ParseGuid(data.MusicBrainzReleaseArtistId), + Contributors: MapAlbumContributors(data), + Ratings: null, + ReleaseTitle: null); + } + + /// + /// Maps the tags of an audio file into track metadata. + /// + /// The tags of the track. + /// The mapped track metadata. + public static AudioMetadataDto MapTrack(Id3TagDto data) + { + return new AudioMetadataDto( + Title: NullIfWhiteSpace(data.Title), + OriginalTitle: null, + Description: null, + Disambiguation: null, + ReleaseInfo: BuildReleaseInfo(data), + Language: MapLanguage(data.Language), + OriginalLanguage: null, + Tags: null, + Genres: MapGenres(data.Genres), + Script: NullIfWhiteSpace(data.Script), + Key: MapKey(data.MusicKey), + Bpm: data.Bpm, + IsVideo: false, + Work: MapWork(data), + Isrcs: MapIsrcs(data.Isrcs), + Moods: MapMoods(data.Moods), + DurationInSeconds: data.DurationInSeconds, + SampleRate: data.SampleRate, + Channels: data.Channels, + BitDepth: data.BitDepth, + AudioCodec: NullIfWhiteSpace(data.AudioCodec), + Bitrate: data.Bitrate, + MusicBrainzRecordingId: ParseGuid(data.MusicBrainzRecordingId), + MusicBrainzTrackId: ParseGuid(data.MusicBrainzReleaseTrackId), + Contributors: MapTrackContributors(data), + Ratings: null); + } + + /// + /// Builds the release information of the metadata from the tags, or when the tags carry none of it. + /// + /// The tags of the track. + /// The release information, or when the tags carry no release field. + private static ReleaseInfoDto? BuildReleaseInfo(Id3TagDto data) + { + ReleaseCountry? releaseCountry = MapReleaseCountry(data.ReleaseCountry); + if (data.OriginalReleaseDate is null && data.OriginalReleaseYear is null && releaseCountry is null) + return null; + + return new ReleaseInfoDto( + OriginalReleaseDate: data.OriginalReleaseDate, + OriginalReleaseYear: data.OriginalReleaseYear, + ReReleaseDate: null, + ReReleaseYear: null, + ReleaseCountry: releaseCountry, + ReleaseVersion: null); + } + + /// + /// Maps the work of the track, or when the tags carry none. + /// + /// The tags of the track. + /// The mapped work, or . + private static MusicWorkDto? MapWork(Id3TagDto data) + { + Guid? workId = ParseFirstGuid(data.MusicBrainzWorkId); + string? workTitle = FirstValue(data.WorkTitle); + // The work is only mapped when both its identifier and its title are known, because the domain requires both and would otherwise reject the whole track. + if (workId is null || string.IsNullOrWhiteSpace(workTitle)) + return null; + return new MusicWorkDto( + MusicBrainzWorkId: workId, + Title: workTitle, + Type: null, + Languages: null, + Iswcs: null); + } + + /// + /// Maps the contributors credited on the track, each with its canonical role. + /// + /// The tags of the track. + /// The mapped contributors, or when the tags credit none. + private static List? MapTrackContributors(Id3TagDto data) + { + List contributors = []; + foreach (string artist in data.TrackArtists) + AddContributor(contributors, artist, MediaContributorRole.Performer); + foreach (string composer in data.Composers) + AddContributor(contributors, composer, MediaContributorRole.Composer); + foreach (string lyricist in data.Lyricists) + AddContributor(contributors, lyricist, MediaContributorRole.Lyricist); + foreach (string conductor in data.Conductors) + AddContributor(contributors, conductor, MediaContributorRole.Conductor); + foreach (string remixer in data.Remixers) + AddContributor(contributors, remixer, MediaContributorRole.Remixer); + foreach ((string role, string name) in data.InvolvedPeople) + AddContributor(contributors, name, MapRole(role)); + + return contributors.Count > 0 ? contributors : null; + } + + /// + /// Maps the contributors credited on the album, which the tags only expose as the album artists. + /// + /// The tags of a track of the album. + /// The mapped contributors, or when the tags credit none. + private static List? MapAlbumContributors(Id3TagDto data) + { + List artists = data.AlbumArtists.Count > 0 ? data.AlbumArtists : data.TrackArtists; + List contributors = []; + foreach (string artist in artists) + AddContributor(contributors, artist, MediaContributorRole.Performer); + return contributors.Count > 0 ? contributors : null; + } + + /// + /// Maps the genres of the metadata, without duplicates. + /// + /// The genre names read from the tags. + /// The mapped genres, or when there are none. + private static List? MapGenres(List genres) + { + List result = [.. genres + .Where(genre => !string.IsNullOrWhiteSpace(genre)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(genre => new GenreDto(genre))]; + return result.Count > 0 ? result : null; + } + + /// + /// Maps the moods of the metadata, without duplicates. + /// + /// The mood names read from the tags. + /// The mapped moods, or when there are none. + private static List? MapMoods(List moods) + { + List result = [.. moods + .Where(mood => !string.IsNullOrWhiteSpace(mood)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(mood => new MoodDto(mood))]; + return result.Count > 0 ? result : null; + } + + /// + /// Maps the ISRCs of the track, without duplicates. + /// + /// The ISRC values read from the tags. + /// The mapped ISRCs, or when there are none. + private static List? MapIsrcs(List isrcs) + { + List result = [.. isrcs + .Where(isrc => !string.IsNullOrWhiteSpace(isrc)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(isrc => new IsrcDto(isrc))]; + return result.Count > 0 ? result : null; + } + + /// + /// Maps the types of the release into the application enum, without duplicates. + /// + /// The free-form release types read from the tags. + /// The mapped release types, or when there are none. + private static List? MapReleaseTypes(List releaseTypes) + { + List result = []; + foreach (string releaseType in releaseTypes) + { + MusicReleaseType? mapped = MapReleaseType(releaseType); + if (mapped is not null && !result.Contains(mapped.Value)) + result.Add(mapped.Value); + } + return result.Count > 0 ? result : null; + } + + /// + /// Maps a single free-form release type into the application enum. + /// + /// The release type to map. + /// The mapped release type, or when the type is unknown. + private static MusicReleaseType? MapReleaseType(string? releaseType) + { + if (string.IsNullOrWhiteSpace(releaseType)) + return null; + return releaseType.Trim().ToLowerInvariant() switch + { + "album" => MusicReleaseType.Album, + "single" => MusicReleaseType.Single, + "ep" => MusicReleaseType.Ep, + "broadcast" => MusicReleaseType.Broadcast, + "other" => MusicReleaseType.Other, + "compilation" => MusicReleaseType.Compilation, + "live" => MusicReleaseType.Live, + "soundtrack" => MusicReleaseType.Soundtrack, + "spokenword" => MusicReleaseType.SpokenWord, + "audio drama" => MusicReleaseType.AudioDrama, + "audiobook" => MusicReleaseType.AudioBook, + "demo" => MusicReleaseType.Demo, + "dj-mix" => MusicReleaseType.DjMix, + "field recording" => MusicReleaseType.FieldRecording, + "interview" => MusicReleaseType.Interview, + "mixtape/street" => MusicReleaseType.Mixtape, + "remix" => MusicReleaseType.Remix, + _ => null + }; + } + + /// + /// Maps a free-form release status into the application enum. + /// + /// The release status to map. + /// The mapped release status, or when the status is unknown. + private static MusicReleaseStatus? MapReleaseStatus(string? releaseStatus) + { + if (string.IsNullOrWhiteSpace(releaseStatus)) + return null; + return releaseStatus.Trim().ToLowerInvariant() switch + { + "official" => MusicReleaseStatus.Official, + "promotion" => MusicReleaseStatus.Promotion, + "bootleg" => MusicReleaseStatus.Bootleg, + "pseudo-release" => MusicReleaseStatus.PseudoRelease, + "withdrawn" => MusicReleaseStatus.Withdrawn, + "cancelled" => MusicReleaseStatus.Cancelled, + "expunged" => MusicReleaseStatus.Expunged, + _ => null + }; + } + + /// + /// Maps an ISO 3166-1 alpha-2 country code into the application enum. + /// + /// The country code to map. + /// The mapped release country, or when the code is unknown. + private static ReleaseCountry? MapReleaseCountry(string? country) + { + if (string.IsNullOrWhiteSpace(country)) + return null; + return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null; + } + + /// + /// Maps a free-form media format into the application enum. + /// + /// The media format to map. + /// The mapped media format, or when the format is unknown. + private static MusicMediaFormat? MapMediaFormat(string? mediaFormat) + { + if (string.IsNullOrWhiteSpace(mediaFormat)) + return null; + + string value = mediaFormat.Trim().ToLowerInvariant(); + MusicMediaFormat? mapped = value switch + { + "12\" vinyl" => MusicMediaFormat.Inch12Vinyl, + "10\" vinyl" => MusicMediaFormat.Inch10Vinyl, + "7\" vinyl" => MusicMediaFormat.Inch7Vinyl, + "3\" vinyl" => MusicMediaFormat.Inch3Vinyl, + "vinyl" => MusicMediaFormat.Vinyl, + "cd" => MusicMediaFormat.CD, + "sacd" => MusicMediaFormat.SACD, + "hybrid sacd" => MusicMediaFormat.HybridSACD, + "digital media" => MusicMediaFormat.DigitalMedia, + "cassette" => MusicMediaFormat.Cassette, + "dvd" => MusicMediaFormat.DVD, + "dvd-video" => MusicMediaFormat.DVDVideo, + "dvd-audio" => MusicMediaFormat.DVDAudio, + "blu-ray" => MusicMediaFormat.BluRay, + "minidisc" => MusicMediaFormat.MiniDisc, + "8cm cd" => MusicMediaFormat.Cm8CD, + "dat" => MusicMediaFormat.DAT, + "vinyl disc" => MusicMediaFormat.VinylDisc, + "other" => MusicMediaFormat.Other, + _ => null + }; + if (mapped is not null) + return mapped; + + // Fall back to a direct parse for the values whose free-form name already matches an enum member, ignoring the separators. + string normalized = value.Replace("\"", string.Empty, StringComparison.Ordinal).Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal); + return Enum.TryParse(normalized, ignoreCase: true, out MusicMediaFormat parsed) ? parsed : null; + } + + /// + /// Maps a free-form packaging into the application enum. + /// + /// The packaging to map. + /// The mapped packaging, or when the packaging is unknown. + private static MusicReleasePackaging? MapPackaging(string? packaging) + { + if (string.IsNullOrWhiteSpace(packaging)) + return null; + + string value = packaging.Trim().ToLowerInvariant().Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal).Replace("/", string.Empty, StringComparison.Ordinal); + return Enum.TryParse(value, ignoreCase: true, out MusicReleasePackaging parsed) ? parsed : null; + } + + /// + /// Maps a free-form musical key into the application enum. + /// + /// The musical key to map. + /// The mapped musical key, or when the key is unknown. + private static MusicKey? MapKey(string? musicKey) + { + if (string.IsNullOrWhiteSpace(musicKey)) + return null; + + string value = musicKey.Trim(); + bool isMinor = false; + if (value.EndsWith("minor", StringComparison.OrdinalIgnoreCase)) + { + isMinor = true; + value = value[..^5]; + } + else if (value.EndsWith("major", StringComparison.OrdinalIgnoreCase)) + value = value[..^5]; + else if (value.EndsWith("min", StringComparison.OrdinalIgnoreCase)) + { + isMinor = true; + value = value[..^3]; + } + else if (value.EndsWith("maj", StringComparison.OrdinalIgnoreCase)) + value = value[..^3]; + else if (value.EndsWith("m", StringComparison.OrdinalIgnoreCase)) + { + isMinor = true; + value = value[..^1]; + } + + value = value.Trim().ToUpperInvariant().Replace("\u266f", "#", StringComparison.Ordinal).Replace("\u266d", "B", StringComparison.Ordinal); + return value switch + { + "C" => isMinor ? MusicKey.CMinor : MusicKey.CMajor, + "C#" or "DB" => isMinor ? MusicKey.CSharpMinor : MusicKey.CSharpMajor, + "D" => isMinor ? MusicKey.DMinor : MusicKey.DMajor, + "D#" or "EB" => isMinor ? MusicKey.DSharpMinor : MusicKey.DSharpMajor, + "E" => isMinor ? MusicKey.EMinor : MusicKey.EMajor, + "F" => isMinor ? MusicKey.FMinor : MusicKey.FMajor, + "F#" or "GB" => isMinor ? MusicKey.FSharpMinor : MusicKey.FSharpMajor, + "G" => isMinor ? MusicKey.GMinor : MusicKey.GMajor, + "G#" or "AB" => isMinor ? MusicKey.GSharpMinor : MusicKey.GSharpMajor, + "A" => isMinor ? MusicKey.AMinor : MusicKey.AMajor, + "A#" or "BB" => isMinor ? MusicKey.ASharpMinor : MusicKey.ASharpMajor, + "B" => isMinor ? MusicKey.BMinor : MusicKey.BMajor, + _ => null + }; + } + + /// + /// Maps a free-form ISO 639 language code into language information. + /// + /// The code to map. + /// The mapped language, or when the code is empty. + private static LanguageInfoDto? MapLanguage(string? rawCode) + { + if (string.IsNullOrWhiteSpace(rawCode)) + return null; + + string code = rawCode.Trim().ToLowerInvariant(); + // A language code can list several languages, such as "eng/ara"; the first one is the language of the release. + string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code; + + switch (primaryCode) + { + case "zxx": + return new LanguageInfoDto(primaryCode, "No linguistic content", null); + case "mul": + return new LanguageInfoDto(primaryCode, "Multiple languages", null); + case "und": + return new LanguageInfoDto(primaryCode, "Undetermined", null); + } + + if (s_culturesByLanguageCode.TryGetValue(primaryCode, out CultureInfo? culture)) + return new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName); + return new LanguageInfoDto(primaryCode, primaryCode, null); + } + + /// + /// Maps a free-form contributor role into a canonical media contributor role. + /// + /// The role to map. + /// The mapped contributor role. + private static MediaContributorRole MapRole(string? role) + { + if (string.IsNullOrWhiteSpace(role)) + return MediaContributorRole.Other; + + string value = role.Trim().ToLowerInvariant(); + + // An instrument is more specific than a generic role, so the instruments are matched first. + if (value.Contains("backing vocal", StringComparison.Ordinal)) + return MediaContributorRole.BackingVocals; + if (value.Contains("vocal", StringComparison.Ordinal)) + return MediaContributorRole.Vocals; + if (value.Contains("bass guitar", StringComparison.Ordinal) || value.Contains("electric bass", StringComparison.Ordinal) || string.Equals(value, "bass", StringComparison.Ordinal)) + return MediaContributorRole.BassGuitar; + if (value.Contains("guitar", StringComparison.Ordinal)) + return MediaContributorRole.Guitar; + if (value.Contains("drum", StringComparison.Ordinal) || value.Contains("membranophone", StringComparison.Ordinal)) + return MediaContributorRole.Drums; + if (value.Contains("percussion", StringComparison.Ordinal) || value.Contains("tambourine", StringComparison.Ordinal) || value.Contains("handclap", StringComparison.Ordinal) || value.Contains("stomp", StringComparison.Ordinal)) + return MediaContributorRole.Percussion; + if (value.Contains("keyboard", StringComparison.Ordinal)) + return MediaContributorRole.Keyboards; + if (value.Contains("piano", StringComparison.Ordinal)) + return MediaContributorRole.Piano; + if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal) || value.Contains("sampler", StringComparison.Ordinal)) + return MediaContributorRole.Synthesizer; + if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal)) + return MediaContributorRole.Strings; + if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal)) + return MediaContributorRole.Brass; + if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal)) + return MediaContributorRole.Woodwinds; + + if (value.Contains("executive producer", StringComparison.Ordinal)) + return MediaContributorRole.ExecutiveProducer; + if (value.Contains("producer", StringComparison.Ordinal)) + return MediaContributorRole.Producer; + if (value.Contains("remix", StringComparison.Ordinal)) + return MediaContributorRole.Remixer; + if (value.Contains("engineer", StringComparison.Ordinal) || value.Contains("mastering", StringComparison.Ordinal)) + return MediaContributorRole.Engineer; + if (value.Contains("mix", StringComparison.Ordinal)) + return MediaContributorRole.Mixer; + if (value.Contains("arranger", StringComparison.Ordinal)) + return MediaContributorRole.Arranger; + if (value.Contains("conductor", StringComparison.Ordinal)) + return MediaContributorRole.Conductor; + if (value.Contains("orchestrator", StringComparison.Ordinal)) + return MediaContributorRole.Orchestrator; + if (value.Contains("composer", StringComparison.Ordinal)) + return MediaContributorRole.Composer; + if (value.Contains("lyricist", StringComparison.Ordinal) || value.Contains("librettist", StringComparison.Ordinal)) + return MediaContributorRole.Lyricist; + if (value.Contains("writer", StringComparison.Ordinal) || value.Contains("author", StringComparison.Ordinal)) + return MediaContributorRole.Author; + if (value.Contains("choir", StringComparison.Ordinal) || value.Contains("chorus", StringComparison.Ordinal)) + return MediaContributorRole.Choir; + if (value.Contains("performer", StringComparison.Ordinal) || value.Contains("member of band", StringComparison.Ordinal) || value.Contains("orchestra", StringComparison.Ordinal)) + return MediaContributorRole.Performer; + + return MediaContributorRole.Other; + } + + /// + /// Adds a contributor to the provided list, unless an identical name and role pair is already present. + /// + /// The contributors collected so far. + /// The display name of the contributor. + /// The role the contributor played. + private static void AddContributor(List contributors, string displayName, MediaContributorRole role) + { + if (string.IsNullOrWhiteSpace(displayName)) + return; + if (contributors.Any(contributor => + string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) && + contributor.Role == role)) + return; + contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), null), role)); + } + + /// + /// Parses the provided value as a globally unique identifier. + /// + /// The value to parse. + /// The parsed identifier, or when the value is missing or malformed. + private static Guid? ParseGuid(string? value) + { + return Guid.TryParse(value, out Guid parsed) ? parsed : null; + } + + /// + /// Parses the first globally unique identifier of a value that may hold several slash-separated identifiers. + /// + /// The value to parse. + /// The first parsed identifier, or when the value holds none. + private static Guid? ParseFirstGuid(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + foreach (string candidate in value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + if (Guid.TryParse(candidate, out Guid parsed)) + return parsed; + return null; + } + + /// + /// Gets the first value of a tag that may hold several slash-separated values. + /// + /// The value to read. + /// The first non-empty value, or when the value is empty. + private static string? FirstValue(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + return NullIfWhiteSpace(value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).FirstOrDefault()); + } + + /// + /// Returns the trimmed value, or when the value is empty or white space. + /// + /// The value to process. + /// The trimmed value, or . + private static string? NullIfWhiteSpace(string? value) + { + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs b/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs new file mode 100644 index 00000000..4f86de83 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Core/Tags/Id3TagReader.cs @@ -0,0 +1,434 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +#endregion + +namespace Lumina.Plugins.ID3.Core.Tags; + +/// +/// Reads the embedded tags of an audio file into a snapshot, caching the snapshot per path so that the tags of a single file are read only once. +/// +internal sealed class Id3TagReader +{ + /// + /// The container tag types whose extended tags are searched, in the order they are tried. + /// + private static readonly TagLib.TagTypes[] s_extendedTagContainerTypes = [TagLib.TagTypes.Xiph, TagLib.TagTypes.Id3v2, TagLib.TagTypes.Apple, TagLib.TagTypes.Ape]; + + /// + /// The keys of the free-form Apple tags that carry the involved people of a track, paired with the role each of them describes. + /// + private static readonly (string Role, string Key)[] s_appleInvolvedPeopleKeys = + [ + ("performer", "performer"), + ("producer", "PRODUCER"), + ("engineer", "ENGINEER"), + ("mixer", "MIXER"), + ("arranger", "arranger"), + ("writer", "writer") + ]; + + /// + /// Matches a four digit year. + /// + private static readonly Regex s_yearPattern = new(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b", RegexOptions.Compiled); + + /// + /// The maximum number of tag snapshots the cache retains, so that reading a large library does not retain the tags of every file it visits. + /// + private const int MAX_CACHED_SNAPSHOTS = 512; + + private readonly Dictionary _cache = new(StringComparer.Ordinal); + private readonly Queue _cacheOrder = new(); + private readonly Lock _cacheLock = new(); + + /// + /// Reads the embedded tags of the audio file stored at . + /// + /// The file system path of the audio file whose tags are read. + /// The snapshot of the tags, or when the file does not exist or its tags cannot be read. + public Id3TagDto? Read(string path) + { + if (string.IsNullOrWhiteSpace(path)) + return null; + + lock (_cacheLock) + { + if (_cache.TryGetValue(path, out Id3TagDto? cached)) + return cached; + } + + Id3TagDto? data = ReadTagData(path); + // A file whose tags cannot be read is not cached, so that a transient failure does not skip the file for the rest of the scan. + if (data is null) + return null; + + lock (_cacheLock) + { + if (!_cache.ContainsKey(path)) + { + if (_cache.Count >= MAX_CACHED_SNAPSHOTS) + EvictOldestSnapshot(); + _cache[path] = data; + _cacheOrder.Enqueue(path); + } + } + return data; + } + + /// + /// Removes the snapshot that was cached first, keeping the cache within its maximum size. + /// + private void EvictOldestSnapshot() + { + if (_cacheOrder.Count == 0) + return; + string oldestPath = _cacheOrder.Dequeue(); + _cache.Remove(oldestPath); + } + + /// + /// Reads the embedded tags of the audio file stored at into a snapshot. + /// + /// The file system path of the audio file whose tags are read. + /// The snapshot of the tags, or when the file does not exist or its tags cannot be read. + private static Id3TagDto? ReadTagData(string path) + { + // A file whose path cannot be represented by the operating system, or that is not an audio container, yields no metadata rather than an error. + if (!File.Exists(path)) + return null; + + try + { + // A link inside a library root must not cause the tags of a file outside the library to be read. + if (File.GetAttributes(path).HasFlag(FileAttributes.ReparsePoint)) + return null; + + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + TagLib.Tag tag = tagFile.Tag; + TagLib.Properties audioProperties = tagFile.Properties; + List>> extendedFields = BuildExtendedFieldSources(tagFile); + + (DateOnly? releaseDate, int? releaseYear) = ParseDate(GetExtendedField(extendedFields, "TDRC", "DATE")); + (DateOnly? originalDate, int? originalYear) = ParseDate(GetExtendedField(extendedFields, "TDOR", "originaldate", "ORIGINALDATE", "originalyear")); + int? year = releaseYear ?? (tag.Year > 0 ? (int)tag.Year : null); + // The original release date and year must describe the same point in time, so the explicit original date is preferred and the year of the chosen date is used whenever a date is known, rather than the year of the release described by the tags. + DateOnly? originalReleaseDate = originalDate ?? releaseDate; + int? originalReleaseYear = originalReleaseDate?.Year ?? originalYear ?? year; + + return new Id3TagDto + { + Title = NullIfWhiteSpace(tag.Title), + Album = NullIfWhiteSpace(tag.Album), + TrackArtists = Filter(tag.Performers), + AlbumArtists = Filter(tag.AlbumArtists), + AlbumArtistSortName = NullIfWhiteSpace(tag.AlbumArtistsSort?.FirstOrDefault()), + TrackArtistSortName = NullIfWhiteSpace(tag.PerformersSort?.FirstOrDefault()), + TrackNumber = tag.Track, + TrackCount = tag.TrackCount, + DiscNumber = tag.Disc, + DiscCount = tag.DiscCount, + Year = year, + OriginalReleaseDate = originalReleaseDate, + OriginalReleaseYear = originalReleaseYear, + Genres = SplitValues(Filter(tag.Genres)), + Composers = SplitValues(Filter(tag.Composers)), + Lyricists = SplitValues(GetExtendedFields(extendedFields, "LYRICIST", "lyricist", "TEXT")), + Conductors = Filter([tag.Conductor]), + Remixers = Filter([tag.RemixedBy]), + InvolvedPeople = ReadInvolvedPeople(extendedFields), + Language = NullIfWhiteSpace(GetExtendedField(extendedFields, "LANGUAGE", "TLAN")), + Script = NullIfWhiteSpace(GetExtendedField(extendedFields, "SCRIPT")), + Label = NullIfWhiteSpace(tag.Publisher) ?? NullIfWhiteSpace(GetExtendedField(extendedFields, "LABEL")), + CatalogNumbers = SplitValuesOnSemicolons(GetExtendedFields(extendedFields, "CATALOGNUMBER")), + Barcode = NullIfWhiteSpace(GetExtendedField(extendedFields, "BARCODE", "barcode")), + ReleaseTypes = SplitValuesOnSemicolons([tag.MusicBrainzReleaseType]), + ReleaseStatus = NullIfWhiteSpace(tag.MusicBrainzReleaseStatus), + ReleaseCountry = NullIfWhiteSpace(tag.MusicBrainzReleaseCountry), + MediaFormat = NullIfWhiteSpace(GetExtendedField(extendedFields, "MEDIA", "TMED")), + Packaging = NullIfWhiteSpace(GetExtendedField(extendedFields, "PACKAGING")), + Asin = NullIfWhiteSpace(tag.AmazonId) ?? NullIfWhiteSpace(GetExtendedField(extendedFields, "ASIN")), + Isrcs = ReadIsrcs(extendedFields, tag), + Moods = SplitValues(GetExtendedFields(extendedFields, "mood", "MOOD", "MOODS")), + WorkTitle = NullIfWhiteSpace(GetExtendedField(extendedFields, "WORK", "MUSICBRAINZ_WORK")), + MusicKey = NullIfWhiteSpace(tag.InitialKey), + Bpm = tag.BeatsPerMinute > 0 ? (int)tag.BeatsPerMinute : null, + DurationInSeconds = audioProperties.Duration > TimeSpan.Zero ? (int)audioProperties.Duration.TotalSeconds : null, + SampleRate = audioProperties.AudioSampleRate > 0 ? audioProperties.AudioSampleRate : null, + Channels = audioProperties.AudioChannels > 0 ? audioProperties.AudioChannels : null, + BitDepth = audioProperties.BitsPerSample > 0 ? audioProperties.BitsPerSample : null, + Bitrate = audioProperties.AudioBitrate > 0 ? audioProperties.AudioBitrate : null, + AudioCodec = NullIfWhiteSpace(audioProperties.Description), + Website = NullIfWhiteSpace(GetExtendedField(extendedFields, "WOAR", "website")), + MusicBrainzArtistId = NullIfWhiteSpace(tag.MusicBrainzArtistId), + MusicBrainzReleaseArtistId = NullIfWhiteSpace(tag.MusicBrainzReleaseArtistId), + MusicBrainzReleaseGroupId = NullIfWhiteSpace(tag.MusicBrainzReleaseGroupId), + MusicBrainzReleaseId = NullIfWhiteSpace(tag.MusicBrainzReleaseId), + MusicBrainzRecordingId = NullIfWhiteSpace(tag.MusicBrainzTrackId), + MusicBrainzReleaseTrackId = NullIfWhiteSpace(GetExtendedField(extendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")), + MusicBrainzWorkId = NullIfWhiteSpace(GetExtendedField(extendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID")) + }; + } + } + catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException) + { + // A file whose tags cannot be read still contributes the metadata derived from its path, so the failure is not propagated. + return null; + } + } + + /// + /// Reads the people credited on the track, together with the free-form role each of them is credited for. + /// + /// The extended fields of the file, in the order their containers are searched. + /// The people credited on the track, as role and name pairs. + private static List<(string Role, string Name)> ReadInvolvedPeople(List>> extendedFields) + { + List<(string Role, string Name)> people = []; + + // The ID3v2.3 involved people list (IPLS) and the ID3v2.4 equivalent (TIPL) store roles and names as a single flat sequence of alternating values. + List id3People = GetExtendedFields(extendedFields, "IPLS", "TIPL", "TMCL"); + for (int index = 0; index + 1 < id3People.Count; index += 2) + people.Add((id3People[index], id3People[index + 1])); + + // The Apple containers store each role as its own free-form tag, carrying one or more names. + foreach ((string role, string key) in s_appleInvolvedPeopleKeys) + foreach (string name in GetExtendedFields(extendedFields, key)) + if (!string.IsNullOrWhiteSpace(name)) + people.Add((role, name)); + + return people; + } + + /// + /// Reads the ISRCs of the track, from both the dedicated tag and the extended tags, without duplicates. + /// + /// The extended fields of the file, in the order their containers are searched. + /// The combined tag of the file. + /// The ISRCs of the track. + private static List ReadIsrcs(List>> extendedFields, TagLib.Tag tag) + { + List values = SplitValues(GetExtendedFields(extendedFields, "ISRC", "TSRC")); + if (!string.IsNullOrWhiteSpace(tag.ISRC)) + values.AddRange(SplitValues([tag.ISRC])); + return [.. values.Distinct(StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Builds the ordered accessors that resolve an extended tag value from whichever container tag of the file carries it. + /// + /// The file whose extended tags are read. + /// The accessors, in the order the containers are searched. + private static List>> BuildExtendedFieldSources(TagLib.File tagFile) + { + List>> sources = []; + foreach (TagLib.TagTypes tagType in s_extendedTagContainerTypes) + { + TagLib.Tag? tag = tagFile.GetTag(tagType); + if (tag is TagLib.Ogg.XiphComment xiphComment) + sources.Add(key => [.. (xiphComment.GetField(key) ?? [])]); + else if (tag is TagLib.Id3v2.Tag id3v2Tag) + { + Dictionary> id3Fields = BuildId3v2Fields(id3v2Tag); + sources.Add(key => id3Fields.TryGetValue(key, out List? values) ? values : []); + } + else if (tag is TagLib.Mpeg4.AppleTag appleTag) + sources.Add(key => GetAppleFields(appleTag, key)); + else if (tag is TagLib.Ape.Tag apeTag) + sources.Add(key => GetApeFields(apeTag, key)); + } + return sources; + } + + /// + /// Builds the map of the ID3v2 frames of the file, keyed by the name each frame is looked up with, so that the frames are enumerated only once per file. + /// + /// The ID3v2 tag whose frames are indexed. + /// The values of every frame, keyed by the frame identifier or the description of a user defined frame. + private static Dictionary> BuildId3v2Fields(TagLib.Id3v2.Tag id3v2Tag) + { + Dictionary> fields = new(StringComparer.OrdinalIgnoreCase); + foreach (TagLib.Id3v2.Frame frame in id3v2Tag.GetFrames()) + { + string key; + List values; + if (frame is TagLib.Id3v2.UserTextInformationFrame userTextViewFrame) + { + key = userTextViewFrame.Description; + values = [.. userTextViewFrame.Text]; + } + else if (frame is TagLib.Id3v2.UrlLinkFrame urlFrame) + { + key = urlFrame.FrameId.ToString(); + values = [.. urlFrame.Text]; + } + else if (frame is TagLib.Id3v2.TextInformationFrame textFrame) + { + key = textFrame.FrameId.ToString(); + values = [.. textFrame.Text]; + } + else + continue; + + // A user defined frame without a description carries no lookup key, so it is not indexed. + if (string.IsNullOrEmpty(key)) + continue; + + if (fields.TryGetValue(key, out List? existing)) + existing.AddRange(values); + else + fields[key] = values; + } + return fields; + } + + /// + /// Reads the values of a free-form Apple tag with the provided . + /// + /// The Apple tag whose values are read. + /// The name of the free-form tag to read. + /// Every value of the tag. + private static List GetAppleFields(TagLib.Mpeg4.AppleTag appleTag, string key) + { + List values = []; + foreach (string appleValue in appleTag.GetDashBoxes("com.apple.iTunes", key) ?? []) + values.AddRange(appleValue.Split('\0', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + return values; + } + + /// + /// Reads the values of an APE tag with the provided . + /// + /// The APE tag whose values are read. + /// The name of the tag to read. + /// Every value of the tag. + private static List GetApeFields(TagLib.Ape.Tag apeTag, string key) + { + if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem) + return [.. apeItem.ToStringArray()]; + return []; + } + + /// + /// Reads the first non-empty value of an extended tag, from whichever container tag of the file carries it. + /// + /// The extended fields of the file, in the order their containers are searched. + /// The candidate names of the extended tag to read, in the order they are tried. + /// The first non-empty value found, or when the file carries none of the provided tags. + private static string? GetExtendedField(List>> extendedFields, params string[] keys) + { + foreach (Func> extendedField in extendedFields) + { + foreach (string key in keys) + { + List values = extendedField(key); + string? value = values.FirstOrDefault(candidate => !string.IsNullOrWhiteSpace(candidate)); + if (!string.IsNullOrWhiteSpace(value)) + return value; + } + } + return null; + } + + /// + /// Reads every value of an extended tag, from whichever container tag of the file carries it. + /// + /// The extended fields of the file, in the order their containers are searched. + /// The candidate names of the extended tag to read, in the order they are tried. + /// Every non-empty value found, or an empty list when the file carries none of the provided tags. + private static List GetExtendedFields(List>> extendedFields, params string[] keys) + { + List values = []; + foreach (Func> extendedField in extendedFields) + foreach (string key in keys) + // A container whose keys are matched case insensitively resolves several case variant aliases to the same entry, so the values already read are not added again. + foreach (string value in extendedField(key)) + if (!string.IsNullOrWhiteSpace(value) && !values.Contains(value, StringComparer.Ordinal)) + values.Add(value); + return values; + } + + /// + /// Keeps only the non-empty values of the provided collection, trimmed. + /// + /// The values to filter. + /// The non-empty, trimmed values. + private static List Filter(IEnumerable? values) + { + return [.. (values ?? []).Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim())]; + } + + /// + /// Splits every provided value on the separators used to pack several values into a single tag, and keeps the non-empty results. + /// + /// The values to split. + /// The individual values found. + private static List SplitValues(IEnumerable values) + { + return SplitValues(values, ['/', ';']); + } + + /// + /// Splits every provided value on semicolons only, for the tags whose own values may contain a slash. + /// + /// The values to split. + /// The individual values found. + private static List SplitValuesOnSemicolons(IEnumerable values) + { + return SplitValues(values, [';']); + } + + /// + /// Splits every provided value on the provided separators, and keeps the non-empty results. + /// + /// The values to split. + /// The separators to split the values on. + /// The individual values found. + private static List SplitValues(IEnumerable values, char[] separators) + { + List result = []; + foreach (string value in values) + { + if (string.IsNullOrWhiteSpace(value)) + continue; + foreach (string part in value.Split(separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + if (!string.IsNullOrWhiteSpace(part)) + result.Add(part); + } + return result; + } + + /// + /// Parses a date string into a date and a year. + /// + /// The date string to parse. + /// The parsed date and year, or values when the string could not be parsed. + private static (DateOnly? Date, int? Year) ParseDate(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return (null, null); + + if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact)) + return (exact, exact.Year); + + Match yearMatch = s_yearPattern.Match(value); + return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null); + } + + /// + /// Returns the trimmed value, or when the value is empty or white space. + /// + /// The value to process. + /// The trimmed value, or . + private static string? NullIfWhiteSpace(string? value) + { + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } +} diff --git a/plugins/Lumina.Plugins.ID3/Lumina.Plugins.ID3.csproj b/plugins/Lumina.Plugins.ID3/Lumina.Plugins.ID3.csproj new file mode 100644 index 00000000..7ff8f7bd --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Lumina.Plugins.ID3.csproj @@ -0,0 +1,35 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + + + + + + + + + + + + + + false + runtime + + + + + + + + diff --git a/plugins/Lumina.Plugins.ID3/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.ID3/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..08a41295 --- /dev/null +++ b/plugins/Lumina.Plugins.ID3/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.IntegrationTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.Fixtures")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.ID3.Fixtures/Common/Models/DTO/Tags/Id3TagDtoFixture.cs b/tests/Common/Lumina.Plugins.ID3.Fixtures/Common/Models/DTO/Tags/Id3TagDtoFixture.cs new file mode 100644 index 00000000..130bb1ac --- /dev/null +++ b/tests/Common/Lumina.Plugins.ID3.Fixtures/Common/Models/DTO/Tags/Id3TagDtoFixture.cs @@ -0,0 +1,253 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.Fixtures.Common.Models.DTO.Tags; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +internal sealed class Id3TagDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The title of the track. + /// Whether the title should be included, or forced to . + /// Optional. The title of the album the track belongs to. + /// Whether the album should be included, or forced to . + /// Optional. The artists credited on the track. + /// Optional. The artists credited on the album. + /// Optional. The sort name of the album artist. + /// Whether the album artist sort name should be included, or forced to . + /// Optional. The sort name of the track artist. + /// Whether the track artist sort name should be included, or forced to . + /// Optional. The number of the track on its disc, or a random one when not supplied. + /// Optional. The number of tracks on the disc, or a random one when not supplied. + /// Optional. The number of the disc the track belongs to, or a random one when not supplied. + /// Optional. The number of discs of the release, or a random one when not supplied. + /// Optional. The year the track was released. + /// Whether the year should be included, or forced to . + /// Optional. The original release date of the track. + /// Whether the original release date should be included, or forced to . + /// Optional. The original release year of the track. + /// Whether the original release year should be included, or forced to . + /// Optional. The genres the tags associate with the track. + /// Optional. The composers credited on the track. + /// Optional. The lyricists credited on the track. + /// Optional. The conductors credited on the track. + /// Optional. The remixers credited on the track. + /// Optional. The people credited on the track, each with their role. + /// Optional. The language of the track. + /// Whether the language should be included, or forced to . + /// Optional. The script used by the language of the track. + /// Whether the script should be included, or forced to . + /// Optional. The label that issued the album. + /// Whether the label should be included, or forced to . + /// Optional. The catalog numbers of the album. + /// Optional. The barcode of the album. + /// Whether the barcode should be included, or forced to . + /// Optional. The types of the release. + /// Optional. The status of the release. + /// Whether the release status should be included, or forced to . + /// Optional. The country the release was issued in. + /// Whether the release country should be included, or forced to . + /// Optional. The medium of the release. + /// Whether the media format should be included, or forced to . + /// Optional. The packaging of the release. + /// Whether the packaging should be included, or forced to . + /// Optional. The ASIN of the album. + /// Whether the ASIN should be included, or forced to . + /// Optional. The ISRCs of the track. + /// Optional. The moods of the track. + /// Optional. The title of the work the track is a recording of. + /// Whether the work title should be included, or forced to . + /// Optional. The musical key of the track. + /// Whether the musical key should be included, or forced to . + /// Optional. The tempo of the track in beats per minute. + /// Whether the tempo should be included, or forced to . + /// Optional. The duration of the audio of the track in seconds. + /// Whether the duration should be included, or forced to . + /// Optional. The sample rate of the audio of the track in Hz. + /// Whether the sample rate should be included, or forced to . + /// Optional. The number of audio channels of the track. + /// Whether the channel count should be included, or forced to . + /// Optional. The bit depth of the audio of the track. + /// Whether the bit depth should be included, or forced to . + /// Optional. The bitrate of the audio of the track in kbps. + /// Whether the bitrate should be included, or forced to . + /// Optional. The description of the audio codec of the track. + /// Whether the audio codec should be included, or forced to . + /// Optional. The official website associated with the artist. + /// Whether the website should be included, or forced to . + /// Optional. The MusicBrainz identifier of the artist. + /// Whether the MusicBrainz artist identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the release artist. + /// Whether the MusicBrainz release artist identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the release group. + /// Whether the MusicBrainz release group identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the release. + /// Whether the MusicBrainz release identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the recording of the track. + /// Whether the MusicBrainz recording identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the track on its release. + /// Whether the MusicBrainz release track identifier should be included, or forced to . + /// Optional. The MusicBrainz identifier of the work the track is a recording of. + /// Whether the MusicBrainz work identifier should be included, or forced to . + /// A configured instance. + public Id3TagDto Create( + string? title = null, + bool includeTitle = true, + string? album = null, + bool includeAlbum = true, + List? trackArtists = null, + List? albumArtists = null, + string? albumArtistSortName = null, + bool includeAlbumArtistSortName = true, + string? trackArtistSortName = null, + bool includeTrackArtistSortName = true, + uint? trackNumber = null, + uint? trackCount = null, + uint? discNumber = null, + uint? discCount = null, + int? year = null, + bool includeYear = true, + DateOnly? originalReleaseDate = null, + bool includeOriginalReleaseDate = true, + int? originalReleaseYear = null, + bool includeOriginalReleaseYear = true, + List? genres = null, + List? composers = null, + List? lyricists = null, + List? conductors = null, + List? remixers = null, + List<(string Role, string Name)>? involvedPeople = null, + string? language = null, + bool includeLanguage = true, + string? script = null, + bool includeScript = true, + string? label = null, + bool includeLabel = true, + List? catalogNumbers = null, + string? barcode = null, + bool includeBarcode = true, + List? releaseTypes = null, + string? releaseStatus = null, + bool includeReleaseStatus = true, + string? releaseCountry = null, + bool includeReleaseCountry = true, + string? mediaFormat = null, + bool includeMediaFormat = true, + string? packaging = null, + bool includePackaging = true, + string? asin = null, + bool includeAsin = true, + List? isrcs = null, + List? moods = null, + string? workTitle = null, + bool includeWorkTitle = true, + string? musicKey = null, + bool includeMusicKey = true, + int? bpm = null, + bool includeBpm = true, + int? durationInSeconds = null, + bool includeDurationInSeconds = true, + int? sampleRate = null, + bool includeSampleRate = true, + int? channels = null, + bool includeChannels = true, + int? bitDepth = null, + bool includeBitDepth = true, + int? bitrate = null, + bool includeBitrate = true, + string? audioCodec = null, + bool includeAudioCodec = true, + string? website = null, + bool includeWebsite = true, + string? musicBrainzArtistId = null, + bool includeMusicBrainzArtistId = true, + string? musicBrainzReleaseArtistId = null, + bool includeMusicBrainzReleaseArtistId = true, + string? musicBrainzReleaseGroupId = null, + bool includeMusicBrainzReleaseGroupId = true, + string? musicBrainzReleaseId = null, + bool includeMusicBrainzReleaseId = true, + string? musicBrainzRecordingId = null, + bool includeMusicBrainzRecordingId = true, + string? musicBrainzReleaseTrackId = null, + bool includeMusicBrainzReleaseTrackId = true, + string? musicBrainzWorkId = null, + bool includeMusicBrainzWorkId = true) + { + return new Id3TagDto + { + Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null, + Album = includeAlbum ? album ?? _faker.Lorem.Sentence(2) : null, + TrackArtists = trackArtists ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + AlbumArtists = albumArtists ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + AlbumArtistSortName = includeAlbumArtistSortName ? albumArtistSortName ?? _faker.Name.LastName() : null, + TrackArtistSortName = includeTrackArtistSortName ? trackArtistSortName ?? _faker.Name.LastName() : null, + TrackNumber = trackNumber ?? (uint)_faker.Random.Int(1, 30), + TrackCount = trackCount ?? (uint)_faker.Random.Int(1, 30), + DiscNumber = discNumber ?? (uint)_faker.Random.Int(1, 4), + DiscCount = discCount ?? (uint)_faker.Random.Int(1, 4), + Year = includeYear ? year ?? _faker.Random.Int(1950, 2024) : null, + OriginalReleaseDate = includeOriginalReleaseDate ? originalReleaseDate ?? DateOnly.FromDateTime(_faker.Date.Past()) : null, + OriginalReleaseYear = includeOriginalReleaseYear ? originalReleaseYear ?? _faker.Random.Int(1950, 2024) : null, + Genres = genres ?? [.. _faker.Make(2, () => _faker.Lorem.Word())], + Composers = composers ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + Lyricists = lyricists ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + Conductors = conductors ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + Remixers = remixers ?? [.. _faker.Make(2, () => _faker.Name.FullName())], + InvolvedPeople = involvedPeople ?? [(_faker.PickRandom("producer", "engineer", "mixer"), _faker.Name.FullName())], + Language = includeLanguage ? language ?? _faker.Random.String2(3, "abcdefghijklmnopqrstuvwxyz") : null, + Script = includeScript ? script ?? _faker.Random.String2(4, "abcdefghijklmnopqrstuvwxyz") : null, + Label = includeLabel ? label ?? _faker.Company.CompanyName() : null, + CatalogNumbers = catalogNumbers ?? [.. _faker.Make(2, () => _faker.Random.AlphaNumeric(8))], + Barcode = includeBarcode ? barcode ?? _faker.Random.AlphaNumeric(12) : null, + ReleaseTypes = releaseTypes ?? [_faker.PickRandom("album", "single", "ep")], + ReleaseStatus = includeReleaseStatus ? releaseStatus ?? _faker.PickRandom("official", "promotion") : null, + ReleaseCountry = includeReleaseCountry ? releaseCountry ?? _faker.PickRandom("US", "GB", "DE") : null, + MediaFormat = includeMediaFormat ? mediaFormat ?? _faker.PickRandom("CD", "Vinyl") : null, + Packaging = includePackaging ? packaging ?? _faker.PickRandom("Jewel Case", "Digipak") : null, + Asin = includeAsin ? asin ?? _faker.Random.AlphaNumeric(10) : null, + Isrcs = isrcs ?? [.. _faker.Make(2, () => $"US{_faker.Random.AlphaNumeric(10).ToUpperInvariant()}")], + Moods = moods ?? [.. _faker.Make(2, () => _faker.Lorem.Word())], + WorkTitle = includeWorkTitle ? workTitle ?? _faker.Lorem.Sentence(3) : null, + MusicKey = includeMusicKey ? musicKey ?? _faker.PickRandom("C major", "A minor") : null, + Bpm = includeBpm ? bpm ?? _faker.Random.Int(60, 200) : null, + DurationInSeconds = includeDurationInSeconds ? durationInSeconds ?? _faker.Random.Int(30, 600) : null, + SampleRate = includeSampleRate ? sampleRate ?? _faker.PickRandom(44100, 48000, 96000) : null, + Channels = includeChannels ? channels ?? _faker.Random.Int(1, 2) : null, + BitDepth = includeBitDepth ? bitDepth ?? _faker.PickRandom(16, 24, 32) : null, + Bitrate = includeBitrate ? bitrate ?? _faker.Random.Int(128, 320) : null, + AudioCodec = includeAudioCodec ? audioCodec ?? _faker.PickRandom("PCM Audio", "MPEG Audio") : null, + Website = includeWebsite ? website ?? _faker.Internet.Url() : null, + MusicBrainzArtistId = includeMusicBrainzArtistId ? musicBrainzArtistId ?? Guid.NewGuid().ToString() : null, + MusicBrainzReleaseArtistId = includeMusicBrainzReleaseArtistId ? musicBrainzReleaseArtistId ?? Guid.NewGuid().ToString() : null, + MusicBrainzReleaseGroupId = includeMusicBrainzReleaseGroupId ? musicBrainzReleaseGroupId ?? Guid.NewGuid().ToString() : null, + MusicBrainzReleaseId = includeMusicBrainzReleaseId ? musicBrainzReleaseId ?? Guid.NewGuid().ToString() : null, + MusicBrainzRecordingId = includeMusicBrainzRecordingId ? musicBrainzRecordingId ?? Guid.NewGuid().ToString() : null, + MusicBrainzReleaseTrackId = includeMusicBrainzReleaseTrackId ? musicBrainzReleaseTrackId ?? Guid.NewGuid().ToString() : null, + MusicBrainzWorkId = includeMusicBrainzWorkId ? musicBrainzWorkId ?? Guid.NewGuid().ToString() : 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.Plugins.ID3.Fixtures/Core/Tags/TestAudioFileFactory.cs b/tests/Common/Lumina.Plugins.ID3.Fixtures/Core/Tags/TestAudioFileFactory.cs new file mode 100644 index 00000000..36ec5a00 --- /dev/null +++ b/tests/Common/Lumina.Plugins.ID3.Fixtures/Core/Tags/TestAudioFileFactory.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; +#endregion + +namespace Lumina.Plugins.ID3.Fixtures.Core.Tags; + +/// +/// Builds minimal, structurally valid WAV files used as test input for the ID3 tag reading tests. +/// The files are produced into a temporary directory at test runtime, because a WAV is a binary container whose +/// embedded tags can only be written by the tagging library itself. +/// +[ExcludeFromCodeCoverage] +public static class TestAudioFileFactory +{ + /// + /// Creates a minimal, untagged PCM WAV file. + /// + /// The path where the WAV is written. + /// The duration of the audio of the file, in milliseconds. + public static void CreateWav(string path, int durationMs = 200) + { + File.WriteAllBytes(path, BuildWav(durationMs)); + } + + /// + /// Creates a PCM WAV file whose embedded tags are configured by the provided callback. + /// + /// The path where the WAV is written. + /// The callback that configures the tags of the file. + /// The duration of the audio of the file, in milliseconds. + public static void CreateTaggedWav(string path, Action configureTags, int durationMs = 200) + { + File.WriteAllBytes(path, BuildWav(durationMs)); + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + configureTags(tagFile); + tagFile.Save(); + } + } + + /// + /// Adds a user defined text information frame (TXXX) to the ID3v2 tag of the file. + /// + /// The file whose ID3v2 tag is extended. + /// The description that identifies the frame. + /// The values of the frame. + public static void AddUserTextFrame(TagLib.File tagFile, string description, params string[] values) + { + GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.UserTextInformationFrame(description) { Text = values }); + } + + /// + /// Adds a text information frame to the ID3v2 tag of the file. + /// + /// The file whose ID3v2 tag is extended. + /// The four character identifier of the frame. + /// The values of the frame. + public static void AddTextFrame(TagLib.File tagFile, string frameId, params string[] values) + { + GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.TextInformationFrame(frameId) { Text = values }); + } + + /// + /// Adds a URL link frame (WXXX/WOAR) to the ID3v2 tag of the file. + /// + /// The file whose ID3v2 tag is extended. + /// The four character identifier of the frame. + /// The URL values of the frame. + public static void AddUrlFrame(TagLib.File tagFile, string frameId, params string[] values) + { + GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.UrlLinkFrame(frameId) { Text = values }); + } + + /// + /// Gets the ID3v2 tag of the file, creating it when the file does not carry one yet. + /// + /// The file whose ID3v2 tag is read. + /// The ID3v2 tag of the file. + private static TagLib.Id3v2.Tag GetId3v2Tag(TagLib.File tagFile) + { + return tagFile.GetTag(TagLib.TagTypes.Id3v2, true) as TagLib.Id3v2.Tag + ?? throw new InvalidOperationException("The test audio file does not expose an ID3v2 tag."); + } + + /// + /// Builds the bytes of a minimal, valid PCM WAV file with a single silent audio channel. + /// + /// The duration of the audio of the file, in milliseconds. + /// The bytes of the WAV file. + private static byte[] BuildWav(int durationMs) + { + const int SAMPLE_RATE = 44100; + const short CHANNELS = 1; + const short BITS_PER_SAMPLE = 16; + + int bytesPerSample = BITS_PER_SAMPLE / 8; + int dataSize = SAMPLE_RATE * CHANNELS * bytesPerSample * durationMs / 1000; + + using (MemoryStream memoryStream = new()) + { + using (BinaryWriter writer = new(memoryStream)) + { + writer.Write(Encoding.ASCII.GetBytes("RIFF")); + writer.Write(36 + dataSize); + writer.Write(Encoding.ASCII.GetBytes("WAVE")); + writer.Write(Encoding.ASCII.GetBytes("fmt ")); + writer.Write(16); + writer.Write((short)1); + writer.Write(CHANNELS); + writer.Write(SAMPLE_RATE); + writer.Write(SAMPLE_RATE * CHANNELS * bytesPerSample); + writer.Write((short)(CHANNELS * bytesPerSample)); + writer.Write(BITS_PER_SAMPLE); + writer.Write(Encoding.ASCII.GetBytes("data")); + writer.Write(dataSize); + writer.Write(new byte[dataSize]); + } + return memoryStream.ToArray(); + } + } +} diff --git a/tests/Common/Lumina.Plugins.ID3.Fixtures/Lumina.Plugins.ID3.Fixtures.csproj b/tests/Common/Lumina.Plugins.ID3.Fixtures/Lumina.Plugins.ID3.Fixtures.csproj new file mode 100644 index 00000000..8685fafc --- /dev/null +++ b/tests/Common/Lumina.Plugins.ID3.Fixtures/Lumina.Plugins.ID3.Fixtures.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.ID3.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.ID3.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..38b23d1d --- /dev/null +++ b/tests/Common/Lumina.Plugins.ID3.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.ID3.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.ID3.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("BB7E0186-B7E4-4DD2-AC9C-2C900EAF1D96")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.IntegrationTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3AlbumMetadataProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3AlbumMetadataProviderTests.cs new file mode 100644 index 00000000..ddbd06ea --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3AlbumMetadataProviderTests.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Lumina.Plugins.ID3.Fixtures.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real tagged audio containers. +/// +[ExcludeFromCodeCoverage] +public class Id3AlbumMetadataProviderTests : IDisposable +{ + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly Id3AlbumMetadataProvider _sut = new(new Id3TagReader()); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3AlbumMetadataProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-album-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryAnAlbum_ShouldReturnTheMappedAlbum() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Album = "The Album"; + file.Tag.AlbumArtists = ["The Album Artist"]; + file.Tag.TrackCount = 10; + file.Tag.DiscCount = 2; + }); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + AlbumMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Album", result.Title); + Assert.Equal(10, result.TotalTracks); + Assert.Equal(2, result.TotalDiscs); + Assert.NotNull(result.Contributors); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Album Artist"); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryNoAlbum_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "untagged.wav"); + TestAudioFileFactory.CreateWav(path); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + AlbumMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheTagsCarryAnAlbum_ShouldReturnASingleCandidate() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Album = "The Album"); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + AlbumMetadataDto candidate = Assert.Single(result); + Assert.Equal("The Album", candidate.Title); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3ArtistMetadataProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3ArtistMetadataProviderTests.cs new file mode 100644 index 00000000..dff187ec --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3ArtistMetadataProviderTests.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Lumina.Plugins.ID3.Fixtures.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real tagged audio containers. +/// +[ExcludeFromCodeCoverage] +public class Id3ArtistMetadataProviderTests : IDisposable +{ + private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new(); + private readonly Id3ArtistMetadataProvider _sut = new(new Id3TagReader()); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3ArtistMetadataProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-artist-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryAnArtist_ShouldReturnTheMappedArtist() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + Guid artistId = Guid.NewGuid(); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Performers = ["The Artist"]; + file.Tag.PerformersSort = ["Artist, The"]; + file.Tag.MusicBrainzArtistId = artistId.ToString(); + }); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + ArtistMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Artist", result.Name); + Assert.Equal("Artist, The", result.SortName); + Assert.Equal(artistId, result.MusicBrainzArtistId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryNoArtist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "untagged.wav"); + TestAudioFileFactory.CreateWav(path); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + ArtistMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheTagsCarryAnArtist_ShouldReturnASingleCandidate() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Performers = ["The Artist"]); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + ArtistMetadataDto candidate = Assert.Single(result); + Assert.Equal("The Artist", candidate.Name); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs new file mode 100644 index 00000000..e2b37e9b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Id3TrackMetadataProviderTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Lumina.Plugins.ID3.Fixtures.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real tagged audio containers. +/// +[ExcludeFromCodeCoverage] +public class Id3TrackMetadataProviderTests : IDisposable +{ + private readonly TrackMetadataLookupDtoFixture _trackMetadataLookupDtoFixture = new(); + private readonly Id3TrackMetadataProvider _sut = new(new Id3TagReader()); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3TrackMetadataProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-track-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryATitle_ShouldReturnTheMappedTrack() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Title = "The Track"; + file.Tag.InitialKey = "C#m"; + file.Tag.BeatsPerMinute = 128; + file.Tag.Performers = ["The Artist"]; + }); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + AudioMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Track", result.Title); + Assert.Equal(MusicKey.CSharpMinor, result.Key); + Assert.Equal(128, result.Bpm); + Assert.NotNull(result.Contributors); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Artist"); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryNoTitle_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "untagged.wav"); + TestAudioFileFactory.CreateWav(path); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + AudioMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheTagsCarryATitle_ShouldReturnASingleCandidate() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tagged.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Title = "The Track"); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + AudioMetadataDto candidate = Assert.Single(result); + Assert.Equal("The Track", candidate.Title); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs new file mode 100644 index 00000000..60a4a815 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Core/Tags/Id3TagReaderTests.cs @@ -0,0 +1,480 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Tags; +using Lumina.Plugins.ID3.Fixtures.Core.Tags; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.ID3.IntegrationTests.Core.Tags; + +/// +/// Contains integration tests for the class, reading real audio containers through the tagging library. +/// +[ExcludeFromCodeCoverage] +public class Id3TagReaderTests : IDisposable +{ + private readonly Id3TagReader _sut = new(); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3TagReaderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-reader-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Read_WhenEveryTagIsPresent_ShouldMapEveryProperty() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "all-fields.wav"); + Guid artistId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + Guid releaseGroupId = Guid.NewGuid(); + Guid releaseId = Guid.NewGuid(); + Guid recordingId = Guid.NewGuid(); + Guid releaseTrackId = Guid.NewGuid(); + Guid workId = Guid.NewGuid(); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Title = "The Track"; + file.Tag.Album = "The Album"; + file.Tag.Performers = ["Track Artist"]; + file.Tag.AlbumArtists = ["Album Artist"]; + file.Tag.PerformersSort = ["Track Artist, The"]; + file.Tag.AlbumArtistsSort = ["Album Artist, The"]; + file.Tag.Track = 3; + file.Tag.TrackCount = 12; + file.Tag.Disc = 1; + file.Tag.DiscCount = 2; + file.Tag.Genres = ["Rock/Pop", "Jazz"]; + file.Tag.Composers = ["Composer One/Composer Two"]; + file.Tag.Conductor = "The Conductor"; + file.Tag.RemixedBy = "The Remixer"; + file.Tag.Publisher = "The Label"; + file.Tag.ISRC = "GBAAA0000001"; + file.Tag.InitialKey = "C#m"; + file.Tag.BeatsPerMinute = 128; + file.Tag.AmazonId = "B000000001"; + file.Tag.MusicBrainzArtistId = artistId.ToString(); + file.Tag.MusicBrainzReleaseArtistId = releaseArtistId.ToString(); + file.Tag.MusicBrainzReleaseGroupId = releaseGroupId.ToString(); + file.Tag.MusicBrainzReleaseId = releaseId.ToString(); + file.Tag.MusicBrainzTrackId = recordingId.ToString(); + file.Tag.MusicBrainzReleaseType = "album"; + file.Tag.MusicBrainzReleaseStatus = "official"; + file.Tag.MusicBrainzReleaseCountry = "US"; + TestAudioFileFactory.AddTextFrame(file, "TDRC", "2011-03-14"); + TestAudioFileFactory.AddTextFrame(file, "TDOR", "1975-11-21"); + TestAudioFileFactory.AddUserTextFrame(file, "LYRICIST", "Lyricist One;Lyricist Two"); + TestAudioFileFactory.AddTextFrame(file, "IPLS", "producer", "Producer Person", "engineer", "Engineer Person"); + TestAudioFileFactory.AddUserTextFrame(file, "LANGUAGE", "eng"); + TestAudioFileFactory.AddUserTextFrame(file, "SCRIPT", "Latn"); + TestAudioFileFactory.AddUserTextFrame(file, "CATALOGNUMBER", "CAT-1;CAT-2"); + TestAudioFileFactory.AddUserTextFrame(file, "BARCODE", "1234567890123"); + TestAudioFileFactory.AddUserTextFrame(file, "MEDIA", "CD"); + TestAudioFileFactory.AddUserTextFrame(file, "PACKAGING", "Jewel Case"); + TestAudioFileFactory.AddUserTextFrame(file, "MOODS", "calm;happy"); + TestAudioFileFactory.AddUserTextFrame(file, "WORK", "The Work"); + TestAudioFileFactory.AddUserTextFrame(file, "MUSICBRAINZ_WORKID", workId.ToString()); + TestAudioFileFactory.AddUserTextFrame(file, "MUSICBRAINZ_RELEASETRACKID", releaseTrackId.ToString()); + TestAudioFileFactory.AddUserTextFrame(file, "website", "https://artist.example"); + }, durationMs: 2000); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Track", result.Title); + Assert.Equal("The Album", result.Album); + Assert.Equal(["Track Artist"], result.TrackArtists); + Assert.Equal(["Album Artist"], result.AlbumArtists); + Assert.Equal("Album Artist, The", result.AlbumArtistSortName); + Assert.Equal("Track Artist, The", result.TrackArtistSortName); + Assert.Equal(3u, result.TrackNumber); + Assert.Equal(12u, result.TrackCount); + Assert.Equal(1u, result.DiscNumber); + Assert.Equal(2u, result.DiscCount); + Assert.Equal(2011, result.Year); + Assert.Equal(new DateOnly(1975, 11, 21), result.OriginalReleaseDate); + Assert.Equal(1975, result.OriginalReleaseYear); + Assert.Equal(["Rock", "Pop", "Jazz"], result.Genres); + Assert.Equal(["Composer One", "Composer Two"], result.Composers); + Assert.Equal(["Lyricist One", "Lyricist Two"], result.Lyricists); + Assert.Equal(["The Conductor"], result.Conductors); + Assert.Equal(["The Remixer"], result.Remixers); + Assert.Equal([("producer", "Producer Person"), ("engineer", "Engineer Person")], result.InvolvedPeople); + Assert.Equal("eng", result.Language); + Assert.Equal("Latn", result.Script); + Assert.Equal("The Label", result.Label); + Assert.Equal(["CAT-1", "CAT-2"], result.CatalogNumbers); + Assert.Equal("1234567890123", result.Barcode); + Assert.Equal(["album"], result.ReleaseTypes); + Assert.Equal("official", result.ReleaseStatus); + Assert.Equal("US", result.ReleaseCountry); + Assert.Equal("CD", result.MediaFormat); + Assert.Equal("Jewel Case", result.Packaging); + Assert.Equal("B000000001", result.Asin); + Assert.Equal(["GBAAA0000001"], result.Isrcs); + Assert.Equal(["calm", "happy"], result.Moods); + Assert.Equal("The Work", result.WorkTitle); + Assert.Equal("C#m", result.MusicKey); + Assert.Equal(128, result.Bpm); + Assert.Equal(2, result.DurationInSeconds); + Assert.Equal(44100, result.SampleRate); + Assert.Equal(1, result.Channels); + Assert.Equal(16, result.BitDepth); + Assert.True(result.Bitrate > 0); + Assert.Equal("PCM Audio", result.AudioCodec); + Assert.Equal("https://artist.example", result.Website); + Assert.Equal(artistId.ToString(), result.MusicBrainzArtistId); + Assert.Equal(releaseArtistId.ToString(), result.MusicBrainzReleaseArtistId); + Assert.Equal(releaseGroupId.ToString(), result.MusicBrainzReleaseGroupId); + Assert.Equal(releaseId.ToString(), result.MusicBrainzReleaseId); + Assert.Equal(recordingId.ToString(), result.MusicBrainzRecordingId); + Assert.Equal(releaseTrackId.ToString(), result.MusicBrainzReleaseTrackId); + Assert.Equal(workId.ToString(), result.MusicBrainzWorkId); + } + + [Fact] + public void Read_WhenTheFileIsUntagged_ShouldReturnASnapshotWithTheAudioProperties() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "untagged.wav"); + TestAudioFileFactory.CreateWav(path); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Title); + Assert.Null(result.Album); + Assert.Empty(result.TrackArtists); + Assert.Empty(result.AlbumArtists); + Assert.Null(result.AlbumArtistSortName); + Assert.Null(result.TrackArtistSortName); + Assert.Equal(0u, result.TrackNumber); + Assert.Equal(0u, result.TrackCount); + Assert.Equal(0u, result.DiscNumber); + Assert.Equal(0u, result.DiscCount); + Assert.Null(result.Year); + Assert.Null(result.OriginalReleaseDate); + Assert.Null(result.OriginalReleaseYear); + Assert.Empty(result.Genres); + Assert.Empty(result.Composers); + Assert.Empty(result.Lyricists); + Assert.Empty(result.Conductors); + Assert.Empty(result.Remixers); + Assert.Empty(result.InvolvedPeople); + Assert.Null(result.Language); + Assert.Null(result.Script); + Assert.Null(result.Label); + Assert.Empty(result.CatalogNumbers); + Assert.Null(result.Barcode); + Assert.Empty(result.ReleaseTypes); + Assert.Null(result.ReleaseStatus); + Assert.Null(result.ReleaseCountry); + Assert.Null(result.MediaFormat); + Assert.Null(result.Packaging); + Assert.Null(result.Asin); + Assert.Empty(result.Isrcs); + Assert.Empty(result.Moods); + Assert.Null(result.WorkTitle); + Assert.Null(result.MusicKey); + Assert.Null(result.Bpm); + Assert.Equal(44100, result.SampleRate); + Assert.Equal(1, result.Channels); + Assert.Equal(16, result.BitDepth); + Assert.Equal("PCM Audio", result.AudioCodec); + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Null(result.MusicBrainzReleaseTrackId); + Assert.Null(result.MusicBrainzWorkId); + } + + [Fact] + public void Read_WhenTheFileIsNotAnAudioContainer_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "not-audio.txt"); + File.WriteAllText(path, "this is not an audio file"); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Read_WhenCalledTwiceForTheSamePath_ShouldReturnTheCachedSnapshot() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "cached.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Title = "The Track"); + + // Act + Id3TagDto? first = _sut.Read(path); + Id3TagDto? second = _sut.Read(path); + + // Assert + Assert.NotNull(first); + Assert.Same(first, second); + } + + [Theory] + [InlineData("2011-03-14", 2011)] // a full date yields its year + [InlineData("2011", 2011)] // a bare year is matched by the year pattern + [InlineData("released in 1999 remastered", 1999)] // a year embedded in free form text is still matched + public void Read_WhenTheReleaseDateIsPresent_ShouldParseTheYear(string releaseDate, int expectedYear) + { + // Arrange + string path = Path.Combine(_temporaryDirectory, $"release-date-{Guid.NewGuid():N}.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUserTextFrame(file, "TDRC", releaseDate)); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(expectedYear, result.Year); + } + + [Fact] + public void Read_WhenOnlyTheYearTagIsPresent_ShouldMapTheYear() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "year-only.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.Year = 1999); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(1999, result.Year); + Assert.Null(result.OriginalReleaseDate); + Assert.Equal(1999, result.OriginalReleaseYear); + } + + [Fact] + public void Read_WhenOnlyTheOriginalYearIsPresent_ShouldUseItForTheOriginalReleaseYear() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "original-year.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.Year = 2000; + TestAudioFileFactory.AddUserTextFrame(file, "originalyear", "1960"); + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(2000, result.Year); + Assert.Null(result.OriginalReleaseDate); + Assert.Equal(1960, result.OriginalReleaseYear); + } + + [Fact] + public void Read_WhenOnlyTheOriginalReleaseDateIsPresent_ShouldDeriveTheOriginalReleaseYearFromIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "original-date.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + TestAudioFileFactory.AddUserTextFrame(file, "TDRC", "2011-03-14"); + TestAudioFileFactory.AddUserTextFrame(file, "TDOR", "1975-11-21"); + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(new DateOnly(1975, 11, 21), result.OriginalReleaseDate); + Assert.Equal(1975, result.OriginalReleaseYear); + } + + [Fact] + public void Read_WhenTheLabelIsOnlyCarriedByTheExtendedTag_ShouldUseIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "extended-label.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUserTextFrame(file, "LABEL", "The Extended Label")); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Extended Label", result.Label); + } + + [Fact] + public void Read_WhenTheAsinIsOnlyCarriedByTheExtendedTag_ShouldUseIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "extended-asin.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUserTextFrame(file, "ASIN", "B000000001")); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("B000000001", result.Asin); + } + + [Fact] + public void Read_WhenTheLanguageUsesTheAlternativeKey_ShouldStillMapIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "tlan.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUserTextFrame(file, "TLAN", "deu")); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("deu", result.Language); + } + + [Fact] + public void Read_WhenTheIsrcIsBothInTheDedicatedAndTheExtendedTag_ShouldKeepOnlyDistinctValues() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "isrc-merge.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + file.Tag.ISRC = "GBAAA0000001"; + TestAudioFileFactory.AddTextFrame(file, "TSRC", "GBAAA0000001", "USRC17607839"); + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(["GBAAA0000001", "USRC17607839"], result.Isrcs); + } + + [Fact] + public void Read_WhenSeveralReleaseTypesArePacked_ShouldSplitThemOnSemicolons() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "release-types.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => file.Tag.MusicBrainzReleaseType = "album;live"); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal(["album", "live"], result.ReleaseTypes); + } + + [Fact] + public void Read_WhenTheWebsiteIsAUrlLinkFrame_ShouldMapIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "woar.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => TestAudioFileFactory.AddUrlFrame(file, "WOAR", "https://artist.example")); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("https://artist.example", result.Website); + } + + [Fact] + public void Read_WhenAFrameCarriesNoDescription_ShouldIgnoreIt() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "no-description.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + TestAudioFileFactory.AddUserTextFrame(file, "", "orphan"); + file.Tag.Title = "The Track"; + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Track", result.Title); + } + + [Fact] + public void Read_WhenAppleStyleInvolvedPeopleKeysArePresent_ShouldMapThem() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "apple-people.wav"); + TestAudioFileFactory.CreateTaggedWav(path, file => + { + TestAudioFileFactory.AddUserTextFrame(file, "performer", "Performer Person"); + TestAudioFileFactory.AddUserTextFrame(file, "PRODUCER", "Producer Person"); + TestAudioFileFactory.AddUserTextFrame(file, "ENGINEER", "Engineer Person"); + }); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.NotNull(result); + Assert.Equal([("performer", "Performer Person"), ("producer", "Producer Person"), ("engineer", "Engineer Person")], result.InvolvedPeople); + } + + [Fact] + public void Read_WhenMoreThanTheCacheLimitFilesAreRead_ShouldEvictTheOldestSnapshot() + { + // Arrange + string[] paths = new string[513]; + for (int index = 0; index < paths.Length; index++) + { + paths[index] = Path.Combine(_temporaryDirectory, $"cache-{index}.wav"); + TestAudioFileFactory.CreateWav(paths[index], durationMs: 1); + } + Id3TagDto? firstBeforeEviction = _sut.Read(paths[0]); + + // Act + for (int index = 1; index < paths.Length; index++) + _sut.Read(paths[index]); + Id3TagDto? firstAfterEviction = _sut.Read(paths[0]); + Id3TagDto? last = _sut.Read(paths[^1]); + + // Assert + Assert.NotNull(firstBeforeEviction); + Assert.NotNull(firstAfterEviction); + // The first snapshot was evicted to make room, so reading it again produced a fresh snapshot. + Assert.NotSame(firstBeforeEviction, firstAfterEviction); + // The most recently read snapshot is still cached. + Assert.Same(_sut.Read(paths[^1]), last); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Lumina.Plugins.ID3.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Lumina.Plugins.ID3.IntegrationTests.csproj new file mode 100644 index 00000000..40ed8eab --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.ID3.IntegrationTests/Lumina.Plugins.ID3.IntegrationTests.csproj @@ -0,0 +1,49 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Common/DependencyInjection/Id3ServicesTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Common/DependencyInjection/Id3ServicesTests.cs new file mode 100644 index 00000000..f637306f --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Common/DependencyInjection/Id3ServicesTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Common.DependencyInjection; +using Lumina.Plugins.ID3.Core.Tags; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3ServicesTests +{ + [Fact] + public void AddId3MetadataProviders_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddId3MetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddId3MetadataProviders_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddId3MetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddId3MetadataProviders_WhenCalled_ShouldRegisterTheThreeMetadataProvidersForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddId3MetadataProviders(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Equal(3, serviceProvider.GetKeyedServices(pluginId).Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void AddId3MetadataProviders_WhenCalled_ShouldRegisterTheTagReaderAsScoped() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddId3MetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor tagReaderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(Id3TagReader)); + Assert.Equal(ServiceLifetime.Scoped, tagReaderDescriptor.Lifetime); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3AlbumMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3AlbumMetadataProviderTests.cs new file mode 100644 index 00000000..c73a3952 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3AlbumMetadataProviderTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3AlbumMetadataProviderTests +{ + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly Id3AlbumMetadataProvider _sut = new(new Id3TagReader()); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("ID3", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + AlbumMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheFileDoesNotExist_ShouldReturnAnEmptyCollection() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: path, title: "The Album"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3ArtistMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3ArtistMetadataProviderTests.cs new file mode 100644 index 00000000..8573b317 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3ArtistMetadataProviderTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3ArtistMetadataProviderTests +{ + private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new(); + private readonly Id3ArtistMetadataProvider _sut = new(new Id3TagReader()); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("ID3", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + ArtistMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheFileDoesNotExist_ShouldReturnAnEmptyCollection() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: path, name: "The Artist"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3PluginTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3PluginTests.cs new file mode 100644 index 00000000..dee05b5e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3PluginTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3PluginTests +{ + private readonly Id3Plugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(Id3Plugin.s_pluginId, result); + Assert.Equal(new Guid("a3f1c8d2-6b47-4e9a-8c15-2d7f9e4b6a03"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("ID3 Metadata", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Populates artist, album and track metadata from the embedded tags of the audio files, without accessing the web.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheThreeKeyedMetadataProviders() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Equal(3, serviceProvider.GetKeyedServices(Id3Plugin.s_pluginId).Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheTagReader() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetService()); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3TrackMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3TrackMetadataProviderTests.cs new file mode 100644 index 00000000..adc796a3 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Id3TrackMetadataProviderTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.ID3.Core; +using Lumina.Plugins.ID3.Core.Tags; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3TrackMetadataProviderTests +{ + private readonly TrackMetadataLookupDtoFixture _trackMetadataLookupDtoFixture = new(); + private readonly Id3TrackMetadataProvider _sut = new(new Id3TagReader()); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("ID3", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + AudioMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheFileDoesNotExist_ShouldReturnAnEmptyCollection() + { + // Arrange + string path = Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.wav"); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: path, title: "The Track"); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Mapping/Id3TagMapperTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Mapping/Id3TagMapperTests.cs new file mode 100644 index 00000000..e3013ff1 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Mapping/Id3TagMapperTests.cs @@ -0,0 +1,1286 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Mapping; +using Lumina.Plugins.ID3.Fixtures.Common.Models.DTO.Tags; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core.Mapping; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Id3TagMapperTests +{ + private readonly Id3TagDtoFixture _id3TagDtoFixture = new(); + + [Fact] + public void MapArtist_WhenTheArtistNameMatchesATrackArtist_ShouldMapEveryArtistField() + { + // Arrange + Guid trackArtistId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Artist"], + albumArtists: ["Some Other Artist"], + trackArtistSortName: "Artist, The", + albumArtistSortName: "Artist, Some Other", + musicBrainzArtistId: trackArtistId.ToString(), + musicBrainzReleaseArtistId: releaseArtistId.ToString(), + website: "https://artist.example"); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Equal("The Artist", result.Name); + Assert.Equal("Artist, The", result.SortName); + Assert.Equal("https://artist.example", result.Website); + Assert.Equal(trackArtistId, result.MusicBrainzArtistId); + Assert.Null(result.Disambiguation); + Assert.Null(result.Type); + Assert.Null(result.Gender); + Assert.Null(result.Country); + Assert.Null(result.Area); + Assert.Null(result.BeginArea); + Assert.Null(result.EndArea); + Assert.Null(result.LifeSpanBegin); + Assert.Null(result.LifeSpanEnd); + Assert.False(result.IsEnded); + Assert.Null(result.Ipis); + Assert.Null(result.Isnis); + Assert.Null(result.Aliases); + Assert.Null(result.Genres); + Assert.Null(result.Tags); + Assert.Null(result.Ratings); + Assert.Null(result.Contributors); + } + + [Fact] + public void MapArtist_WhenTheArtistNameMatchesOnlyAnAlbumArtist_ShouldUseTheAlbumArtistData() + { + // Arrange + Guid trackArtistId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Some Other Artist"], + albumArtists: ["The Artist"], + trackArtistSortName: "Artist, Some Other", + albumArtistSortName: "Artist, The", + musicBrainzArtistId: trackArtistId.ToString(), + musicBrainzReleaseArtistId: releaseArtistId.ToString()); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Equal("The Artist", result.Name); + Assert.Equal("Artist, The", result.SortName); + Assert.Equal(releaseArtistId, result.MusicBrainzArtistId); + } + + [Fact] + public void MapArtist_WhenTheArtistNameIsUnknown_ShouldFallBackToTheAlbumArtist() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + albumArtists: ["Album Artist"], + trackArtistSortName: "Artist, Track", + albumArtistSortName: "Artist, Album"); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "Unknown Artist"); + + // Assert + Assert.Equal("Album Artist", result.Name); + Assert.Equal("Artist, Album", result.SortName); + } + + [Fact] + public void MapArtist_WhenTheArtistNameIsUnknownAndThereAreNoAlbumArtists_ShouldFallBackToTheTrackArtist() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + albumArtists: []); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "Unknown Artist"); + + // Assert + Assert.Equal("Track Artist", result.Name); + } + + [Fact] + public void MapArtist_WhenTheTrackArtistSortNameIsMissing_ShouldFallBackToTheAlbumArtistSortName() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Artist"], + albumArtists: ["Some Other Artist"], + includeTrackArtistSortName: false, + albumArtistSortName: "Artist, Album"); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Equal("Artist, Album", result.SortName); + } + + [Fact] + public void MapArtist_WhenTheAlbumArtistSortNameIsMissing_ShouldFallBackToTheTrackArtistSortName() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Some Other Artist"], + albumArtists: ["The Artist"], + trackArtistSortName: "Artist, Track", + includeAlbumArtistSortName: false); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Equal("Artist, Track", result.SortName); + } + + [Fact] + public void MapArtist_WhenTheUnknownArtistHasOnlyATrackArtistSortName_ShouldUseIt() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + albumArtists: [], + trackArtistSortName: "Artist, Track", + includeAlbumArtistSortName: false); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "Unknown Artist"); + + // Assert + Assert.Equal("Track Artist", result.Name); + Assert.Equal("Artist, Track", result.SortName); + } + + [Fact] + public void MapArtist_WhenTheArtistNameIsWhiteSpace_ShouldFallBackToTheCreditedArtists() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + albumArtists: ["Album Artist"]); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, " "); + + // Assert + Assert.Equal("Album Artist", result.Name); + } + + [Fact] + public void MapArtist_WhenTheIdentifierCannotBeParsed_ShouldReturnNullMusicBrainzArtistId() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Artist"], + musicBrainzArtistId: "not-a-guid", + includeMusicBrainzReleaseArtistId: false); + + // Act + ArtistMetadataDto result = Id3TagMapper.MapArtist(data, "The Artist"); + + // Assert + Assert.Null(result.MusicBrainzArtistId); + } + + [Fact] + public void MapAlbum_WhenTheTagsCarryEveryAlbumField_ShouldMapEveryField() + { + // Arrange + Guid releaseId = Guid.NewGuid(); + Guid releaseGroupId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + album: "The Album", + language: "eng", + script: "Latn", + genres: ["Rock"], + releaseTypes: ["album", "live"], + releaseStatus: "official", + mediaFormat: "CD", + packaging: "Jewel Case", + discCount: 2, + trackCount: 12, + barcode: "1234567890123", + catalogNumbers: ["CAT-1", "CAT-2"], + label: "The Label", + asin: "B000000001", + originalReleaseDate: new DateOnly(1975, 11, 21), + originalReleaseYear: 1975, + releaseCountry: "US", + musicBrainzReleaseId: releaseId.ToString(), + musicBrainzReleaseGroupId: releaseGroupId.ToString(), + musicBrainzReleaseArtistId: releaseArtistId.ToString(), + albumArtists: ["The Album Artist"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal("The Album", result.Title); + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Null(result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 11, 21), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry); + Assert.Null(result.ReleaseInfo.ReleaseVersion); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language!.LanguageCode); + Assert.Null(result.OriginalLanguage); + Assert.Null(result.Tags); + Assert.Equal(["Rock"], result.Genres!.Select(genre => genre.Name)); + Assert.Equal("Latn", result.Script); + Assert.Equal([MusicReleaseType.Album, MusicReleaseType.Live], result.ReleaseTypes); + Assert.Equal(MusicReleaseStatus.Official, result.ReleaseStatus); + Assert.Equal(MusicMediaFormat.CD, result.MediaFormat); + Assert.Equal(MusicReleasePackaging.JewelCase, result.Packaging); + Assert.Equal(2, result.TotalDiscs); + Assert.Equal(12, result.TotalTracks); + Assert.Equal("1234567890123", result.Barcode); + Assert.Equal(["CAT-1", "CAT-2"], result.CatalogNumbers); + Assert.Equal("The Label", result.Label); + Assert.Equal("B000000001", result.ASIN); + Assert.Equal(releaseId, result.MusicBrainzReleaseId); + Assert.Equal(releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Album Artist", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Performer, contributor.Role); + Assert.Null(result.Ratings); + Assert.Null(result.ReleaseTitle); + } + + [Fact] + public void MapAlbum_WhenTheTagsAreEmpty_ShouldReturnNullOptionalFields() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + album: "", + includeLanguage: false, + includeScript: false, + genres: [], + releaseTypes: [], + includeReleaseStatus: false, + includeMediaFormat: false, + includePackaging: false, + discCount: 0, + trackCount: 0, + includeBarcode: false, + catalogNumbers: [], + includeLabel: false, + includeAsin: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReleaseCountry: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false, + albumArtists: [], + trackArtists: []); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.ReleaseInfo); + Assert.Null(result.Language); + Assert.Null(result.Genres); + Assert.Null(result.Script); + Assert.Null(result.ReleaseTypes); + Assert.Null(result.ReleaseStatus); + Assert.Null(result.MediaFormat); + Assert.Null(result.Packaging); + Assert.Null(result.TotalDiscs); + Assert.Null(result.TotalTracks); + Assert.Null(result.Barcode); + Assert.Null(result.CatalogNumbers); + Assert.Null(result.Label); + Assert.Null(result.ASIN); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Null(result.Contributors); + } + + [Fact] + public void MapAlbum_WhenGenresAreDuplicated_ShouldKeepOnlyTheDistinctOnes() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(genres: ["Rock", "rock", "ROCK"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(["Rock"], result.Genres!.Select(genre => genre.Name)); + } + + [Fact] + public void MapAlbum_WhenThereIsNoReleaseInformation_ShouldReturnNullReleaseInfo() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReleaseCountry: false); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Fact] + public void MapAlbum_WhenOnlyTheReleaseCountryIsPresent_ShouldBuildTheReleaseInfoFromIt() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + releaseCountry: "US"); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo!.ReleaseCountry); + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.OriginalReleaseYear); + } + + [Fact] + public void MapAlbum_WhenTheReleaseCountryIsUnknown_ShouldReturnNullReleaseCountry() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + releaseCountry: "not-a-country"); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Theory] + [InlineData("eng", "en", "English")] // a three letter code maps to the neutral culture + [InlineData("deu", "de", "German")] // another three letter code maps to the neutral culture + [InlineData("en", "en", "English")] // a two letter code maps too + [InlineData("zxx", "zxx", "No linguistic content")] // the special code of MusicBrainz + [InlineData("mul", "mul", "Multiple languages")] // the special code of MusicBrainz + [InlineData("und", "und", "Undetermined")] // the special code of MusicBrainz + [InlineData("eng/ara", "en", "English")] // only the first code of a multi language tag is used + public void MapAlbum_WhenTheLanguageCodeIsPresent_ShouldMapIt(string language, string expectedCode, string expectedName) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(language: language); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.NotNull(result.Language); + Assert.Equal(expectedCode, result.Language!.LanguageCode); + Assert.Equal(expectedName, result.Language.LanguageName); + } + + [Fact] + public void MapAlbum_WhenTheLanguageCodeIsUnknown_ShouldFallBackToTheRawCode() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(language: "qqq"); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.NotNull(result.Language); + Assert.Equal("qqq", result.Language!.LanguageCode); + Assert.Equal("qqq", result.Language.LanguageName); + Assert.Null(result.Language.NativeName); + } + + [Theory] + [InlineData("official", MusicReleaseStatus.Official)] + [InlineData("promotion", MusicReleaseStatus.Promotion)] + [InlineData("bootleg", MusicReleaseStatus.Bootleg)] + [InlineData("pseudo-release", MusicReleaseStatus.PseudoRelease)] + [InlineData("withdrawn", MusicReleaseStatus.Withdrawn)] + [InlineData("cancelled", MusicReleaseStatus.Cancelled)] + [InlineData("expunged", MusicReleaseStatus.Expunged)] + public void MapAlbum_WhenTheReleaseStatusIsKnown_ShouldMapIt(string status, MusicReleaseStatus expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseStatus: status); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(expected, result.ReleaseStatus); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapAlbum_WhenTheReleaseStatusIsUnknown_ShouldReturnNullStatus(string? status) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseStatus: status); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.ReleaseStatus); + } + + [Theory] + [InlineData("album", MusicReleaseType.Album)] + [InlineData("single", MusicReleaseType.Single)] + [InlineData("ep", MusicReleaseType.Ep)] + [InlineData("broadcast", MusicReleaseType.Broadcast)] + [InlineData("other", MusicReleaseType.Other)] + [InlineData("compilation", MusicReleaseType.Compilation)] + [InlineData("live", MusicReleaseType.Live)] + [InlineData("soundtrack", MusicReleaseType.Soundtrack)] + [InlineData("spokenword", MusicReleaseType.SpokenWord)] + [InlineData("audio drama", MusicReleaseType.AudioDrama)] + [InlineData("audiobook", MusicReleaseType.AudioBook)] + [InlineData("demo", MusicReleaseType.Demo)] + [InlineData("dj-mix", MusicReleaseType.DjMix)] + [InlineData("field recording", MusicReleaseType.FieldRecording)] + [InlineData("interview", MusicReleaseType.Interview)] + [InlineData("mixtape/street", MusicReleaseType.Mixtape)] + [InlineData("remix", MusicReleaseType.Remix)] + public void MapAlbum_WhenTheReleaseTypeIsKnown_ShouldMapIt(string releaseType, MusicReleaseType expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseTypes: [releaseType]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal([expected], result.ReleaseTypes); + } + + [Fact] + public void MapAlbum_WhenSomeReleaseTypesAreUnknown_ShouldKeepOnlyTheKnownOnesWithoutDuplicates() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseTypes: ["made-up", "album", "Album"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal([MusicReleaseType.Album], result.ReleaseTypes); + } + + [Fact] + public void MapAlbum_WhenEveryReleaseTypeIsEmptyOrUnknown_ShouldReturnNullReleaseTypes() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(releaseTypes: ["", " ", "made-up"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.ReleaseTypes); + } + + [Theory] + [InlineData("12\" vinyl", MusicMediaFormat.Inch12Vinyl)] + [InlineData("10\" vinyl", MusicMediaFormat.Inch10Vinyl)] + [InlineData("7\" vinyl", MusicMediaFormat.Inch7Vinyl)] + [InlineData("3\" vinyl", MusicMediaFormat.Inch3Vinyl)] + [InlineData("vinyl", MusicMediaFormat.Vinyl)] + [InlineData("cd", MusicMediaFormat.CD)] + [InlineData("sacd", MusicMediaFormat.SACD)] + [InlineData("hybrid sacd", MusicMediaFormat.HybridSACD)] + [InlineData("digital media", MusicMediaFormat.DigitalMedia)] + [InlineData("cassette", MusicMediaFormat.Cassette)] + [InlineData("dvd", MusicMediaFormat.DVD)] + [InlineData("dvd-video", MusicMediaFormat.DVDVideo)] + [InlineData("dvd-audio", MusicMediaFormat.DVDAudio)] + [InlineData("blu-ray", MusicMediaFormat.BluRay)] + [InlineData("minidisc", MusicMediaFormat.MiniDisc)] + [InlineData("8cm cd", MusicMediaFormat.Cm8CD)] + [InlineData("dat", MusicMediaFormat.DAT)] + [InlineData("vinyl disc", MusicMediaFormat.VinylDisc)] // parsed through the normalized fallback + [InlineData("other", MusicMediaFormat.Other)] + public void MapAlbum_WhenTheMediaFormatIsKnown_ShouldMapIt(string mediaFormat, MusicMediaFormat expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(mediaFormat: mediaFormat); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(expected, result.MediaFormat); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapAlbum_WhenTheMediaFormatIsUnknown_ShouldReturnNullMediaFormat(string? mediaFormat) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(mediaFormat: mediaFormat); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.MediaFormat); + } + + [Theory] + [InlineData("book", MusicReleasePackaging.Book)] + [InlineData("box", MusicReleasePackaging.Box)] + [InlineData("cardboard/paper sleeve", MusicReleasePackaging.CardboardPaperSleeve)] + [InlineData("jewel case", MusicReleasePackaging.JewelCase)] + [InlineData("digipak", MusicReleasePackaging.Digipak)] + [InlineData("metal tin", MusicReleasePackaging.MetalTin)] + [InlineData("none", MusicReleasePackaging.None)] + [InlineData("other", MusicReleasePackaging.Other)] + public void MapAlbum_WhenThePackagingIsKnown_ShouldMapIt(string packaging, MusicReleasePackaging expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(packaging: packaging); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(expected, result.Packaging); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapAlbum_WhenThePackagingIsUnknown_ShouldReturnNullPackaging(string? packaging) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(packaging: packaging); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.Packaging); + } + + [Fact] + public void MapAlbum_WhenAlbumArtistsArePresent_ShouldMapThemAsPerformerContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + albumArtists: ["Album Artist One", "Album Artist Two"], + trackArtists: ["Track Artist"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + Assert.All(result.Contributors, contributor => Assert.Equal(MediaContributorRole.Performer, contributor.Role)); + Assert.Equal(["Album Artist One", "Album Artist Two"], result.Contributors.Select(contributor => contributor.Name!.DisplayName)); + } + + [Fact] + public void MapAlbum_WhenThereAreNoAlbumArtists_ShouldFallBackToTheTrackArtistsForTheContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(albumArtists: [], trackArtists: ["Track Artist"]); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("Track Artist", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Performer, contributor.Role); + } + + [Fact] + public void MapAlbum_WhenThereAreNoArtistsAtAll_ShouldReturnNullContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(albumArtists: [], trackArtists: []); + + // Act + AlbumMetadataDto result = Id3TagMapper.MapAlbum(data); + + // Assert + Assert.Null(result.Contributors); + } + + [Fact] + public void MapTrack_WhenTheTagsCarryEveryTrackField_ShouldMapEveryField() + { + // Arrange + Guid recordingId = Guid.NewGuid(); + Guid releaseTrackId = Guid.NewGuid(); + Guid workId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + title: "The Track", + language: "eng", + script: "Latn", + genres: ["Rock"], + musicKey: "C#m", + bpm: 128, + isrcs: ["US1A2B3C4D5E"], + moods: ["calm"], + durationInSeconds: 215, + sampleRate: 44100, + channels: 2, + bitDepth: 24, + bitrate: 320, + audioCodec: "MPEG Audio", + originalReleaseDate: new DateOnly(1975, 11, 21), + originalReleaseYear: 1975, + releaseCountry: "US", + musicBrainzRecordingId: recordingId.ToString(), + musicBrainzReleaseTrackId: releaseTrackId.ToString(), + musicBrainzWorkId: workId.ToString(), + workTitle: "The Work", + trackArtists: ["The Artist"], + composers: ["The Composer"], + lyricists: ["The Lyricist"], + conductors: ["The Conductor"], + remixers: ["The Remixer"], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Equal("The Track", result.Title); + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Null(result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 11, 21), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language!.LanguageCode); + Assert.Null(result.OriginalLanguage); + Assert.Null(result.Tags); + Assert.Equal(["Rock"], result.Genres!.Select(genre => genre.Name)); + Assert.Equal("Latn", result.Script); + Assert.Equal(MusicKey.CSharpMinor, result.Key); + Assert.Equal(128, result.Bpm); + Assert.False(result.IsVideo); + Assert.NotNull(result.Work); + Assert.Equal(workId, result.Work!.MusicBrainzWorkId); + Assert.Equal("The Work", result.Work.Title); + Assert.Equal("US1A2B3C4D5E", Assert.Single(result.Isrcs!).Value); + Assert.Equal("calm", Assert.Single(result.Moods!).Name); + Assert.Equal(215, result.DurationInSeconds); + Assert.Equal(44100, result.SampleRate); + Assert.Equal(2, result.Channels); + Assert.Equal(24, result.BitDepth); + Assert.Equal(320, result.Bitrate); + Assert.Equal("MPEG Audio", result.AudioCodec); + Assert.Equal(recordingId, result.MusicBrainzRecordingId); + Assert.Equal(releaseTrackId, result.MusicBrainzTrackId); + Assert.Null(result.Ratings); + Assert.Equal(5, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Artist" && contributor.Role == MediaContributorRole.Performer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Composer" && contributor.Role == MediaContributorRole.Composer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Lyricist" && contributor.Role == MediaContributorRole.Lyricist); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Conductor" && contributor.Role == MediaContributorRole.Conductor); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Remixer" && contributor.Role == MediaContributorRole.Remixer); + } + + [Fact] + public void MapTrack_WhenTheTagsAreEmpty_ShouldReturnNullOptionalFields() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + title: "", + includeLanguage: false, + includeScript: false, + genres: [], + includeMusicKey: false, + includeBpm: false, + isrcs: [], + moods: [], + includeDurationInSeconds: false, + includeSampleRate: false, + includeChannels: false, + includeBitDepth: false, + includeBitrate: false, + includeAudioCodec: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReleaseCountry: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzReleaseTrackId: false, + includeMusicBrainzWorkId: false, + includeWorkTitle: false, + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.ReleaseInfo); + Assert.Null(result.Language); + Assert.Null(result.Genres); + Assert.Null(result.Script); + Assert.Null(result.Key); + Assert.Null(result.Bpm); + Assert.Null(result.Work); + Assert.Null(result.Isrcs); + Assert.Null(result.Moods); + Assert.Null(result.DurationInSeconds); + Assert.Null(result.SampleRate); + Assert.Null(result.Channels); + Assert.Null(result.BitDepth); + Assert.Null(result.Bitrate); + Assert.Null(result.AudioCodec); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Null(result.MusicBrainzTrackId); + Assert.Null(result.Contributors); + } + + [Fact] + public void MapTrack_WhenThereIsNoReleaseInformation_ShouldReturnNullReleaseInfo() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReleaseCountry: false); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Fact] + public void MapTrack_WhenOnlyTheReleaseCountryIsPresent_ShouldBuildTheReleaseInfoFromIt() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + releaseCountry: "US"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo!.ReleaseCountry); + } + + [Fact] + public void MapTrack_WhenBothTheWorkIdAndTheWorkTitleArePresent_ShouldMapTheWork() + { + // Arrange + Guid workId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: workId.ToString(), + workTitle: "The Work"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.NotNull(result.Work); + Assert.Equal(workId, result.Work!.MusicBrainzWorkId); + Assert.Equal("The Work", result.Work.Title); + Assert.Null(result.Work.Type); + Assert.Null(result.Work.Languages); + Assert.Null(result.Work.Iswcs); + } + + [Fact] + public void MapTrack_WhenTheWorkIdIsSlashSeparated_ShouldUseTheFirstParsableIdentifier() + { + // Arrange + Guid workId = Guid.NewGuid(); + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: $"not-a-guid/{workId}", + workTitle: "The Work"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.NotNull(result.Work); + Assert.Equal(workId, result.Work!.MusicBrainzWorkId); + } + + [Fact] + public void MapTrack_WhenTheWorkTitleIsSlashSeparated_ShouldUseTheFirstValue() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: Guid.NewGuid().ToString(), + workTitle: "The Work/Alternate"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.NotNull(result.Work); + Assert.Equal("The Work", result.Work!.Title); + } + + [Fact] + public void MapTrack_WhenOnlyTheWorkIdIsPresent_ShouldReturnNullWork() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: Guid.NewGuid().ToString(), + includeWorkTitle: false); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Work); + } + + [Fact] + public void MapTrack_WhenOnlyTheWorkTitleIsPresent_ShouldReturnNullWork() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + includeMusicBrainzWorkId: false, + workTitle: "The Work"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Work); + } + + [Fact] + public void MapTrack_WhenTheWorkIdCannotBeParsed_ShouldReturnNullWork() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + musicBrainzWorkId: "not-a-guid/also-not-a-guid", + workTitle: "The Work"); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Work); + } + + [Theory] + [InlineData("C", MusicKey.CMajor)] + [InlineData("C major", MusicKey.CMajor)] + [InlineData("C maj", MusicKey.CMajor)] + [InlineData("Cm", MusicKey.CMinor)] + [InlineData("C min", MusicKey.CMinor)] + [InlineData("C#m", MusicKey.CSharpMinor)] + [InlineData("C# minor", MusicKey.CSharpMinor)] + [InlineData("Db", MusicKey.CSharpMajor)] + [InlineData("D", MusicKey.DMajor)] + [InlineData("Dm", MusicKey.DMinor)] + [InlineData("D# minor", MusicKey.DSharpMinor)] + [InlineData("E", MusicKey.EMajor)] + [InlineData("Em", MusicKey.EMinor)] + [InlineData("F", MusicKey.FMajor)] + [InlineData("Fm", MusicKey.FMinor)] + [InlineData("G", MusicKey.GMajor)] + [InlineData("Gm", MusicKey.GMinor)] + [InlineData("E\u266d", MusicKey.DSharpMajor)] // the flat sign is normalized to the sharp equivalent + [InlineData("F# major", MusicKey.FSharpMajor)] + [InlineData("Gb", MusicKey.FSharpMajor)] + [InlineData("G#m", MusicKey.GSharpMinor)] + [InlineData("Ab", MusicKey.GSharpMajor)] + [InlineData("A#m", MusicKey.ASharpMinor)] + [InlineData("Bb", MusicKey.ASharpMajor)] + [InlineData("am", MusicKey.AMinor)] + [InlineData("b", MusicKey.BMajor)] + public void MapTrack_WhenTheMusicalKeyIsKnown_ShouldMapIt(string musicKey, MusicKey expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(musicKey: musicKey); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Equal(expected, result.Key); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("H")] + [InlineData("Hm")] + public void MapTrack_WhenTheMusicalKeyIsUnknown_ShouldReturnNullKey(string? musicKey) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(musicKey: musicKey); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Key); + } + + [Fact] + public void MapTrack_WhenTheTrackArtistsArePresent_ShouldMapThemAsPerformerContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["Track Artist"], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("Track Artist", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Performer, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheComposersArePresent_ShouldMapThemAsComposerContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: ["The Composer"], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Composer", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Composer, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheLyricistsArePresent_ShouldMapThemAsLyricistContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: ["The Lyricist"], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Lyricist", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Lyricist, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheConductorsArePresent_ShouldMapThemAsConductorContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: ["The Conductor"], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Conductor", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Conductor, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheRemixersArePresent_ShouldMapThemAsRemixerContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: ["The Remixer"], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Remixer", contributor.Name!.DisplayName); + Assert.Equal(MediaContributorRole.Remixer, contributor.Role); + } + + [Theory] + [InlineData("producer", MediaContributorRole.Producer)] + [InlineData("executive producer", MediaContributorRole.ExecutiveProducer)] + [InlineData("backing vocals", MediaContributorRole.BackingVocals)] + [InlineData("vocals", MediaContributorRole.Vocals)] + [InlineData("electric bass", MediaContributorRole.BassGuitar)] + [InlineData("bass", MediaContributorRole.BassGuitar)] + [InlineData("guitar", MediaContributorRole.Guitar)] + [InlineData("drums", MediaContributorRole.Drums)] + [InlineData("membranophone", MediaContributorRole.Drums)] + [InlineData("percussion", MediaContributorRole.Percussion)] + [InlineData("tambourine", MediaContributorRole.Percussion)] + [InlineData("keyboard", MediaContributorRole.Keyboards)] + [InlineData("piano", MediaContributorRole.Piano)] + [InlineData("synthesizer", MediaContributorRole.Synthesizer)] + [InlineData("sampler", MediaContributorRole.Synthesizer)] + [InlineData("violin", MediaContributorRole.Strings)] + [InlineData("trumpet", MediaContributorRole.Brass)] + [InlineData("flute", MediaContributorRole.Woodwinds)] + [InlineData("remix", MediaContributorRole.Remixer)] + [InlineData("mastering", MediaContributorRole.Engineer)] + [InlineData("mix", MediaContributorRole.Mixer)] + [InlineData("arranger", MediaContributorRole.Arranger)] + [InlineData("conductor", MediaContributorRole.Conductor)] + [InlineData("orchestrator", MediaContributorRole.Orchestrator)] + [InlineData("composer", MediaContributorRole.Composer)] + [InlineData("librettist", MediaContributorRole.Lyricist)] + [InlineData("author", MediaContributorRole.Author)] + [InlineData("chorus", MediaContributorRole.Choir)] + [InlineData("member of band", MediaContributorRole.Performer)] + [InlineData("orchestra", MediaContributorRole.Performer)] + [InlineData("made-up role", MediaContributorRole.Other)] + public void MapTrack_WhenInvolvedPeopleArePresent_ShouldMapTheirRoles(string role, MediaContributorRole expected) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: [(role, "The Person")]); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Person", contributor.Name!.DisplayName); + Assert.Equal(expected, contributor.Role); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void MapTrack_WhenAnInvolvedPersonHasNoRole_ShouldMapThemAsOther(string? role) + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: [(role!, "The Person")]); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal(MediaContributorRole.Other, contributor.Role); + } + + [Fact] + public void MapTrack_WhenTheSameContributorIsCreditedTwiceWithTheSameRole_ShouldKeepASingleContributor() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Artist", "The Artist"], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Single(result.Contributors!); + } + + [Fact] + public void MapTrack_WhenTheSameNameIsCreditedWithTwoRoles_ShouldKeepBothContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["The Person"], + composers: ["The Person"], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + } + + [Fact] + public void MapTrack_WhenAContributorNameIsWhiteSpace_ShouldSkipIt() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: ["", " "], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Contributors); + } + + [Fact] + public void MapTrack_WhenThereAreNoContributors_ShouldReturnNullContributors() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create( + trackArtists: [], + composers: [], + lyricists: [], + conductors: [], + remixers: [], + involvedPeople: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Contributors); + } + + [Fact] + public void MapTrack_WhenTheIsrcsAreDuplicated_ShouldKeepOnlyTheDistinctOnes() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(isrcs: ["US1A2B3C4D5E", "us1a2b3c4d5e"]); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Single(result.Isrcs!); + } + + [Fact] + public void MapTrack_WhenTheMoodsAreDuplicated_ShouldKeepOnlyTheDistinctOnes() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(moods: ["calm", "CALM"]); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Single(result.Moods!); + } + + [Fact] + public void MapTrack_WhenTheMoodsAreAbsent_ShouldReturnNullMoods() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(moods: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Moods); + } + + [Fact] + public void MapTrack_WhenTheGenresAreAbsent_ShouldReturnNullGenres() + { + // Arrange + Id3TagDto data = _id3TagDtoFixture.Create(genres: []); + + // Act + AudioMetadataDto result = Id3TagMapper.MapTrack(data); + + // Assert + Assert.Null(result.Genres); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/Id3TagReaderTests.cs b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/Id3TagReaderTests.cs new file mode 100644 index 00000000..72cb56cf --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Core/Tags/Id3TagReaderTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.ID3.Common.Models.DTO.Tags; +using Lumina.Plugins.ID3.Core.Tags; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.ID3.UnitTests.Core.Tags; + +/// +/// Contains unit tests for the class, covering the guard branches that do not reach the tagging library. +/// +[ExcludeFromCodeCoverage] +public class Id3TagReaderTests : IDisposable +{ + private readonly Id3TagReader _sut = new(); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public Id3TagReaderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-id3-reader-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Read_WhenPathIsNull_ShouldReturnNull() + { + // Act + Id3TagDto? result = _sut.Read(null!); + + // Assert + Assert.Null(result); + } + + [Theory] + [InlineData("")] // an empty path + [InlineData(" ")] // a white space path + public void Read_WhenPathIsEmptyOrWhiteSpace_ShouldReturnNull(string path) + { + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Read_WhenTheFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string path = Path.Combine(_temporaryDirectory, "missing.wav"); + + // Act + Id3TagDto? result = _sut.Read(path); + + // Assert + Assert.Null(result); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Lumina.Plugins.ID3.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Lumina.Plugins.ID3.UnitTests.csproj new file mode 100644 index 00000000..40ed8eab --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.ID3.UnitTests/Lumina.Plugins.ID3.UnitTests.csproj @@ -0,0 +1,49 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + +