mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the ID3 music metadata plugin and its unit and integration test suites
This commit is contained in:
1 parent
80af18170a
commit
1ffa14cec4
27 files changed
+4842
No files matched your search
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Utility class for registering the services of the ID3 metadata provider into the Dependency Injection container.
|
||||
/// </summary>
|
||||
internal static class Id3Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the services of the ID3 metadata providers into the Dependency Injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
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<Id3TagReader>();
|
||||
|
||||
// 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<IMetadataProvider, Id3ArtistMetadataProvider>(pluginId);
|
||||
services.AddKeyedTransient<IMetadataProvider, Id3AlbumMetadataProvider>(pluginId);
|
||||
services.AddKeyedTransient<IMetadataProvider, Id3TrackMetadataProvider>(pluginId);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.ID3.Common.Models.DTO.Tags;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class Id3TagDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or initializes the title of the track.
|
||||
/// </summary>
|
||||
public string? Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the title of the album the track belongs to.
|
||||
/// </summary>
|
||||
public string? Album { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the artists credited on the track.
|
||||
/// </summary>
|
||||
public List<string> TrackArtists { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the artists credited on the album.
|
||||
/// </summary>
|
||||
public List<string> AlbumArtists { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the sort name of the album artist.
|
||||
/// </summary>
|
||||
public string? AlbumArtistSortName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the sort name of the track artist.
|
||||
/// </summary>
|
||||
public string? TrackArtistSortName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the number of the track on its disc.
|
||||
/// </summary>
|
||||
public uint TrackNumber { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the number of tracks on the disc, as reported by the tags.
|
||||
/// </summary>
|
||||
public uint TrackCount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the number of the disc the track belongs to.
|
||||
/// </summary>
|
||||
public uint DiscNumber { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the number of discs of the release, as reported by the tags.
|
||||
/// </summary>
|
||||
public uint DiscCount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the year the track was released.
|
||||
/// </summary>
|
||||
public int? Year { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the original release date of the track.
|
||||
/// </summary>
|
||||
public DateOnly? OriginalReleaseDate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the original release year of the track.
|
||||
/// </summary>
|
||||
public int? OriginalReleaseYear { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the genres the tags associate with the track.
|
||||
/// </summary>
|
||||
public List<string> Genres { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the composers credited on the track.
|
||||
/// </summary>
|
||||
public List<string> Composers { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the lyricists credited on the track.
|
||||
/// </summary>
|
||||
public List<string> Lyricists { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the conductors credited on the track.
|
||||
/// </summary>
|
||||
public List<string> Conductors { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the remixers credited on the track.
|
||||
/// </summary>
|
||||
public List<string> Remixers { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the people credited on the track, each with the free-form role read from the tags.
|
||||
/// </summary>
|
||||
public List<(string Role, string Name)> InvolvedPeople { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the language of the track.
|
||||
/// </summary>
|
||||
public string? Language { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the script used by the language of the track.
|
||||
/// </summary>
|
||||
public string? Script { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the label that issued the album.
|
||||
/// </summary>
|
||||
public string? Label { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the catalog numbers of the album.
|
||||
/// </summary>
|
||||
public List<string> CatalogNumbers { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the barcode of the album.
|
||||
/// </summary>
|
||||
public string? Barcode { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the types of the release, as read from the tags.
|
||||
/// </summary>
|
||||
public List<string> ReleaseTypes { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the status of the release.
|
||||
/// </summary>
|
||||
public string? ReleaseStatus { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the country the release was issued in.
|
||||
/// </summary>
|
||||
public string? ReleaseCountry { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the physical or digital medium of the release.
|
||||
/// </summary>
|
||||
public string? MediaFormat { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the outermost packaging of the release.
|
||||
/// </summary>
|
||||
public string? Packaging { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the ASIN of the album.
|
||||
/// </summary>
|
||||
public string? Asin { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the ISRCs of the track.
|
||||
/// </summary>
|
||||
public List<string> Isrcs { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the moods of the track.
|
||||
/// </summary>
|
||||
public List<string> Moods { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the title of the work the track is a recording of.
|
||||
/// </summary>
|
||||
public string? WorkTitle { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the musical key of the track.
|
||||
/// </summary>
|
||||
public string? MusicKey { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the tempo of the track in beats per minute.
|
||||
/// </summary>
|
||||
public int? Bpm { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the duration of the audio of the track in seconds.
|
||||
/// </summary>
|
||||
public int? DurationInSeconds { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the sample rate of the audio of the track in Hz.
|
||||
/// </summary>
|
||||
public int? SampleRate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the number of audio channels of the track.
|
||||
/// </summary>
|
||||
public int? Channels { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the bit depth of the audio of the track.
|
||||
/// </summary>
|
||||
public int? BitDepth { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the bitrate of the audio of the track in kbps.
|
||||
/// </summary>
|
||||
public int? Bitrate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the description of the audio codec of the track.
|
||||
/// </summary>
|
||||
public string? AudioCodec { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the official website associated with the artist.
|
||||
/// </summary>
|
||||
public string? Website { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the MusicBrainz identifier of the artist.
|
||||
/// </summary>
|
||||
public string? MusicBrainzArtistId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the MusicBrainz identifier of the release artist.
|
||||
/// </summary>
|
||||
public string? MusicBrainzReleaseArtistId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the MusicBrainz identifier of the release group.
|
||||
/// </summary>
|
||||
public string? MusicBrainzReleaseGroupId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the MusicBrainz identifier of the release.
|
||||
/// </summary>
|
||||
public string? MusicBrainzReleaseId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the MusicBrainz identifier of the recording of the track.
|
||||
/// </summary>
|
||||
public string? MusicBrainzRecordingId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the MusicBrainz identifier of the track on its release.
|
||||
/// </summary>
|
||||
public string? MusicBrainzReleaseTrackId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or initializes the MusicBrainz identifier of the work the track is a recording of.
|
||||
/// </summary>
|
||||
public string? MusicBrainzWorkId { get; init; }
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Provides album metadata from the embedded tags of one of its audio files, by resolving lookups into album metadata DTOs.
|
||||
/// </summary>
|
||||
internal sealed class Id3AlbumMetadataProvider : IMetadataProvider<AlbumMetadataLookupDto, AlbumMetadataDto>
|
||||
{
|
||||
private readonly Id3TagReader _tagReader;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the metadata provider.
|
||||
/// </summary>
|
||||
public string Name => "ID3";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library types this metadata provider supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
|
||||
/// </summary>
|
||||
public bool RequiresWebAccess => false;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Id3AlbumMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
|
||||
public Id3AlbumMetadataProvider(Id3TagReader tagReader)
|
||||
{
|
||||
_tagReader = tagReader;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Searches for the metadata of the album described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the album to search for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The collection of album metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
|
||||
public async Task<IReadOnlyList<AlbumMetadataDto>> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
AlbumMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<AlbumMetadataDto> results = metadata is null ? [] : [metadata];
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the metadata of the album described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the album to get the metadata for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The metadata of the album, or <see langword="null"/> when the file carries none.</returns>
|
||||
public Task<AlbumMetadataDto?> GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
return ReadMetadataAsync(lookup.Path, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the metadata of the album from the embedded tags of the track stored at <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of a track of the album.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The metadata of the album, or <see langword="null"/> when the tags carry no album title.</returns>
|
||||
private Task<AlbumMetadataDto?> 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Provides music artist metadata from the embedded tags of one of its audio files, by resolving lookups into artist metadata DTOs.
|
||||
/// </summary>
|
||||
internal sealed class Id3ArtistMetadataProvider : IMetadataProvider<ArtistMetadataLookupDto, ArtistMetadataDto>
|
||||
{
|
||||
private readonly Id3TagReader _tagReader;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the metadata provider.
|
||||
/// </summary>
|
||||
public string Name => "ID3";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library types this metadata provider supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
|
||||
/// </summary>
|
||||
public bool RequiresWebAccess => false;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Id3ArtistMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
|
||||
public Id3ArtistMetadataProvider(Id3TagReader tagReader)
|
||||
{
|
||||
_tagReader = tagReader;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Searches for the metadata of the artist described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the artist to search for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The collection of artist metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
|
||||
public async Task<IReadOnlyList<ArtistMetadataDto>> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
ArtistMetadataDto? metadata = await ReadMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<ArtistMetadataDto> results = metadata is null ? [] : [metadata];
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the metadata of the artist described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the artist to get the metadata for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The metadata of the artist, or <see langword="null"/> when the file carries none.</returns>
|
||||
public Task<ArtistMetadataDto?> GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
return ReadMetadataAsync(lookup, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the metadata of the artist described by <paramref name="lookup"/> from the embedded tags of the track stored at its path.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the artist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The metadata of the artist, or <see langword="null"/> when the tags carry no artist name.</returns>
|
||||
private Task<ArtistMetadataDto?> 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Plugin that populates music metadata exclusively from the embedded tags of the audio files, without accessing the web.
|
||||
/// </summary>
|
||||
public sealed class Id3Plugin : IPlugin, IPluginServiceRegistrator
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public static readonly Guid s_pluginId = new("a3f1c8d2-6b47-4e9a-8c15-2d7f9e4b6a03");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public Guid Id => s_pluginId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the plugin.
|
||||
/// </summary>
|
||||
public string Name => "ID3 Metadata";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the author of the plugin.
|
||||
/// </summary>
|
||||
public string Author => "Lumina";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the version of the plugin.
|
||||
/// </summary>
|
||||
public Version Version => new(1, 0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the description of the plugin.
|
||||
/// </summary>
|
||||
public string Description => "Populates artist, album and track metadata from the embedded tags of the audio files, without accessing the web.";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings schema of the plugin.
|
||||
/// </summary>
|
||||
/// <returns>The settings descriptors of the plugin.</returns>
|
||||
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services required by the plugin.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
public void RegisterServices(IServiceCollection services)
|
||||
{
|
||||
services.AddId3MetadataProviders(pluginId: Id);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Provides track metadata from the embedded tags of the audio file, by resolving lookups into audio metadata DTOs.
|
||||
/// </summary>
|
||||
internal sealed class Id3TrackMetadataProvider : IMetadataProvider<TrackMetadataLookupDto, AudioMetadataDto>
|
||||
{
|
||||
private readonly Id3TagReader _tagReader;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the metadata provider.
|
||||
/// </summary>
|
||||
public string Name => "ID3";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library types this metadata provider supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
|
||||
/// </summary>
|
||||
public bool RequiresWebAccess => false;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Id3TrackMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
|
||||
public Id3TrackMetadataProvider(Id3TagReader tagReader)
|
||||
{
|
||||
_tagReader = tagReader;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Searches for the metadata of the track described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the track to search for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The collection of track metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
|
||||
public async Task<IReadOnlyList<AudioMetadataDto>> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
AudioMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<AudioMetadataDto> results = metadata is null ? [] : [metadata];
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the metadata of the track described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the track to get the metadata for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The metadata of the track, or <see langword="null"/> when the file carries none.</returns>
|
||||
public Task<AudioMetadataDto?> GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
return ReadMetadataAsync(lookup.Path, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the metadata of the track stored at <paramref name="path"/> from its embedded tags.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the track.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The metadata of the track, or <see langword="null"/> when the tags carry no title.</returns>
|
||||
private Task<AudioMetadataDto?> 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Maps the metadata read from the embedded tags of an audio file into the application's media metadata DTOs.
|
||||
/// </summary>
|
||||
internal static class Id3TagMapper
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, CultureInfo> s_culturesByLanguageCode = BuildCulturesByLanguageCode();
|
||||
|
||||
/// <summary>
|
||||
/// Builds the map of the neutral cultures of the application, keyed by their language codes.
|
||||
/// </summary>
|
||||
/// <returns>The cultures, keyed by both their two letter and three letter language codes.</returns>
|
||||
private static Dictionary<string, CultureInfo> BuildCulturesByLanguageCode()
|
||||
{
|
||||
Dictionary<string, CultureInfo> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the tags of an audio file into artist metadata.
|
||||
/// </summary>
|
||||
/// <param name="data">The tags of a track of the artist.</param>
|
||||
/// <param name="artistName">The name of the artist the metadata is mapped for, when known, used to select the matching credited artist.</param>
|
||||
/// <returns>The mapped artist metadata.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the tags of an audio file into album metadata.
|
||||
/// </summary>
|
||||
/// <param name="data">The tags of a track of the album.</param>
|
||||
/// <returns>The mapped album metadata.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the tags of an audio file into track metadata.
|
||||
/// </summary>
|
||||
/// <param name="data">The tags of the track.</param>
|
||||
/// <returns>The mapped track metadata.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the release information of the metadata from the tags, or <see langword="null"/> when the tags carry none of it.
|
||||
/// </summary>
|
||||
/// <param name="data">The tags of the track.</param>
|
||||
/// <returns>The release information, or <see langword="null"/> when the tags carry no release field.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the work of the track, or <see langword="null"/> when the tags carry none.
|
||||
/// </summary>
|
||||
/// <param name="data">The tags of the track.</param>
|
||||
/// <returns>The mapped work, or <see langword="null"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the contributors credited on the track, each with its canonical role.
|
||||
/// </summary>
|
||||
/// <param name="data">The tags of the track.</param>
|
||||
/// <returns>The mapped contributors, or <see langword="null"/> when the tags credit none.</returns>
|
||||
private static List<MediaContributorDto>? MapTrackContributors(Id3TagDto data)
|
||||
{
|
||||
List<MediaContributorDto> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the contributors credited on the album, which the tags only expose as the album artists.
|
||||
/// </summary>
|
||||
/// <param name="data">The tags of a track of the album.</param>
|
||||
/// <returns>The mapped contributors, or <see langword="null"/> when the tags credit none.</returns>
|
||||
private static List<MediaContributorDto>? MapAlbumContributors(Id3TagDto data)
|
||||
{
|
||||
List<string> artists = data.AlbumArtists.Count > 0 ? data.AlbumArtists : data.TrackArtists;
|
||||
List<MediaContributorDto> contributors = [];
|
||||
foreach (string artist in artists)
|
||||
AddContributor(contributors, artist, MediaContributorRole.Performer);
|
||||
return contributors.Count > 0 ? contributors : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the genres of the metadata, without duplicates.
|
||||
/// </summary>
|
||||
/// <param name="genres">The genre names read from the tags.</param>
|
||||
/// <returns>The mapped genres, or <see langword="null"/> when there are none.</returns>
|
||||
private static List<GenreDto>? MapGenres(List<string> genres)
|
||||
{
|
||||
List<GenreDto> result = [.. genres
|
||||
.Where(genre => !string.IsNullOrWhiteSpace(genre))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.Select(genre => new GenreDto(genre))];
|
||||
return result.Count > 0 ? result : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the moods of the metadata, without duplicates.
|
||||
/// </summary>
|
||||
/// <param name="moods">The mood names read from the tags.</param>
|
||||
/// <returns>The mapped moods, or <see langword="null"/> when there are none.</returns>
|
||||
private static List<MoodDto>? MapMoods(List<string> moods)
|
||||
{
|
||||
List<MoodDto> result = [.. moods
|
||||
.Where(mood => !string.IsNullOrWhiteSpace(mood))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.Select(mood => new MoodDto(mood))];
|
||||
return result.Count > 0 ? result : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the ISRCs of the track, without duplicates.
|
||||
/// </summary>
|
||||
/// <param name="isrcs">The ISRC values read from the tags.</param>
|
||||
/// <returns>The mapped ISRCs, or <see langword="null"/> when there are none.</returns>
|
||||
private static List<IsrcDto>? MapIsrcs(List<string> isrcs)
|
||||
{
|
||||
List<IsrcDto> result = [.. isrcs
|
||||
.Where(isrc => !string.IsNullOrWhiteSpace(isrc))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.Select(isrc => new IsrcDto(isrc))];
|
||||
return result.Count > 0 ? result : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps the types of the release into the application enum, without duplicates.
|
||||
/// </summary>
|
||||
/// <param name="releaseTypes">The free-form release types read from the tags.</param>
|
||||
/// <returns>The mapped release types, or <see langword="null"/> when there are none.</returns>
|
||||
private static List<MusicReleaseType>? MapReleaseTypes(List<string> releaseTypes)
|
||||
{
|
||||
List<MusicReleaseType> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a single free-form release type into the application enum.
|
||||
/// </summary>
|
||||
/// <param name="releaseType">The release type to map.</param>
|
||||
/// <returns>The mapped release type, or <see langword="null"/> when the type is unknown.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a free-form release status into the application enum.
|
||||
/// </summary>
|
||||
/// <param name="releaseStatus">The release status to map.</param>
|
||||
/// <returns>The mapped release status, or <see langword="null"/> when the status is unknown.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps an ISO 3166-1 alpha-2 country code into the application enum.
|
||||
/// </summary>
|
||||
/// <param name="country">The country code to map.</param>
|
||||
/// <returns>The mapped release country, or <see langword="null"/> when the code is unknown.</returns>
|
||||
private static ReleaseCountry? MapReleaseCountry(string? country)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(country))
|
||||
return null;
|
||||
return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a free-form media format into the application enum.
|
||||
/// </summary>
|
||||
/// <param name="mediaFormat">The media format to map.</param>
|
||||
/// <returns>The mapped media format, or <see langword="null"/> when the format is unknown.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a free-form packaging into the application enum.
|
||||
/// </summary>
|
||||
/// <param name="packaging">The packaging to map.</param>
|
||||
/// <returns>The mapped packaging, or <see langword="null"/> when the packaging is unknown.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a free-form musical key into the application enum.
|
||||
/// </summary>
|
||||
/// <param name="musicKey">The musical key to map.</param>
|
||||
/// <returns>The mapped musical key, or <see langword="null"/> when the key is unknown.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a free-form ISO 639 language code into language information.
|
||||
/// </summary>
|
||||
/// <param name="rawCode">The code to map.</param>
|
||||
/// <returns>The mapped language, or <see langword="null"/> when the code is empty.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a free-form contributor role into a canonical media contributor role.
|
||||
/// </summary>
|
||||
/// <param name="role">The role to map.</param>
|
||||
/// <returns>The mapped contributor role.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a contributor to the provided list, unless an identical name and role pair is already present.
|
||||
/// </summary>
|
||||
/// <param name="contributors">The contributors collected so far.</param>
|
||||
/// <param name="displayName">The display name of the contributor.</param>
|
||||
/// <param name="role">The role the contributor played.</param>
|
||||
private static void AddContributor(List<MediaContributorDto> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the provided value as a globally unique identifier.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to parse.</param>
|
||||
/// <returns>The parsed identifier, or <see langword="null"/> when the value is missing or malformed.</returns>
|
||||
private static Guid? ParseGuid(string? value)
|
||||
{
|
||||
return Guid.TryParse(value, out Guid parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the first globally unique identifier of a value that may hold several slash-separated identifiers.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to parse.</param>
|
||||
/// <returns>The first parsed identifier, or <see langword="null"/> when the value holds none.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the first value of a tag that may hold several slash-separated values.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to read.</param>
|
||||
/// <returns>The first non-empty value, or <see langword="null"/> when the value is empty.</returns>
|
||||
private static string? FirstValue(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return null;
|
||||
return NullIfWhiteSpace(value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).FirstOrDefault());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to process.</param>
|
||||
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
|
||||
private static string? NullIfWhiteSpace(string? value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class Id3TagReader
|
||||
{
|
||||
/// <summary>
|
||||
/// The container tag types whose extended tags are searched, in the order they are tried.
|
||||
/// </summary>
|
||||
private static readonly TagLib.TagTypes[] s_extendedTagContainerTypes = [TagLib.TagTypes.Xiph, TagLib.TagTypes.Id3v2, TagLib.TagTypes.Apple, TagLib.TagTypes.Ape];
|
||||
|
||||
/// <summary>
|
||||
/// The keys of the free-form Apple tags that carry the involved people of a track, paired with the role each of them describes.
|
||||
/// </summary>
|
||||
private static readonly (string Role, string Key)[] s_appleInvolvedPeopleKeys =
|
||||
[
|
||||
("performer", "performer"),
|
||||
("producer", "PRODUCER"),
|
||||
("engineer", "ENGINEER"),
|
||||
("mixer", "MIXER"),
|
||||
("arranger", "arranger"),
|
||||
("writer", "writer")
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Matches a four digit year.
|
||||
/// </summary>
|
||||
private static readonly Regex s_yearPattern = new(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private const int MAX_CACHED_SNAPSHOTS = 512;
|
||||
|
||||
private readonly Dictionary<string, Id3TagDto> _cache = new(StringComparer.Ordinal);
|
||||
private readonly Queue<string> _cacheOrder = new();
|
||||
private readonly Lock _cacheLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Reads the embedded tags of the audio file stored at <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the audio file whose tags are read.</param>
|
||||
/// <returns>The snapshot of the tags, or <see langword="null"/> when the file does not exist or its tags cannot be read.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the snapshot that was cached first, keeping the cache within its maximum size.
|
||||
/// </summary>
|
||||
private void EvictOldestSnapshot()
|
||||
{
|
||||
if (_cacheOrder.Count == 0)
|
||||
return;
|
||||
string oldestPath = _cacheOrder.Dequeue();
|
||||
_cache.Remove(oldestPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the embedded tags of the audio file stored at <paramref name="path"/> into a snapshot.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the audio file whose tags are read.</param>
|
||||
/// <returns>The snapshot of the tags, or <see langword="null"/> when the file does not exist or its tags cannot be read.</returns>
|
||||
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<Func<string, List<string>>> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the people credited on the track, together with the free-form role each of them is credited for.
|
||||
/// </summary>
|
||||
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
|
||||
/// <returns>The people credited on the track, as role and name pairs.</returns>
|
||||
private static List<(string Role, string Name)> ReadInvolvedPeople(List<Func<string, List<string>>> 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<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the ISRCs of the track, from both the dedicated tag and the extended tags, without duplicates.
|
||||
/// </summary>
|
||||
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
|
||||
/// <param name="tag">The combined tag of the file.</param>
|
||||
/// <returns>The ISRCs of the track.</returns>
|
||||
private static List<string> ReadIsrcs(List<Func<string, List<string>>> extendedFields, TagLib.Tag tag)
|
||||
{
|
||||
List<string> values = SplitValues(GetExtendedFields(extendedFields, "ISRC", "TSRC"));
|
||||
if (!string.IsNullOrWhiteSpace(tag.ISRC))
|
||||
values.AddRange(SplitValues([tag.ISRC]));
|
||||
return [.. values.Distinct(StringComparer.OrdinalIgnoreCase)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the ordered accessors that resolve an extended tag value from whichever container tag of the file carries it.
|
||||
/// </summary>
|
||||
/// <param name="tagFile">The file whose extended tags are read.</param>
|
||||
/// <returns>The accessors, in the order the containers are searched.</returns>
|
||||
private static List<Func<string, List<string>>> BuildExtendedFieldSources(TagLib.File tagFile)
|
||||
{
|
||||
List<Func<string, List<string>>> 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<string, List<string>> id3Fields = BuildId3v2Fields(id3v2Tag);
|
||||
sources.Add(key => id3Fields.TryGetValue(key, out List<string>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="id3v2Tag">The ID3v2 tag whose frames are indexed.</param>
|
||||
/// <returns>The values of every frame, keyed by the frame identifier or the description of a user defined frame.</returns>
|
||||
private static Dictionary<string, List<string>> BuildId3v2Fields(TagLib.Id3v2.Tag id3v2Tag)
|
||||
{
|
||||
Dictionary<string, List<string>> fields = new(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (TagLib.Id3v2.Frame frame in id3v2Tag.GetFrames())
|
||||
{
|
||||
string key;
|
||||
List<string> 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<string>? existing))
|
||||
existing.AddRange(values);
|
||||
else
|
||||
fields[key] = values;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the values of a free-form Apple tag with the provided <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="appleTag">The Apple tag whose values are read.</param>
|
||||
/// <param name="key">The name of the free-form tag to read.</param>
|
||||
/// <returns>Every value of the tag.</returns>
|
||||
private static List<string> GetAppleFields(TagLib.Mpeg4.AppleTag appleTag, string key)
|
||||
{
|
||||
List<string> values = [];
|
||||
foreach (string appleValue in appleTag.GetDashBoxes("com.apple.iTunes", key) ?? [])
|
||||
values.AddRange(appleValue.Split('\0', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
|
||||
return values;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the values of an APE tag with the provided <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="apeTag">The APE tag whose values are read.</param>
|
||||
/// <param name="key">The name of the tag to read.</param>
|
||||
/// <returns>Every value of the tag.</returns>
|
||||
private static List<string> GetApeFields(TagLib.Ape.Tag apeTag, string key)
|
||||
{
|
||||
if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem)
|
||||
return [.. apeItem.ToStringArray()];
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the first non-empty value of an extended tag, from whichever container tag of the file carries it.
|
||||
/// </summary>
|
||||
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
|
||||
/// <param name="keys">The candidate names of the extended tag to read, in the order they are tried.</param>
|
||||
/// <returns>The first non-empty value found, or <see langword="null"/> when the file carries none of the provided tags.</returns>
|
||||
private static string? GetExtendedField(List<Func<string, List<string>>> extendedFields, params string[] keys)
|
||||
{
|
||||
foreach (Func<string, List<string>> extendedField in extendedFields)
|
||||
{
|
||||
foreach (string key in keys)
|
||||
{
|
||||
List<string> values = extendedField(key);
|
||||
string? value = values.FirstOrDefault(candidate => !string.IsNullOrWhiteSpace(candidate));
|
||||
if (!string.IsNullOrWhiteSpace(value))
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads every value of an extended tag, from whichever container tag of the file carries it.
|
||||
/// </summary>
|
||||
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
|
||||
/// <param name="keys">The candidate names of the extended tag to read, in the order they are tried.</param>
|
||||
/// <returns>Every non-empty value found, or an empty list when the file carries none of the provided tags.</returns>
|
||||
private static List<string> GetExtendedFields(List<Func<string, List<string>>> extendedFields, params string[] keys)
|
||||
{
|
||||
List<string> values = [];
|
||||
foreach (Func<string, List<string>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps only the non-empty values of the provided collection, trimmed.
|
||||
/// </summary>
|
||||
/// <param name="values">The values to filter.</param>
|
||||
/// <returns>The non-empty, trimmed values.</returns>
|
||||
private static List<string> Filter(IEnumerable<string>? values)
|
||||
{
|
||||
return [.. (values ?? []).Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits every provided value on the separators used to pack several values into a single tag, and keeps the non-empty results.
|
||||
/// </summary>
|
||||
/// <param name="values">The values to split.</param>
|
||||
/// <returns>The individual values found.</returns>
|
||||
private static List<string> SplitValues(IEnumerable<string> values)
|
||||
{
|
||||
return SplitValues(values, ['/', ';']);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits every provided value on semicolons only, for the tags whose own values may contain a slash.
|
||||
/// </summary>
|
||||
/// <param name="values">The values to split.</param>
|
||||
/// <returns>The individual values found.</returns>
|
||||
private static List<string> SplitValuesOnSemicolons(IEnumerable<string> values)
|
||||
{
|
||||
return SplitValues(values, [';']);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits every provided value on the provided separators, and keeps the non-empty results.
|
||||
/// </summary>
|
||||
/// <param name="values">The values to split.</param>
|
||||
/// <param name="separators">The separators to split the values on.</param>
|
||||
/// <returns>The individual values found.</returns>
|
||||
private static List<string> SplitValues(IEnumerable<string> values, char[] separators)
|
||||
{
|
||||
List<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a date string into a date and a year.
|
||||
/// </summary>
|
||||
/// <param name="value">The date string to parse.</param>
|
||||
/// <returns>The parsed date and year, or <see langword="null"/> values when the string could not be parsed.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to process.</param>
|
||||
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
|
||||
private static string? NullIfWhiteSpace(string? value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
|
||||
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TagLibSharp" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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")]
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="Id3TagDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
internal sealed class Id3TagDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Id3TagDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="title">Optional. The title of the track.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="album">Optional. The title of the album the track belongs to.</param>
|
||||
/// <param name="includeAlbum">Whether the album should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="trackArtists">Optional. The artists credited on the track.</param>
|
||||
/// <param name="albumArtists">Optional. The artists credited on the album.</param>
|
||||
/// <param name="albumArtistSortName">Optional. The sort name of the album artist.</param>
|
||||
/// <param name="includeAlbumArtistSortName">Whether the album artist sort name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="trackArtistSortName">Optional. The sort name of the track artist.</param>
|
||||
/// <param name="includeTrackArtistSortName">Whether the track artist sort name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="trackNumber">Optional. The number of the track on its disc, or a random one when not supplied.</param>
|
||||
/// <param name="trackCount">Optional. The number of tracks on the disc, or a random one when not supplied.</param>
|
||||
/// <param name="discNumber">Optional. The number of the disc the track belongs to, or a random one when not supplied.</param>
|
||||
/// <param name="discCount">Optional. The number of discs of the release, or a random one when not supplied.</param>
|
||||
/// <param name="year">Optional. The year the track was released.</param>
|
||||
/// <param name="includeYear">Whether the year should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="originalReleaseDate">Optional. The original release date of the track.</param>
|
||||
/// <param name="includeOriginalReleaseDate">Whether the original release date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="originalReleaseYear">Optional. The original release year of the track.</param>
|
||||
/// <param name="includeOriginalReleaseYear">Whether the original release year should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="genres">Optional. The genres the tags associate with the track.</param>
|
||||
/// <param name="composers">Optional. The composers credited on the track.</param>
|
||||
/// <param name="lyricists">Optional. The lyricists credited on the track.</param>
|
||||
/// <param name="conductors">Optional. The conductors credited on the track.</param>
|
||||
/// <param name="remixers">Optional. The remixers credited on the track.</param>
|
||||
/// <param name="involvedPeople">Optional. The people credited on the track, each with their role.</param>
|
||||
/// <param name="language">Optional. The language of the track.</param>
|
||||
/// <param name="includeLanguage">Whether the language should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="script">Optional. The script used by the language of the track.</param>
|
||||
/// <param name="includeScript">Whether the script should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="label">Optional. The label that issued the album.</param>
|
||||
/// <param name="includeLabel">Whether the label should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="catalogNumbers">Optional. The catalog numbers of the album.</param>
|
||||
/// <param name="barcode">Optional. The barcode of the album.</param>
|
||||
/// <param name="includeBarcode">Whether the barcode should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="releaseTypes">Optional. The types of the release.</param>
|
||||
/// <param name="releaseStatus">Optional. The status of the release.</param>
|
||||
/// <param name="includeReleaseStatus">Whether the release status should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="releaseCountry">Optional. The country the release was issued in.</param>
|
||||
/// <param name="includeReleaseCountry">Whether the release country should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="mediaFormat">Optional. The medium of the release.</param>
|
||||
/// <param name="includeMediaFormat">Whether the media format should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="packaging">Optional. The packaging of the release.</param>
|
||||
/// <param name="includePackaging">Whether the packaging should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="asin">Optional. The ASIN of the album.</param>
|
||||
/// <param name="includeAsin">Whether the ASIN should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="isrcs">Optional. The ISRCs of the track.</param>
|
||||
/// <param name="moods">Optional. The moods of the track.</param>
|
||||
/// <param name="workTitle">Optional. The title of the work the track is a recording of.</param>
|
||||
/// <param name="includeWorkTitle">Whether the work title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="musicKey">Optional. The musical key of the track.</param>
|
||||
/// <param name="includeMusicKey">Whether the musical key should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="bpm">Optional. The tempo of the track in beats per minute.</param>
|
||||
/// <param name="includeBpm">Whether the tempo should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="durationInSeconds">Optional. The duration of the audio of the track in seconds.</param>
|
||||
/// <param name="includeDurationInSeconds">Whether the duration should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="sampleRate">Optional. The sample rate of the audio of the track in Hz.</param>
|
||||
/// <param name="includeSampleRate">Whether the sample rate should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="channels">Optional. The number of audio channels of the track.</param>
|
||||
/// <param name="includeChannels">Whether the channel count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="bitDepth">Optional. The bit depth of the audio of the track.</param>
|
||||
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="bitrate">Optional. The bitrate of the audio of the track in kbps.</param>
|
||||
/// <param name="includeBitrate">Whether the bitrate should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="audioCodec">Optional. The description of the audio codec of the track.</param>
|
||||
/// <param name="includeAudioCodec">Whether the audio codec should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="website">Optional. The official website associated with the artist.</param>
|
||||
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
|
||||
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz artist identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="musicBrainzReleaseArtistId">Optional. The MusicBrainz identifier of the release artist.</param>
|
||||
/// <param name="includeMusicBrainzReleaseArtistId">Whether the MusicBrainz release artist identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="musicBrainzReleaseGroupId">Optional. The MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="includeMusicBrainzReleaseGroupId">Whether the MusicBrainz release group identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="musicBrainzReleaseId">Optional. The MusicBrainz identifier of the release.</param>
|
||||
/// <param name="includeMusicBrainzReleaseId">Whether the MusicBrainz release identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="musicBrainzRecordingId">Optional. The MusicBrainz identifier of the recording of the track.</param>
|
||||
/// <param name="includeMusicBrainzRecordingId">Whether the MusicBrainz recording identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="musicBrainzReleaseTrackId">Optional. The MusicBrainz identifier of the track on its release.</param>
|
||||
/// <param name="includeMusicBrainzReleaseTrackId">Whether the MusicBrainz release track identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="musicBrainzWorkId">Optional. The MusicBrainz identifier of the work the track is a recording of.</param>
|
||||
/// <param name="includeMusicBrainzWorkId">Whether the MusicBrainz work identifier should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="Id3TagDto"/> instance.</returns>
|
||||
public Id3TagDto Create(
|
||||
string? title = null,
|
||||
bool includeTitle = true,
|
||||
string? album = null,
|
||||
bool includeAlbum = true,
|
||||
List<string>? trackArtists = null,
|
||||
List<string>? 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<string>? genres = null,
|
||||
List<string>? composers = null,
|
||||
List<string>? lyricists = null,
|
||||
List<string>? conductors = null,
|
||||
List<string>? 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<string>? catalogNumbers = null,
|
||||
string? barcode = null,
|
||||
bool includeBarcode = true,
|
||||
List<string>? 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<string>? isrcs = null,
|
||||
List<string>? 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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="Id3TagDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="Id3TagDto"/> instances.</returns>
|
||||
public List<Id3TagDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class TestAudioFileFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a minimal, untagged PCM WAV file.
|
||||
/// </summary>
|
||||
/// <param name="path">The path where the WAV is written.</param>
|
||||
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
|
||||
public static void CreateWav(string path, int durationMs = 200)
|
||||
{
|
||||
File.WriteAllBytes(path, BuildWav(durationMs));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a PCM WAV file whose embedded tags are configured by the provided callback.
|
||||
/// </summary>
|
||||
/// <param name="path">The path where the WAV is written.</param>
|
||||
/// <param name="configureTags">The callback that configures the tags of the file.</param>
|
||||
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
|
||||
public static void CreateTaggedWav(string path, Action<TagLib.File> configureTags, int durationMs = 200)
|
||||
{
|
||||
File.WriteAllBytes(path, BuildWav(durationMs));
|
||||
using (TagLib.File tagFile = TagLib.File.Create(path))
|
||||
{
|
||||
configureTags(tagFile);
|
||||
tagFile.Save();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a user defined text information frame (TXXX) to the ID3v2 tag of the file.
|
||||
/// </summary>
|
||||
/// <param name="tagFile">The file whose ID3v2 tag is extended.</param>
|
||||
/// <param name="description">The description that identifies the frame.</param>
|
||||
/// <param name="values">The values of the frame.</param>
|
||||
public static void AddUserTextFrame(TagLib.File tagFile, string description, params string[] values)
|
||||
{
|
||||
GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.UserTextInformationFrame(description) { Text = values });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a text information frame to the ID3v2 tag of the file.
|
||||
/// </summary>
|
||||
/// <param name="tagFile">The file whose ID3v2 tag is extended.</param>
|
||||
/// <param name="frameId">The four character identifier of the frame.</param>
|
||||
/// <param name="values">The values of the frame.</param>
|
||||
public static void AddTextFrame(TagLib.File tagFile, string frameId, params string[] values)
|
||||
{
|
||||
GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.TextInformationFrame(frameId) { Text = values });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a URL link frame (WXXX/WOAR) to the ID3v2 tag of the file.
|
||||
/// </summary>
|
||||
/// <param name="tagFile">The file whose ID3v2 tag is extended.</param>
|
||||
/// <param name="frameId">The four character identifier of the frame.</param>
|
||||
/// <param name="values">The URL values of the frame.</param>
|
||||
public static void AddUrlFrame(TagLib.File tagFile, string frameId, params string[] values)
|
||||
{
|
||||
GetId3v2Tag(tagFile).AddFrame(new TagLib.Id3v2.UrlLinkFrame(frameId) { Text = values });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ID3v2 tag of the file, creating it when the file does not carry one yet.
|
||||
/// </summary>
|
||||
/// <param name="tagFile">The file whose ID3v2 tag is read.</param>
|
||||
/// <returns>The ID3v2 tag of the file.</returns>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the bytes of a minimal, valid PCM WAV file with a single silent audio channel.
|
||||
/// </summary>
|
||||
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
|
||||
/// <returns>The bytes of the WAV file.</returns>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture" />
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" />
|
||||
<PackageReference Include="Bogus" />
|
||||
<PackageReference Include="TagLibSharp" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.ID3\Lumina.Plugins.ID3.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -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")]
|
||||
+102
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="Id3AlbumMetadataProvider"/> class, reading real tagged audio containers.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Id3AlbumMetadataProviderTests : IDisposable
|
||||
{
|
||||
private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new();
|
||||
private readonly Id3AlbumMetadataProvider _sut = new(new Id3TagReader());
|
||||
private readonly string _temporaryDirectory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Id3AlbumMetadataProviderTests"/> class.
|
||||
/// </summary>
|
||||
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<AlbumMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
AlbumMetadataDto candidate = Assert.Single(result);
|
||||
Assert.Equal("The Album", candidate.Title);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the temporary directory created for the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_temporaryDirectory))
|
||||
Directory.Delete(_temporaryDirectory, recursive: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+100
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="Id3ArtistMetadataProvider"/> class, reading real tagged audio containers.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Id3ArtistMetadataProviderTests : IDisposable
|
||||
{
|
||||
private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new();
|
||||
private readonly Id3ArtistMetadataProvider _sut = new(new Id3TagReader());
|
||||
private readonly string _temporaryDirectory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Id3ArtistMetadataProviderTests"/> class.
|
||||
/// </summary>
|
||||
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<ArtistMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ArtistMetadataDto candidate = Assert.Single(result);
|
||||
Assert.Equal("The Artist", candidate.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the temporary directory created for the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_temporaryDirectory))
|
||||
Directory.Delete(_temporaryDirectory, recursive: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+103
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="Id3TrackMetadataProvider"/> class, reading real tagged audio containers.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Id3TrackMetadataProviderTests : IDisposable
|
||||
{
|
||||
private readonly TrackMetadataLookupDtoFixture _trackMetadataLookupDtoFixture = new();
|
||||
private readonly Id3TrackMetadataProvider _sut = new(new Id3TagReader());
|
||||
private readonly string _temporaryDirectory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Id3TrackMetadataProviderTests"/> class.
|
||||
/// </summary>
|
||||
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<AudioMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
AudioMetadataDto candidate = Assert.Single(result);
|
||||
Assert.Equal("The Track", candidate.Title);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the temporary directory created for the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_temporaryDirectory))
|
||||
Directory.Delete(_temporaryDirectory, recursive: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+480
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="Id3TagReader"/> class, reading real audio containers through the tagging library.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Id3TagReaderTests : IDisposable
|
||||
{
|
||||
private readonly Id3TagReader _sut = new();
|
||||
private readonly string _temporaryDirectory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Id3TagReaderTests"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the temporary directory created for the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_temporaryDirectory))
|
||||
Directory.Delete(_temporaryDirectory, recursive: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" />
|
||||
<PackageReference Include="Bogus" />
|
||||
<PackageReference Include="coverlet.collector">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="NSubstitute" />
|
||||
<PackageReference Include="TagLibSharp" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.ID3\Lumina.Plugins.ID3.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Plugins.ID3.Fixtures\Lumina.Plugins.ID3.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+74
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Id3Services"/> class.
|
||||
/// </summary>
|
||||
[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<ArgumentNullException>(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<IMetadataProvider>(pluginId).Count());
|
||||
Assert.Empty(serviceProvider.GetKeyedServices<IMetadataProvider>(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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Id3AlbumMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
[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<LibraryType> 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<AlbumMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Id3ArtistMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
[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<LibraryType> 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<ArtistMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Id3Plugin"/> class.
|
||||
/// </summary>
|
||||
[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<PluginSettingDescriptorDto> 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<IMetadataProvider>(Id3Plugin.s_pluginId).Count());
|
||||
Assert.Empty(serviceProvider.GetKeyedServices<IMetadataProvider>(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<Id3TagReader>());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Id3TrackMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
[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<LibraryType> 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<AudioMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Id3TagReader"/> class, covering the guard branches that do not reach the tagging library.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Id3TagReaderTests : IDisposable
|
||||
{
|
||||
private readonly Id3TagReader _sut = new();
|
||||
private readonly string _temporaryDirectory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Id3TagReaderTests"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the temporary directory created for the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_temporaryDirectory))
|
||||
Directory.Delete(_temporaryDirectory, recursive: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" />
|
||||
<PackageReference Include="Bogus" />
|
||||
<PackageReference Include="coverlet.collector">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="NSubstitute" />
|
||||
<PackageReference Include="TagLibSharp" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.ID3\Lumina.Plugins.ID3.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Plugins.ID3.Fixtures\Lumina.Plugins.ID3.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in new issue
Block a user