diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Common/DependencyInjection/LocalMusicArtworkServices.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Common/DependencyInjection/LocalMusicArtworkServices.cs new file mode 100644 index 00000000..8c2b7582 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Common/DependencyInjection/LocalMusicArtworkServices.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the local music artwork providers into the Dependency Injection container. +/// +internal static class LocalMusicArtworkServices +{ + /// + /// Registers the services of the local music artwork providers into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the artwork. + /// The updated . + internal static IServiceCollection AddLocalMusicArtworkProviders(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults. + services.TryAddScoped(serviceProvider => + { + LocalMusicArtworkSettingsDto defaults = new(); + IPluginSettingsStore? settingsStore = serviceProvider.GetService(); + return new LocalMusicArtworkSettingsProvider(settingsStore, pluginId, defaults); + }); + + // Register the artwork providers as keyed by pluginId transient services, so they can be resolved specifically among other IArtworkProvider implementations. + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDto.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDto.cs new file mode 100644 index 00000000..2a9ef3f5 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDto.cs @@ -0,0 +1,13 @@ +namespace Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; + +/// +/// Data transfer object for the settings that configure the local music artwork plugin. +/// +internal sealed class LocalMusicArtworkSettingsDto +{ + /// + /// Gets or sets a value indicating whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// Defaults to , so that a cover is found even when the library stores none on disk. + /// + public bool ShouldExtractEmbeddedCover { get; set; } = true; +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicAlbumArtworkProvider.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicAlbumArtworkProvider.cs new file mode 100644 index 00000000..ef2d8c37 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicAlbumArtworkProvider.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Provides the artwork of an album from the images stored in the folders of the local music library of the user. +/// When the album has no cover image on disk and the settings allow it, the cover embedded in the audio files is extracted as a fallback. +/// +internal sealed class LocalMusicAlbumArtworkProvider : IArtworkProvider +{ + private readonly LocalMusicArtworkSettingsProvider _settingsProvider; + + /// + /// Gets the display name of the artwork provider. + /// + public string Name => "Local Music Artwork"; + + /// + /// Gets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess => false; + + /// + /// Initializes a new instance of the class. + /// + /// The provider of the runtime settings of the plugin. + public LocalMusicAlbumArtworkProvider(LocalMusicArtworkSettingsProvider settingsProvider) + { + _settingsProvider = settingsProvider; + } + + /// + /// Gets the artworks of the album described by . + /// + /// The lookup describing the album to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artworks of the album, or an empty collection when no artwork was found. + public async Task> GetArtworkAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + IReadOnlyList artworks = LocalMusicArtworkScanner.ScanAlbumArtwork(lookup.Path); + + // The cover stored on disk always wins; the embedded one only fills the gap when the album carries no cover on disk at all. + if (artworks.Any(artwork => artwork.Type == ArtworkType.Cover)) + return artworks; + + LocalMusicArtworkSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + if (!settings.ShouldExtractEmbeddedCover) + return artworks; + + ArtworkDto? embeddedCover = LocalMusicArtworkEmbeddedCoverExtractor.Extract(lookup.Path); + if (embeddedCover is null) + return artworks; + return [.. artworks, embeddedCover]; + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtistArtworkProvider.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtistArtworkProvider.cs new file mode 100644 index 00000000..8c6aab35 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtistArtworkProvider.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Provides the artwork of an artist from the images stored in the folders of the local music library of the user. +/// +internal sealed class LocalMusicArtistArtworkProvider : IArtworkProvider +{ + /// + /// Gets the display name of the artwork provider. + /// + public string Name => "Local Music Artwork"; + + /// + /// Gets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess => false; + + /// + /// Gets the artworks of the artist described by . + /// + /// The lookup describing the artist to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artworks of the artist, or an empty collection when no artwork was found. + public Task> GetArtworkAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + return Task.FromResult(LocalMusicArtworkScanner.ScanArtistArtwork(lookup.Path)); + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkEmbeddedCoverExtractor.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkEmbeddedCoverExtractor.cs new file mode 100644 index 00000000..4613a332 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkEmbeddedCoverExtractor.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Extracts the cover image embedded in the metadata of an audio file into a temporary file, so that it can be stored as the artwork of an album. +/// +internal static class LocalMusicArtworkEmbeddedCoverExtractor +{ + private const int MAX_EMBEDDED_COVER_SIZE_BYTES = 10 * 1024 * 1024; // The maximum size of an embedded cover, matching the size limit the artwork storage enforces. + + /// + /// Extracts the first embedded cover image of the audio file stored at into a temporary file. + /// + /// The file system path of the audio file whose embedded cover is extracted. + /// The extracted cover artwork, which points to a temporary file, or when the file carries no usable embedded cover. + public static ArtworkDto? Extract(string? trackPath) + { + if (string.IsNullOrWhiteSpace(trackPath) || !File.Exists(trackPath)) + return null; + + try + { + // A link must not cause the metadata of a file outside the library to be read. + if (File.GetAttributes(trackPath).HasFlag(FileAttributes.ReparsePoint)) + return null; + + using (TagLib.File tagFile = TagLib.File.Create(trackPath)) + { + TagLib.IPicture? cover = tagFile.Tag.Pictures?.FirstOrDefault(picture => picture is not null && picture.Data is not null); + if (cover?.Data is null) + return null; + + byte[] imageBytes = cover.Data.Data; + if (imageBytes is null || imageBytes.Length == 0 || imageBytes.Length > MAX_EMBEDDED_COVER_SIZE_BYTES) + return null; + + string temporaryPath = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artwork-{Guid.NewGuid():N}{ResolveImageExtension(cover.MimeType)}"); + File.WriteAllBytes(temporaryPath, imageBytes); + return new ArtworkDto(ArtworkType.Cover, 0, LocalPath: temporaryPath, RemoteUrl: null, IsTemporary: true); + } + } + catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException) + { + // A file whose embedded cover cannot be read contributes no cover, rather than failing the artwork resolution of the whole album. + return null; + } + } + + /// + /// Resolves the file extension of an embedded cover image from its MIME type. + /// + /// The MIME type of the embedded cover image. + /// The file extension matching the MIME type, falling back to the JPEG extension. + private static string ResolveImageExtension(string? mimeType) + { + return mimeType?.Trim().ToLowerInvariant() switch + { + "image/png" => ".png", + "image/webp" => ".webp", + "image/bmp" or "image/x-ms-bmp" => ".bmp", + "image/gif" => ".gif", + "image/tiff" => ".tiff", + _ => ".jpg" + }; + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkPlugin.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkPlugin.cs new file mode 100644 index 00000000..766d9672 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkPlugin.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Plugin that provides the artwork of music artists and albums from the images stored in the folders of a local music library. +/// +public sealed class LocalMusicArtworkPlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "Local Music Artwork"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Reads the artwork of the artists and the albums from the images stored in the folders of a local music library."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return + [ + new PluginSettingDescriptorDto( + Key: LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER, + Label: "Extract embedded album cover image from audio files when it is not already present on disk", + Type: PluginSettingType.Boolean, + DefaultValue: "true") + ]; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddLocalMusicArtworkProviders(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkScanner.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkScanner.cs new file mode 100644 index 00000000..b7eb16ce --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/LocalMusicArtworkScanner.cs @@ -0,0 +1,270 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core; + +/// +/// Scans the folders of a local music library and classifies the images they contain into artwork DTOs, following the naming +/// conventions that music media servers use for the images of an artist and of an album. +/// The file names are matched case sensitively, so that a library that stores them with a different casing is left alone. +/// +internal static class LocalMusicArtworkScanner +{ + private const int MAX_ALBUM_ANCESTOR_LEVELS = 2; // The number of directories, the one of a track and its parent, that are inspected when locating the folder of an album. + private const int MAX_ARTIST_ANCESTOR_LEVELS = 5; // The number of parent directories that are inspected when locating the folder of an artist. + + private static readonly HashSet s_imageExtensions = new([".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif", ".tif", ".tiff"], StringComparer.Ordinal); + + /// + /// Scans the directory of the provided track, and its parent directory, for the artwork of an album. + /// + /// The file system path of a track of the album. + /// The artwork of the album, or an empty collection when no artwork was found. + public static IReadOnlyList ScanAlbumArtwork(string? trackPath) + { + string? trackDirectory = GetDirectoryOrNull(trackPath); + if (trackDirectory is null) + return []; + + // A multi disc album nests its tracks in disc subdirectories, so both the track directory and its parent are inspected, the nearest one taking precedence. + List artworks = []; + HashSet<(ArtworkType Type, int Ordinal)> seenArtworks = []; + DirectoryInfo? currentDirectory = new(trackDirectory); + int level = 0; + while (currentDirectory is not null && level < MAX_ALBUM_ANCESTOR_LEVELS) + { + foreach (ArtworkDto artwork in ClassifyImages(currentDirectory, isArtist: false)) + if (seenArtworks.Add((artwork.Type, artwork.Ordinal))) + artworks.Add(artwork); + currentDirectory = currentDirectory.Parent; + level++; + } + return artworks; + } + + /// + /// Scans the ancestor directories of the provided track for the artwork of an artist. + /// + /// The file system path of a track of the artist. + /// The artwork of the artist, or an empty collection when no artwork was found. + public static IReadOnlyList ScanArtistArtwork(string? trackPath) + { + string? trackDirectory = GetDirectoryOrNull(trackPath); + if (trackDirectory is null) + return []; + + // The artist directory is the nearest ancestor that carries an artist level image, like a folder, a backdrop or a logo. + DirectoryInfo? currentDirectory = new(trackDirectory); + int level = 0; + while (currentDirectory is not null && level < MAX_ARTIST_ANCESTOR_LEVELS) + { + IReadOnlyList artworks = ClassifyImages(currentDirectory, isArtist: true); + if (artworks.Count > 0) + return artworks; + currentDirectory = currentDirectory.Parent; + level++; + } + return []; + } + + /// + /// Classifies the images directly contained in . + /// + /// The directory whose images are classified. + /// Whether the images belong to an artist, as opposed to an album. + /// The classified artwork, one for every recognized file, ordered by type and ordinal. + private static IReadOnlyList ClassifyImages(DirectoryInfo directory, bool isArtist) + { + FileInfo[] files; + try + { + files = [.. directory.EnumerateFiles()]; + } + catch (IOException) + { + return []; + } + catch (UnauthorizedAccessException) + { + return []; + } + + List candidates = []; + foreach (FileInfo file in files) + { + if (!s_imageExtensions.Contains(file.Extension)) + continue; + + (string baseName, int ordinal) = SplitStem(Path.GetFileNameWithoutExtension(file.Name)); + bool isRecognized = isArtist + ? TryMapArtistName(baseName, out ArtworkType artworkType, out int priority) + : TryMapAlbumName(baseName, out artworkType, out priority); + if (!isRecognized) + continue; + candidates.Add(new ClassifiedArtwork(artworkType, ordinal, priority, file.Name, file.FullName)); + } + + // Multiple file names can describe the same piece of artwork, like a cover and a front image, so only the preferred one is kept per type and ordinal. + List artworks = []; + HashSet<(ArtworkType Type, int Ordinal)> seenArtworks = []; + foreach (ClassifiedArtwork candidate in candidates + .OrderBy(candidate => candidate.Type) + .ThenBy(candidate => candidate.Ordinal) + .ThenBy(candidate => candidate.Priority) + .ThenBy(candidate => candidate.FileName, StringComparer.Ordinal)) + { + if (!seenArtworks.Add((candidate.Type, candidate.Ordinal))) + continue; + artworks.Add(new ArtworkDto(candidate.Type, candidate.Ordinal, LocalPath: candidate.FilePath, RemoteUrl: null)); + } + return artworks; + } + + /// + /// Splits the stem of an image file into the base name that identifies the artwork and the ordinal that orders it within its type. + /// + /// The stem of the image file, without its extension. + /// The base name of the artwork and the ordinal it carries, which is zero when the stem carries no number. + private static (string BaseName, int Ordinal) SplitStem(string stem) + { + int index = stem.Length; + while (index > 0 && char.IsAsciiDigit(stem[index - 1])) + index--; + string ordinalPart = stem[index..]; + string baseName = stem[..index].TrimEnd(' ', '-', '_'); + int ordinal = ordinalPart.Length > 0 && int.TryParse(ordinalPart, out int parsedOrdinal) ? parsedOrdinal : 0; + return (baseName, ordinal); + } + + /// + /// Maps the base name of an artist image onto an artwork type. + /// + /// The base name of the image file. + /// The mapped artwork type, when the base name is recognized. + /// The priority of the base name among the file names of the same artwork type and ordinal, lower being preferred. + /// when the base name was recognized, otherwise . + private static bool TryMapArtistName(string baseName, out ArtworkType artworkType, out int priority) + { + priority = 0; + switch (baseName) + { + case "folder": + artworkType = ArtworkType.Cover; + return true; + case "backdrop": + artworkType = ArtworkType.Backdrop; + return true; + case "banner": + artworkType = ArtworkType.Banner; + return true; + case "logo": + artworkType = ArtworkType.Logo; + return true; + case "thumb": + artworkType = ArtworkType.Thumb; + return true; + default: + artworkType = ArtworkType.Other; + priority = int.MaxValue; + return false; + } + } + + /// + /// Maps the base name of an album image onto an artwork type. + /// + /// The base name of the image file. + /// The mapped artwork type, when the base name is recognized. + /// The priority of the base name among the file names of the same artwork type and ordinal, lower being preferred. + /// when the base name was recognized, otherwise . + private static bool TryMapAlbumName(string baseName, out ArtworkType artworkType, out int priority) + { + switch (baseName) + { + case "cover": + artworkType = ArtworkType.Cover; + priority = 0; + return true; + case "front": + artworkType = ArtworkType.Front; + priority = 0; + return true; + case "back": + artworkType = ArtworkType.Back; + priority = 0; + return true; + case "booklet": + artworkType = ArtworkType.Booklet; + priority = 0; + return true; + case "disk": + case "disc": + artworkType = ArtworkType.Medium; + priority = 0; + return true; + case "liner": + artworkType = ArtworkType.Liner; + priority = 0; + return true; + case "tray": + artworkType = ArtworkType.Tray; + priority = 0; + return true; + case "spine": + artworkType = ArtworkType.Spine; + priority = 0; + return true; + case "obi": + artworkType = ArtworkType.Obi; + priority = 0; + return true; + case "sticker": + artworkType = ArtworkType.Sticker; + priority = 0; + return true; + case "poster": + artworkType = ArtworkType.Poster; + priority = 0; + return true; + default: + artworkType = ArtworkType.Other; + priority = int.MaxValue; + return false; + } + } + + /// + /// Gets the directory of the provided . + /// + /// The file system path whose directory is retrieved. + /// The directory of the path, or when the path is empty or has no directory part. + private static string? GetDirectoryOrNull(string? path) + { + if (string.IsNullOrWhiteSpace(path)) + return null; + string? directory = Path.GetDirectoryName(path); + return string.IsNullOrWhiteSpace(directory) ? null : directory; + } + + /// + /// A recognized image of an artist or an album, before it is ordered and de-duplicated. + /// + /// The type of the artwork. + /// The ordinal of the artwork within its type. + /// The priority of the file name among the files of the same artwork type and ordinal, lower being preferred. + /// The name of the image file. + /// The file system path of the image file. + private sealed record ClassifiedArtwork( + ArtworkType Type, + int Ordinal, + int Priority, + string FileName, + string FilePath + ); +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsKeys.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsKeys.cs new file mode 100644 index 00000000..7773c721 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsKeys.cs @@ -0,0 +1,12 @@ +namespace Lumina.Plugins.LocalMusicArtwork.Core.Settings; + +/// +/// Keys of the settings of the local music artwork plugin, shared by the settings schema and the settings provider. +/// +internal static class LocalMusicArtworkSettingsKeys +{ + /// + /// The key of the setting that controls whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// + internal const string SHOULD_EXTRACT_EMBEDDED_COVER = "ShouldExtractEmbeddedCover"; +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsProvider.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsProvider.cs new file mode 100644 index 00000000..c2a5462f --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Core/Settings/LocalMusicArtworkSettingsProvider.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Core.Settings; + +/// +/// Provides the runtime settings of the local music artwork plugin, overlaying the settings persisted by the host over the configured defaults. +/// +internal sealed class LocalMusicArtworkSettingsProvider +{ + private readonly IPluginSettingsStore? _settingsStore; + private readonly Guid _pluginId; + private readonly LocalMusicArtworkSettingsDto _defaults; + + // The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already + // resolved path lock free; the gate is only needed by the first callers that race to resolve it. + private readonly SemaphoreSlim _gate = new(1, 1); + private LocalMusicArtworkSettingsDto? _runtimeSettings; + + /// + /// Initializes a new instance of the class. + /// + /// The store of the settings persisted by the host, or when no store is available. + /// The unique identifier of the plugin whose settings are read. + /// The runtime settings with the default values and the optional configuration callback already applied. + public LocalMusicArtworkSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, LocalMusicArtworkSettingsDto defaults) + { + _settingsStore = settingsStore; + _pluginId = pluginId; + _defaults = defaults; + } + + /// + /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call. + /// + /// Cancellation token that can be used to stop the execution. + /// The runtime settings of the plugin. + public async Task GetAsync(CancellationToken cancellationToken) + { + // Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact. + LocalMusicArtworkSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is not null) + return runtimeSettings; + + // Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once. + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // Second check inside the gate: another caller may have resolved the settings while this one was waiting for it. + runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is null) + { + // The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes. + runtimeSettings = new LocalMusicArtworkSettingsDto + { + ShouldExtractEmbeddedCover = _defaults.ShouldExtractEmbeddedCover + }; + + if (_settingsStore is not null) + { + IReadOnlyDictionary? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false); + if (storedSettings is not null && + storedSettings.TryGetValue(LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER, out string? shouldExtractEmbeddedCover) && + bool.TryParse(shouldExtractEmbeddedCover, out bool shouldExtractEmbeddedCoverValue)) + runtimeSettings.ShouldExtractEmbeddedCover = shouldExtractEmbeddedCoverValue; + } + + // Publishing through Volatile makes the fully built instance visible to the lock free readers above. + Volatile.Write(ref _runtimeSettings, runtimeSettings); + } + + return runtimeSettings; + } + finally + { + _gate.Release(); + } + } +} diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Lumina.Plugins.LocalMusicArtwork.csproj b/plugins/Lumina.Plugins.LocalMusicArtwork/Lumina.Plugins.LocalMusicArtwork.csproj new file mode 100644 index 00000000..406f5b96 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Lumina.Plugins.LocalMusicArtwork.csproj @@ -0,0 +1,38 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + + + + + + + + + + + + + + false + runtime + + + + + + + + + + + diff --git a/plugins/Lumina.Plugins.LocalMusicArtwork/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.LocalMusicArtwork/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..f0b1cda2 --- /dev/null +++ b/plugins/Lumina.Plugins.LocalMusicArtwork/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.SecurityTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.IntegrationTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.Fixtures")] diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDtoFixture.cs new file mode 100644 index 00000000..0ad5598d --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Common/Models/DTO/Settings/LocalMusicArtworkSettingsDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class LocalMusicArtworkSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. Whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// A configured instance. + public LocalMusicArtworkSettingsDto Create( + bool? shouldExtractEmbeddedCover = null) + { + return new LocalMusicArtworkSettingsDto + { + ShouldExtractEmbeddedCover = shouldExtractEmbeddedCover ?? _faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestAudioFileFactory.cs b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestAudioFileFactory.cs new file mode 100644 index 00000000..a48164ed --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestAudioFileFactory.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; + +/// +/// Builds minimal, structurally valid WAV files used as test input for the artwork scanning and embedded cover extraction tests. +/// The files are produced into a temporary directory at test runtime, because a WAV is a binary container whose embedded pictures can only be written by the tagging library itself. +/// +[ExcludeFromCodeCoverage] +public static class TestAudioFileFactory +{ + /// + /// Creates a minimal, untagged PCM WAV file. + /// + /// The path where the WAV is written. + /// The duration of the audio of the file, in milliseconds. + public static void CreateWav(string path, int durationMs = 200) + { + WriteFile(path, BuildWav(durationMs)); + } + + /// + /// Creates a PCM WAV file that carries the provided image as its embedded front cover. + /// + /// The path where the WAV is written. + /// The bytes of the embedded cover image. + /// The MIME type of the embedded cover image, defaulting to JPEG. + /// The duration of the audio of the file, in milliseconds. + public static void CreateWavWithEmbeddedCover(string path, byte[] imageBytes, string? mimeType = "image/jpeg", int durationMs = 200) + { + CreateTaggedWav(path, tagFile => + { + tagFile.Tag.Pictures = + [ + new TagLib.Picture + { + MimeType = mimeType!, + Type = TagLib.PictureType.FrontCover, + Data = [.. imageBytes] + } + ]; + }, durationMs); + } + + /// + /// Creates a PCM WAV file whose embedded tags are configured by the provided callback. + /// + /// The path where the WAV is written. + /// The callback that configures the tags of the file. + /// The duration of the audio of the file, in milliseconds. + public static void CreateTaggedWav(string path, Action configureTags, int durationMs = 200) + { + WriteFile(path, BuildWav(durationMs)); + using (TagLib.File tagFile = TagLib.File.Create(path)) + { + configureTags(tagFile); + tagFile.Save(); + } + } + + /// + /// Creates a file whose content is not a recognizable audio container, so that the resilience of the embedded cover extraction can be exercised. + /// + /// The path where the file is written. + public static void CreateUnsupportedFile(string path) + { + WriteFile(path, Encoding.UTF8.GetBytes("This is not an audio file.")); + } + + /// + /// Writes the provided bytes at , creating the containing directory when it does not exist yet. + /// + /// The path where the bytes are written. + /// The bytes of the file. + private static void WriteFile(string path, byte[] contents) + { + string? directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + File.WriteAllBytes(path, contents); + } + + /// + /// Builds the bytes of a minimal, valid PCM WAV file with a single silent audio channel. + /// + /// The duration of the audio of the file, in milliseconds. + /// The bytes of the WAV file. + private static byte[] BuildWav(int durationMs) + { + const int SAMPLE_RATE = 44100; + const short CHANNELS = 1; + const short BITS_PER_SAMPLE = 16; + + int bytesPerSample = BITS_PER_SAMPLE / 8; + int dataSize = SAMPLE_RATE * CHANNELS * bytesPerSample * durationMs / 1000; + + using (MemoryStream memoryStream = new()) + { + using (BinaryWriter writer = new(memoryStream)) + { + writer.Write(Encoding.ASCII.GetBytes("RIFF")); + writer.Write(36 + dataSize); + writer.Write(Encoding.ASCII.GetBytes("WAVE")); + writer.Write(Encoding.ASCII.GetBytes("fmt ")); + writer.Write(16); + writer.Write((short)1); + writer.Write(CHANNELS); + writer.Write(SAMPLE_RATE); + writer.Write(SAMPLE_RATE * CHANNELS * bytesPerSample); + writer.Write((short)(CHANNELS * bytesPerSample)); + writer.Write(BITS_PER_SAMPLE); + writer.Write(Encoding.ASCII.GetBytes("data")); + writer.Write(dataSize); + writer.Write(new byte[dataSize]); + } + return memoryStream.ToArray(); + } + } +} diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestImageFileFactory.cs b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestImageFileFactory.cs new file mode 100644 index 00000000..4076b5b3 --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Core/TestImageFileFactory.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; + +/// +/// Creates image files of the formats a local music library stores next to its tracks, so that artwork scanning can be exercised against real files. +/// Each file carries the magic bytes of its format, mirroring the images a music library keeps in the folders of its artists and albums. +/// +[ExcludeFromCodeCoverage] +public static class TestImageFileFactory +{ + /// + /// Creates a JPEG image file at the provided path. + /// + /// The path where the image is written. + public static void CreateJpeg(string path) + { + WriteFile(path, [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xFF, 0xD9]); + } + + /// + /// Creates a PNG image file at the provided path. + /// + /// The path where the image is written. + public static void CreatePng(string path) + { + WriteFile(path, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52]); + } + + /// + /// Creates a WebP image file at the provided path. + /// + /// The path where the image is written. + public static void CreateWebp(string path) + { + WriteFile(path, [.. Encoding.ASCII.GetBytes("RIFF"), 0x00, 0x00, 0x00, 0x00, .. Encoding.ASCII.GetBytes("WEBP")]); + } + + /// + /// Creates a BMP image file at the provided path. + /// + /// The path where the image is written. + public static void CreateBmp(string path) + { + WriteFile(path, [0x42, 0x4D, 0x00, 0x00, 0x00, 0x00]); + } + + /// + /// Creates a GIF image file at the provided path. + /// + /// The path where the image is written. + public static void CreateGif(string path) + { + WriteFile(path, [.. Encoding.ASCII.GetBytes("GIF89a")]); + } + + /// + /// Creates a TIFF image file at the provided path. + /// + /// The path where the image is written. + public static void CreateTiff(string path) + { + WriteFile(path, [0x49, 0x49, 0x2A, 0x00]); + } + + /// + /// Creates a file whose content is not an image, so that the exclusion of non image files can be exercised. + /// + /// The path where the file is written. + public static void CreateTextFile(string path) + { + WriteFile(path, Encoding.UTF8.GetBytes("This is not an image.")); + } + + /// + /// Writes the provided bytes at , creating the containing directory when it does not exist yet. + /// + /// The path where the bytes are written. + /// The bytes of the file. + private static void WriteFile(string path, byte[] contents) + { + string? directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + File.WriteAllBytes(path, contents); + } +} diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj new file mode 100644 index 00000000..38d05ad9 --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..7301273e --- /dev/null +++ b/tests/Common/Lumina.Plugins.LocalMusicArtwork.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.LocalMusicArtwork.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.LocalMusicArtwork.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("3401EC09-8D4F-4E45-9F40-62FEA3C81373")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.LocalMusicArtwork.IntegrationTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicAlbumArtworkProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicAlbumArtworkProviderTests.cs new file mode 100644 index 00000000..b30fbf7d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicAlbumArtworkProviderTests.cs @@ -0,0 +1,300 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +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.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real image and audio files from the file system. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicAlbumArtworkProviderTests : IDisposable +{ + private static readonly byte[] s_embeddedCoverBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0x01, 0x02, 0x03, 0xFF, 0xD9]; + + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly LocalMusicArtworkSettingsDtoFixture _localMusicArtworkSettingsDtoFixture = new(); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public LocalMusicAlbumArtworkProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-album-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("Local Music Artwork", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Arrange + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasDiskImages_ShouldReturnTheDiskArtwork() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav")); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null), + new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.png"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasACoverOnDisk_ShouldNotExtractTheEmbeddedCover() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "cover.jpg"), artwork.LocalPath); + Assert.Null(artwork.RemoteUrl); + Assert.False(artwork.IsTemporary); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndExtractionIsEnabled_ShouldReturnTheEmbeddedCover() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(ArtworkType.Back, result[0].Type); + Assert.Equal(0, result[0].Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "back.png"), result[0].LocalPath); + Assert.Null(result[0].RemoteUrl); + Assert.False(result[0].IsTemporary); + Assert.Equal(ArtworkType.Cover, result[1].Type); + Assert.Equal(0, result[1].Ordinal); + Assert.NotNull(result[1].LocalPath); + Assert.EndsWith(".jpg", result[1].LocalPath); + Assert.True(File.Exists(result[1].LocalPath)); + Assert.Equal(s_embeddedCoverBytes, File.ReadAllBytes(result[1].LocalPath!)); + Assert.Null(result[1].RemoteUrl); + Assert.True(result[1].IsTemporary); + File.Delete(result[1].LocalPath!); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndExtractionIsDisabled_ShouldReturnOnlyTheDiskArtwork() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWavWithEmbeddedCover(Path.Combine(albumDirectory, "track.wav"), s_embeddedCoverBytes); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: false); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Back, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "back.png"), artwork.LocalPath); + Assert.Null(artwork.RemoteUrl); + Assert.False(artwork.IsTemporary); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndTheTrackHasNoEmbeddedCover_ShouldReturnOnlyTheDiskArtwork() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav")); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Back, artwork.Type); + Assert.Equal(Path.Combine(albumDirectory, "back.png"), artwork.LocalPath); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheTrackHasNoImagesAtAll_ShouldReturnEmpty() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav")); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no artwork + [InlineData("")] // an empty path contributes no artwork + [InlineData(" ")] // a white space path contributes no artwork + [InlineData("track.flac")] // a path without a directory part contributes no artwork + public async Task GetArtworkAsync_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath) + { + // Arrange + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheTrackDirectoryDoesNotExist_ShouldReturnEmpty() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Album", "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheAlbumHasNoCoverOnDiskAndTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestAudioFileFactory.CreateWav(Path.Combine(albumDirectory, "track.wav")); + string trackPath = Path.Combine(albumDirectory, "track.wav"); + LocalMusicAlbumArtworkProvider sut = CreateProvider(shouldExtractEmbeddedCover: true); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + Task Act() + { + return sut.GetArtworkAsync(lookup, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + /// + /// Creates a whose settings provider carries the provided embedded cover extraction setting. + /// + /// Whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// The created provider. + private LocalMusicAlbumArtworkProvider CreateProvider(bool shouldExtractEmbeddedCover) + { + LocalMusicArtworkSettingsProvider settingsProvider = new( + null, + Guid.NewGuid(), + _localMusicArtworkSettingsDtoFixture.Create(shouldExtractEmbeddedCover: shouldExtractEmbeddedCover)); + return new LocalMusicAlbumArtworkProvider(settingsProvider); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtistArtworkProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtistArtworkProviderTests.cs new file mode 100644 index 00000000..a612ec61 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtistArtworkProviderTests.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +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.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real image files from the file system. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtistArtworkProviderTests : IDisposable +{ + private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new(); + private readonly LocalMusicArtistArtworkProvider _sut = new(); + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public LocalMusicArtistArtworkProviderTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artist-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Local Music Artwork", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheArtistDirectoryCarriesImages_ShouldReturnTheArtistArtwork() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(artistDirectory, "banner.png")); + TestImageFileFactory.CreateWebp(Path.Combine(artistDirectory, "logo.webp")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(artistDirectory, "folder.jpg"), null), + new(ArtworkType.Banner, 0, Path.Combine(artistDirectory, "banner.png"), null), + new(ArtworkType.Logo, 0, Path.Combine(artistDirectory, "logo.webp"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public async Task GetArtworkAsync_WhenNoArtistImagesExist_ShouldReturnEmpty() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "back.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no artwork + [InlineData("")] // an empty path contributes no artwork + [InlineData(" ")] // a white space path contributes no artwork + [InlineData("track.flac")] // a path without a directory part contributes no artwork + public async Task GetArtworkAsync_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath) + { + // Arrange + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheTrackDirectoryDoesNotExist_ShouldReturnEmpty() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Artist", "track.flac"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldStillReturnTheDiskArtwork() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: trackPath); + + // Act + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, cancellationTokenSource.Token); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(Path.Combine(artistDirectory, "folder.jpg"), artwork.LocalPath); + } + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkEmbeddedCoverExtractorTests.cs b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkEmbeddedCoverExtractorTests.cs new file mode 100644 index 00000000..8ce06ac6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkEmbeddedCoverExtractorTests.cs @@ -0,0 +1,198 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, reading real audio containers that carry embedded pictures. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkEmbeddedCoverExtractorTests : IDisposable +{ + private static readonly byte[] s_coverBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0x11, 0x22, 0x33, 0xFF, 0xD9]; + + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public LocalMusicArtworkEmbeddedCoverExtractorTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-embedded-cover-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void Extract_WhenTheTrackCarriesAnEmbeddedCover_ShouldReturnATemporaryCoverArtwork() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, s_coverBytes, "image/jpeg"); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.NotNull(result); + Assert.Equal(ArtworkType.Cover, result.Type); + Assert.Equal(0, result.Ordinal); + Assert.NotNull(result.LocalPath); + Assert.StartsWith(Path.GetTempPath(), result.LocalPath); + Assert.EndsWith(".jpg", result.LocalPath); + Assert.True(File.Exists(result.LocalPath)); + Assert.Equal(s_coverBytes, File.ReadAllBytes(result.LocalPath!)); + Assert.Null(result.RemoteUrl); + Assert.True(result.IsTemporary); + File.Delete(result.LocalPath!); + } + + [Fact] + public void Extract_WhenTheTrackHasNoEmbeddedCover_ShouldReturnNull() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWav(trackPath); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no cover + [InlineData("")] // an empty path contributes no cover + [InlineData(" ")] // a white space path contributes no cover + public void Extract_WhenTheTrackPathIsNullOrEmpty_ShouldReturnNull(string? trackPath) + { + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Extract_WhenTheTrackFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "missing.wav"); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Theory] + [InlineData("image/jpeg", ".jpg")] + [InlineData("image/png", ".png")] + [InlineData("image/webp", ".webp")] + [InlineData("image/bmp", ".bmp")] + [InlineData("image/x-ms-bmp", ".bmp")] + [InlineData("image/gif", ".gif")] + [InlineData("image/tiff", ".tiff")] + [InlineData("IMAGE/PNG", ".png")] // the MIME type is matched without regard to casing + [InlineData(" image/png ", ".png")] // the MIME type is trimmed before it is matched + [InlineData("application/octet-stream", ".jpg")] // an unknown MIME type falls back to the JPEG extension + [InlineData("", ".jpg")] // an empty MIME type falls back to the JPEG extension + [InlineData(null, ".jpg")] // a missing MIME type falls back to the JPEG extension + public void Extract_WhenTheMimeTypeIsProvided_ShouldUseTheMatchingFileExtension(string? mimeType, string expectedExtension) + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, s_coverBytes, mimeType); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.LocalPath); + Assert.EndsWith(expectedExtension, result.LocalPath); + Assert.Equal(s_coverBytes, File.ReadAllBytes(result.LocalPath!)); + Assert.True(result.IsTemporary); + File.Delete(result.LocalPath!); + } + + [Fact] + public void Extract_WhenTheEmbeddedCoverIsExactlyTheMaximumSize_ShouldReturnTheCover() + { + // Arrange + byte[] maximumCover = new byte[10 * 1024 * 1024]; + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, maximumCover, "image/jpeg"); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.LocalPath); + Assert.Equal(maximumCover, File.ReadAllBytes(result.LocalPath!)); + Assert.True(result.IsTemporary); + File.Delete(result.LocalPath!); + } + + [Fact] + public void Extract_WhenTheEmbeddedCoverIsLargerThanTheMaximumSize_ShouldReturnNull() + { + // Arrange + byte[] oversizedCover = new byte[10 * 1024 * 1024 + 1]; + string trackPath = Path.Combine(_temporaryDirectory, "track.wav"); + TestAudioFileFactory.CreateWavWithEmbeddedCover(trackPath, oversizedCover, "image/jpeg"); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Extract_WhenTheTrackIsNotAnAudioFile_ShouldReturnNull() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.txt"); + TestAudioFileFactory.CreateUnsupportedFile(trackPath); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + [Fact] + public void Extract_WhenTheAudioFileIsCorrupt_ShouldReturnNull() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "track.mp3"); + TestAudioFileFactory.CreateUnsupportedFile(trackPath); + + // Act + ArtworkDto? result = LocalMusicArtworkEmbeddedCoverExtractor.Extract(trackPath); + + // Assert + Assert.Null(result); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkScannerTests.cs b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkScannerTests.cs new file mode 100644 index 00000000..e1a3a25e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Core/LocalMusicArtworkScannerTests.cs @@ -0,0 +1,487 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.IntegrationTests.Core; + +/// +/// Contains integration tests for the class, scanning real image files on the file system. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkScannerTests : IDisposable +{ + private readonly string _temporaryDirectory; + + /// + /// Initializes a new instance of the class. + /// + public LocalMusicArtworkScannerTests() + { + _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-local-music-artwork-scanner-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_temporaryDirectory); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheAlbumDirectoryCarriesTheStandardImages_ShouldReturnEachArtworkType() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Artist", "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "front.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "back.png")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet1.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "booklet2.png")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "disk.png")); + TestImageFileFactory.CreateGif(Path.Combine(albumDirectory, "tray.gif")); + TestImageFileFactory.CreateTiff(Path.Combine(albumDirectory, "spine.tiff")); + TestImageFileFactory.CreateBmp(Path.Combine(albumDirectory, "obi.bmp")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "sticker.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(albumDirectory, "poster.png")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "liner.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null), + new(ArtworkType.Front, 0, Path.Combine(albumDirectory, "front.jpg"), null), + new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.png"), null), + new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet1.jpg"), null), + new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet2.png"), null), + new(ArtworkType.Medium, 0, Path.Combine(albumDirectory, "disk.png"), null), + new(ArtworkType.Tray, 0, Path.Combine(albumDirectory, "tray.gif"), null), + new(ArtworkType.Spine, 0, Path.Combine(albumDirectory, "spine.tiff"), null), + new(ArtworkType.Obi, 0, Path.Combine(albumDirectory, "obi.bmp"), null), + new(ArtworkType.Sticker, 0, Path.Combine(albumDirectory, "sticker.jpg"), null), + new(ArtworkType.Poster, 0, Path.Combine(albumDirectory, "poster.png"), null), + new(ArtworkType.Liner, 0, Path.Combine(albumDirectory, "liner.jpg"), null) + ]; + Assert.Equal(12, result.Count); + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheStemCarriesANumber_ShouldUseItAsTheOrdinal() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet1.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet2.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk1.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk2.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Booklet, 0, Path.Combine(albumDirectory, "booklet.jpg"), null), + new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet1.jpg"), null), + new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet2.jpg"), null), + new(ArtworkType.Medium, 1, Path.Combine(albumDirectory, "disk1.jpg"), null), + new(ArtworkType.Medium, 2, Path.Combine(albumDirectory, "disk2.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheStemHasAHyphenOrUnderscoreBeforeTheNumber_ShouldTrimTheSeparator() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet - 1.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "booklet_2.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Booklet, 1, Path.Combine(albumDirectory, "booklet - 1.jpg"), null), + new(ArtworkType.Booklet, 2, Path.Combine(albumDirectory, "booklet_2.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenBothCoverAndFrontExist_ShouldReturnThemAsDistinctArtworks() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "front.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null), + new(ArtworkType.Front, 0, Path.Combine(albumDirectory, "front.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenSeveralNamesMapToTheSameTypeAndOrdinal_ShouldKeepOnlyThePreferredFile() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disk.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "disc.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + // Both file names describe the medium of the album, and the one that sorts first by name wins, so that a single image is stored per type and ordinal. + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Medium, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "disc.jpg"), artwork.LocalPath); + Assert.Null(artwork.RemoteUrl); + Assert.False(artwork.IsTemporary); + } + + [Fact] + public void ScanAlbumArtwork_WhenAFileIsNotAnImage_ShouldIgnoreIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateTextFile(Path.Combine(albumDirectory, "notes.txt")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(Path.Combine(albumDirectory, "cover.jpg"), artwork.LocalPath); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheImageExtensionIsUppercase_ShouldIgnoreIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.JPG")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.JPEG")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheImageNameHasDifferentCasing_ShouldIgnoreIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "Cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "BACK.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheImageNameIsNotRecognized_ShouldIgnoreIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "random.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "folder.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "backdrop.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheAlbumIsMultiDiscAndTheParentDirectoryCarriesTheArtwork_ShouldFindIt() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + string discDirectory = Path.Combine(albumDirectory, "CD1"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.jpg")); + Directory.CreateDirectory(discDirectory); + string trackPath = Path.Combine(discDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(albumDirectory, "cover.jpg"), null), + new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenBothTheDiscAndTheParentDirectoryCarryTheSameArtwork_ShouldPreferTheNearest() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + string discDirectory = Path.Combine(albumDirectory, "CD1"); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(discDirectory, "cover.jpg")); + string trackPath = Path.Combine(discDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(discDirectory, "cover.jpg"), artwork.LocalPath); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheDiscAndTheParentDirectoryCarryDifferentArtworks_ShouldReturnBoth() + { + // Arrange + string albumDirectory = Path.Combine(_temporaryDirectory, "Album"); + string discDirectory = Path.Combine(albumDirectory, "CD1"); + TestImageFileFactory.CreateJpeg(Path.Combine(discDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "back.jpg")); + string trackPath = Path.Combine(discDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(discDirectory, "cover.jpg"), null), + new(ArtworkType.Back, 0, Path.Combine(albumDirectory, "back.jpg"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheArtworkIsMoreThanTwoLevelsAboveTheTrack_ShouldNotFindIt() + { + // Arrange + TestImageFileFactory.CreateJpeg(Path.Combine(_temporaryDirectory, "cover.jpg")); + string trackPath = Path.Combine(_temporaryDirectory, "Album", "CD1", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no artwork + [InlineData("")] // an empty path contributes no artwork + [InlineData(" ")] // a white space path contributes no artwork + [InlineData("track.flac")] // a path without a directory part contributes no artwork + public void ScanAlbumArtwork_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath) + { + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanAlbumArtwork_WhenTheAlbumDirectoryDoesNotExist_ShouldReturnEmpty() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Album", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheArtistDirectoryCarriesTheStandardImages_ShouldReturnEachArtworkType() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "backdrop.jpg")); + TestImageFileFactory.CreatePng(Path.Combine(artistDirectory, "banner.png")); + TestImageFileFactory.CreateWebp(Path.Combine(artistDirectory, "logo.webp")); + TestImageFileFactory.CreateGif(Path.Combine(artistDirectory, "thumb.gif")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + List expected = + [ + new(ArtworkType.Cover, 0, Path.Combine(artistDirectory, "folder.jpg"), null), + new(ArtworkType.Backdrop, 0, Path.Combine(artistDirectory, "backdrop.jpg"), null), + new(ArtworkType.Banner, 0, Path.Combine(artistDirectory, "banner.png"), null), + new(ArtworkType.Logo, 0, Path.Combine(artistDirectory, "logo.webp"), null), + new(ArtworkType.Thumb, 0, Path.Combine(artistDirectory, "thumb.gif"), null) + ]; + Assert.Equal(expected, result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheDirectoryCarriesOnlyAlbumImages_ShouldReturnEmpty() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "cover.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "back.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "disk.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheArtistImagesAreInAnAncestorDirectory_ShouldFindThem() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "folder.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "CD1", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(artistDirectory, "folder.jpg"), artwork.LocalPath); + } + + [Fact] + public void ScanArtistArtwork_WhenSeveralAncestorDirectoriesCarryArtistImages_ShouldPreferTheNearest() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + string albumDirectory = Path.Combine(artistDirectory, "Album"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "backdrop.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "folder.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(albumDirectory, "cover.jpg")); + string trackPath = Path.Combine(albumDirectory, "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + // The nearest ancestor that carries an artist image wins, and the album images of that directory are not part of the artist artwork. + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(ArtworkType.Cover, artwork.Type); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(Path.Combine(albumDirectory, "folder.jpg"), artwork.LocalPath); + } + + [Fact] + public void ScanArtistArtwork_WhenTheArtistImagesAreBeyondTheSearchDepth_ShouldReturnEmpty() + { + // Arrange + TestImageFileFactory.CreateJpeg(Path.Combine(_temporaryDirectory, "folder.jpg")); + string trackPath = Path.Combine(_temporaryDirectory, "A", "B", "C", "D", "E", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheImageNameHasDifferentCasing_ShouldIgnoreIt() + { + // Arrange + string artistDirectory = Path.Combine(_temporaryDirectory, "Artist"); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "Folder.jpg")); + TestImageFileFactory.CreateJpeg(Path.Combine(artistDirectory, "Backdrop.jpg")); + string trackPath = Path.Combine(artistDirectory, "Album", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(null)] // a null path contributes no artwork + [InlineData("")] // an empty path contributes no artwork + [InlineData(" ")] // a white space path contributes no artwork + [InlineData("track.flac")] // a path without a directory part contributes no artwork + public void ScanArtistArtwork_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath) + { + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ScanArtistArtwork_WhenTheAncestorDirectoryDoesNotExist_ShouldReturnEmpty() + { + // Arrange + string trackPath = Path.Combine(_temporaryDirectory, "Missing", "Artist", "track.flac"); + + // Act + IReadOnlyList result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath); + + // Assert + Assert.Empty(result); + } + + /// + /// Removes the temporary directory created for the test. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests.csproj b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests.csproj new file mode 100644 index 00000000..ae7f44d4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests/Lumina.Plugins.LocalMusicArtwork.IntegrationTests.csproj @@ -0,0 +1,49 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Common/DependencyInjection/LocalMusicArtworkServicesTests.cs b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Common/DependencyInjection/LocalMusicArtworkServicesTests.cs new file mode 100644 index 00000000..3da0193d --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Common/DependencyInjection/LocalMusicArtworkServicesTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.LocalMusicArtwork.Common.DependencyInjection; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkServicesTests +{ + [Fact] + public void AddLocalMusicArtworkProviders_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddLocalMusicArtworkProviders_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddLocalMusicArtworkProviders_WhenCalled_ShouldRegisterTheAlbumAndArtistProvidersForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddLocalMusicArtworkProviders(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + IReadOnlyList providers = [.. serviceProvider.GetKeyedServices(pluginId)]; + Assert.Equal(2, providers.Count); + Assert.Contains(providers, provider => provider is LocalMusicAlbumArtworkProvider); + Assert.Contains(providers, provider => provider is LocalMusicArtistArtworkProvider); + Assert.Equal(2, providers.Select(provider => provider.GetType()).Distinct().Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void AddLocalMusicArtworkProviders_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddLocalMusicArtworkProviders(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(LocalMusicArtworkSettingsProvider)); + Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime); + } + + [Fact] + public void AddLocalMusicArtworkProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddSettingsProvider() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddLocalMusicArtworkProviders(pluginId: pluginId); + services.AddLocalMusicArtworkProviders(pluginId: pluginId); + + // Assert + // The settings provider is registered with TryAdd, so a second call must not add it again, while the artwork providers stay transient and are added once per call. + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(LocalMusicArtworkSettingsProvider)); + Assert.Equal(4, services.Count(descriptor => descriptor.ServiceType == typeof(IArtworkProvider))); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/LocalMusicArtworkPluginTests.cs b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/LocalMusicArtworkPluginTests.cs new file mode 100644 index 00000000..fccfaccf --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/LocalMusicArtworkPluginTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.LocalMusicArtwork.Core; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkPluginTests +{ + private readonly LocalMusicArtworkPlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(LocalMusicArtworkPlugin.s_pluginId, result); + Assert.Equal(new Guid("c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Local Music Artwork", 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("Reads the artwork of the artists and the albums from the images stored in the folders of a local music library.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnTheSingleSettingDescriptor() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + PluginSettingDescriptorDto descriptor = Assert.Single(result); + Assert.Equal(LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER, descriptor.Key); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldDescribeTheEmbeddedCoverSettingCorrectly() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + PluginSettingDescriptorDto descriptor = Assert.Single(result); + Assert.Equal("Extract embedded album cover image from audio files when it is not already present on disk", descriptor.Label); + Assert.Equal(PluginSettingType.Boolean, descriptor.Type); + Assert.Equal("true", descriptor.DefaultValue); + Assert.Null(descriptor.AllowedValues); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheAlbumAndArtistArtworkProviders() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + IReadOnlyList providers = [.. serviceProvider.GetKeyedServices(LocalMusicArtworkPlugin.s_pluginId)]; + Assert.Equal(2, providers.Count); + Assert.Contains(providers, provider => provider is LocalMusicAlbumArtworkProvider); + Assert.Contains(providers, provider => provider is LocalMusicArtistArtworkProvider); + Assert.Equal(2, providers.Select(provider => provider.GetType()).Distinct().Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/Settings/LocalMusicArtworkSettingsProviderTests.cs b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/Settings/LocalMusicArtworkSettingsProviderTests.cs new file mode 100644 index 00000000..4835b085 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Core/Settings/LocalMusicArtworkSettingsProviderTests.cs @@ -0,0 +1,223 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings; +using Lumina.Plugins.LocalMusicArtwork.Core.Settings; +using Lumina.Plugins.LocalMusicArtwork.Fixtures.Common.Models.DTO.Settings; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.LocalMusicArtwork.UnitTests.Core.Settings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LocalMusicArtworkSettingsProviderTests +{ + private readonly LocalMusicArtworkSettingsDtoFixture _localMusicArtworkSettingsDtoFixture = new(); + + [Fact] + public async Task GetAsync_WhenNoStoreIsAvailable_ShouldReturnTheDefaults() + { + // Arrange + LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: true); + LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), defaults); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.NotSame(defaults, result); + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenNoStoreIsAvailableAndTheDefaultsDisableExtraction_ShouldReturnTheDisabledDefault() + { + // Arrange + LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: false); + LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), defaults); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.False(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenTheStoreReturnsNoSettings_ShouldReturnTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns((IReadOnlyDictionary?)null); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Theory] + [InlineData("false", true, false)] // a stored value disables extraction over a default that enables it + [InlineData("true", false, true)] // a stored value enables extraction over a default that disables it + [InlineData("True", false, true)] // the stored value is parsed without regard to casing + [InlineData("FALSE", true, false)] // the stored value is parsed without regard to casing + public async Task GetAsync_WhenTheSettingIsPersisted_ShouldOverlayItOverTheDefaults(string storedValue, bool defaultValue, bool expectedValue) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = storedValue }); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: defaultValue)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedValue, result.ShouldExtractEmbeddedCover); + } + + [Theory] + [InlineData("not-a-boolean")] + [InlineData("")] + [InlineData(" ")] + [InlineData("1")] + [InlineData("0")] + [InlineData("yes")] + public async Task GetAsync_WhenThePersistedSettingIsNotABoolean_ShouldKeepTheDefault(string storedValue) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = storedValue }); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenThePersistedSettingsDoNotContainTheKey_ShouldKeepTheDefault() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { ["SomeOtherKey"] = "false" }); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenThePersistedKeyHasDifferentCasing_ShouldKeepTheDefault() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { ["shouldextractembeddedcover"] = "false" }); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.True(result.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenThePersistedSettingOverridesTheDefaults_ShouldNotMutateTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [LocalMusicArtworkSettingsKeys.SHOULD_EXTRACT_EMBEDDED_COVER] = "false" }); + LocalMusicArtworkSettingsDto defaults = CreateDefaults(shouldExtractEmbeddedCover: true); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), defaults); + + // Act + LocalMusicArtworkSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.False(result.ShouldExtractEmbeddedCover); + Assert.True(defaults.ShouldExtractEmbeddedCover); + } + + [Fact] + public async Task GetAsync_WhenCalledTwice_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto first = await sut.GetAsync(CancellationToken.None); + LocalMusicArtworkSettingsDto second = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Same(first, second); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + LocalMusicArtworkSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + LocalMusicArtworkSettingsDto[] results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => sut.GetAsync(CancellationToken.None))); + + // Assert + Assert.All(results, result => Assert.Same(results[0], result)); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + LocalMusicArtworkSettingsProvider sut = new(null, Guid.NewGuid(), CreateDefaults(shouldExtractEmbeddedCover: true)); + + // Act + Task Act() + { + return sut.GetAsync(cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + /// + /// Creates the default settings used by the tests of the provider. + /// + /// Whether the cover embedded in the audio files is extracted when the album has no cover image on disk. + /// The default settings. + private LocalMusicArtworkSettingsDto CreateDefaults(bool shouldExtractEmbeddedCover) + { + return _localMusicArtworkSettingsDtoFixture.Create(shouldExtractEmbeddedCover: shouldExtractEmbeddedCover); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests.csproj new file mode 100644 index 00000000..b0d3aff0 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests/Lumina.Plugins.LocalMusicArtwork.UnitTests.csproj @@ -0,0 +1,47 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + +