Adds the local music artwork plugin, its fixtures, and its unit and integration test suites

This commit is contained in:
BinaryAlley committed 2026-10-04 21:16:42 +03:00
1 parent fb05561619
commit 62b0e9297a
25 files changed
+2720

No files matched your search

@@ -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;
/// <summary>
/// Utility class for registering the services of the local music artwork providers into the Dependency Injection container.
/// </summary>
internal static class LocalMusicArtworkServices
{
/// <summary>
/// Registers the services of the local music artwork providers into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the artwork.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
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<IPluginSettingsStore>();
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<IArtworkProvider, LocalMusicAlbumArtworkProvider>(pluginId);
services.AddKeyedTransient<IArtworkProvider, LocalMusicArtistArtworkProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,13 @@
namespace Lumina.Plugins.LocalMusicArtwork.Common.Models.DTO.Settings;
/// <summary>
/// Data transfer object for the settings that configure the local music artwork plugin.
/// </summary>
internal sealed class LocalMusicArtworkSettingsDto
{
/// <summary>
/// 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 <see langword="true"/>, so that a cover is found even when the library stores none on disk.
/// </summary>
public bool ShouldExtractEmbeddedCover { get; set; } = true;
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal sealed class LocalMusicAlbumArtworkProvider : IArtworkProvider<AlbumMetadataLookupDto>
{
private readonly LocalMusicArtworkSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the artwork provider.
/// </summary>
public string Name => "Local Music Artwork";
/// <summary>
/// Gets the media library types this artwork provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicAlbumArtworkProvider"/> class.
/// </summary>
/// <param name="settingsProvider">The provider of the runtime settings of the plugin.</param>
public LocalMusicAlbumArtworkProvider(LocalMusicArtworkSettingsProvider settingsProvider)
{
_settingsProvider = settingsProvider;
}
/// <summary>
/// Gets the artworks of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the artwork for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artworks of the album, or an empty collection when no artwork was found.</returns>
public async Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
IReadOnlyList<ArtworkDto> 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];
}
}
@@ -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;
/// <summary>
/// Provides the artwork of an artist from the images stored in the folders of the local music library of the user.
/// </summary>
internal sealed class LocalMusicArtistArtworkProvider : IArtworkProvider<ArtistMetadataLookupDto>
{
/// <summary>
/// Gets the display name of the artwork provider.
/// </summary>
public string Name => "Local Music Artwork";
/// <summary>
/// Gets the media library types this artwork provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Gets the artworks of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to get the artwork for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artworks of the artist, or an empty collection when no artwork was found.</returns>
public Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return Task.FromResult(LocalMusicArtworkScanner.ScanArtistArtwork(lookup.Path));
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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.
/// <summary>
/// Extracts the first embedded cover image of the audio file stored at <paramref name="trackPath"/> into a temporary file.
/// </summary>
/// <param name="trackPath">The file system path of the audio file whose embedded cover is extracted.</param>
/// <returns>The extracted cover artwork, which points to a temporary file, or <see langword="null"/> when the file carries no usable embedded cover.</returns>
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;
}
}
/// <summary>
/// Resolves the file extension of an embedded cover image from its MIME type.
/// </summary>
/// <param name="mimeType">The MIME type of the embedded cover image.</param>
/// <returns>The file extension matching the MIME type, falling back to the JPEG extension.</returns>
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"
};
}
}
@@ -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;
/// <summary>
/// Plugin that provides the artwork of music artists and albums from the images stored in the folders of a local music library.
/// </summary>
public sealed class LocalMusicArtworkPlugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "Local Music Artwork";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Reads the artwork of the artists and the albums from the images stored in the folders of a local music library.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> 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")
];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddLocalMusicArtworkProviders(pluginId: Id);
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<string> s_imageExtensions = new([".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif", ".tif", ".tiff"], StringComparer.Ordinal);
/// <summary>
/// Scans the directory of the provided track, and its parent directory, for the artwork of an album.
/// </summary>
/// <param name="trackPath">The file system path of a track of the album.</param>
/// <returns>The artwork of the album, or an empty collection when no artwork was found.</returns>
public static IReadOnlyList<ArtworkDto> 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<ArtworkDto> 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;
}
/// <summary>
/// Scans the ancestor directories of the provided track for the artwork of an artist.
/// </summary>
/// <param name="trackPath">The file system path of a track of the artist.</param>
/// <returns>The artwork of the artist, or an empty collection when no artwork was found.</returns>
public static IReadOnlyList<ArtworkDto> 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<ArtworkDto> artworks = ClassifyImages(currentDirectory, isArtist: true);
if (artworks.Count > 0)
return artworks;
currentDirectory = currentDirectory.Parent;
level++;
}
return [];
}
/// <summary>
/// Classifies the images directly contained in <paramref name="directory"/>.
/// </summary>
/// <param name="directory">The directory whose images are classified.</param>
/// <param name="isArtist">Whether the images belong to an artist, as opposed to an album.</param>
/// <returns>The classified artwork, one for every recognized file, ordered by type and ordinal.</returns>
private static IReadOnlyList<ArtworkDto> ClassifyImages(DirectoryInfo directory, bool isArtist)
{
FileInfo[] files;
try
{
files = [.. directory.EnumerateFiles()];
}
catch (IOException)
{
return [];
}
catch (UnauthorizedAccessException)
{
return [];
}
List<ClassifiedArtwork> 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<ArtworkDto> 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;
}
/// <summary>
/// Splits the stem of an image file into the base name that identifies the artwork and the ordinal that orders it within its type.
/// </summary>
/// <param name="stem">The stem of the image file, without its extension.</param>
/// <returns>The base name of the artwork and the ordinal it carries, which is zero when the stem carries no number.</returns>
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);
}
/// <summary>
/// Maps the base name of an artist image onto an artwork type.
/// </summary>
/// <param name="baseName">The base name of the image file.</param>
/// <param name="artworkType">The mapped artwork type, when the base name is recognized.</param>
/// <param name="priority">The priority of the base name among the file names of the same artwork type and ordinal, lower being preferred.</param>
/// <returns><see langword="true"/> when the base name was recognized, otherwise <see langword="false"/>.</returns>
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;
}
}
/// <summary>
/// Maps the base name of an album image onto an artwork type.
/// </summary>
/// <param name="baseName">The base name of the image file.</param>
/// <param name="artworkType">The mapped artwork type, when the base name is recognized.</param>
/// <param name="priority">The priority of the base name among the file names of the same artwork type and ordinal, lower being preferred.</param>
/// <returns><see langword="true"/> when the base name was recognized, otherwise <see langword="false"/>.</returns>
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;
}
}
/// <summary>
/// Gets the directory of the provided <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path whose directory is retrieved.</param>
/// <returns>The directory of the path, or <see langword="null"/> when the path is empty or has no directory part.</returns>
private static string? GetDirectoryOrNull(string? path)
{
if (string.IsNullOrWhiteSpace(path))
return null;
string? directory = Path.GetDirectoryName(path);
return string.IsNullOrWhiteSpace(directory) ? null : directory;
}
/// <summary>
/// A recognized image of an artist or an album, before it is ordered and de-duplicated.
/// </summary>
/// <param name="Type">The type of the artwork.</param>
/// <param name="Ordinal">The ordinal of the artwork within its type.</param>
/// <param name="Priority">The priority of the file name among the files of the same artwork type and ordinal, lower being preferred.</param>
/// <param name="FileName">The name of the image file.</param>
/// <param name="FilePath">The file system path of the image file.</param>
private sealed record ClassifiedArtwork(
ArtworkType Type,
int Ordinal,
int Priority,
string FileName,
string FilePath
);
}
@@ -0,0 +1,12 @@
namespace Lumina.Plugins.LocalMusicArtwork.Core.Settings;
/// <summary>
/// Keys of the settings of the local music artwork plugin, shared by the settings schema and the settings provider.
/// </summary>
internal static class LocalMusicArtworkSettingsKeys
{
/// <summary>
/// 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.
/// </summary>
internal const string SHOULD_EXTRACT_EMBEDDED_COVER = "ShouldExtractEmbeddedCover";
}
@@ -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;
/// <summary>
/// Provides the runtime settings of the local music artwork plugin, overlaying the settings persisted by the host over the configured defaults.
/// </summary>
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;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicArtworkSettingsProvider"/> class.
/// </summary>
/// <param name="settingsStore">The store of the settings persisted by the host, or <see langword="null"/> when no store is available.</param>
/// <param name="pluginId">The unique identifier of the plugin whose settings are read.</param>
/// <param name="defaults">The runtime settings with the default values and the optional configuration callback already applied.</param>
public LocalMusicArtworkSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, LocalMusicArtworkSettingsDto defaults)
{
_settingsStore = settingsStore;
_pluginId = pluginId;
_defaults = defaults;
}
/// <summary>
/// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The runtime settings of the plugin.</returns>
public async Task<LocalMusicArtworkSettingsDto> 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<string, string>? 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();
}
}
}
@@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="TagLibSharp" />
</ItemGroup>
</Project>
@@ -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")]
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LocalMusicArtworkSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class LocalMusicArtworkSettingsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="LocalMusicArtworkSettingsDto"/> instance with randomized test data.
/// </summary>
/// <param name="shouldExtractEmbeddedCover">Optional. Whether the cover embedded in the audio files is extracted when the album has no cover image on disk.</param>
/// <returns>A configured <see cref="LocalMusicArtworkSettingsDto"/> instance.</returns>
public LocalMusicArtworkSettingsDto Create(
bool? shouldExtractEmbeddedCover = null)
{
return new LocalMusicArtworkSettingsDto
{
ShouldExtractEmbeddedCover = shouldExtractEmbeddedCover ?? _faker.Random.Bool()
};
}
/// <summary>
/// Creates multiple <see cref="LocalMusicArtworkSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LocalMusicArtworkSettingsDto"/> instances.</returns>
public List<LocalMusicArtworkSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,124 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Core;
/// <summary>
/// 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.
/// </summary>
[ExcludeFromCodeCoverage]
public static class TestAudioFileFactory
{
/// <summary>
/// Creates a minimal, untagged PCM WAV file.
/// </summary>
/// <param name="path">The path where the WAV is written.</param>
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
public static void CreateWav(string path, int durationMs = 200)
{
WriteFile(path, BuildWav(durationMs));
}
/// <summary>
/// Creates a PCM WAV file that carries the provided image as its embedded front cover.
/// </summary>
/// <param name="path">The path where the WAV is written.</param>
/// <param name="imageBytes">The bytes of the embedded cover image.</param>
/// <param name="mimeType">The MIME type of the embedded cover image, defaulting to JPEG.</param>
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
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);
}
/// <summary>
/// Creates a PCM WAV file whose embedded tags are configured by the provided callback.
/// </summary>
/// <param name="path">The path where the WAV is written.</param>
/// <param name="configureTags">The callback that configures the tags of the file.</param>
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
public static void CreateTaggedWav(string path, Action<TagLib.File> configureTags, int durationMs = 200)
{
WriteFile(path, BuildWav(durationMs));
using (TagLib.File tagFile = TagLib.File.Create(path))
{
configureTags(tagFile);
tagFile.Save();
}
}
/// <summary>
/// Creates a file whose content is not a recognizable audio container, so that the resilience of the embedded cover extraction can be exercised.
/// </summary>
/// <param name="path">The path where the file is written.</param>
public static void CreateUnsupportedFile(string path)
{
WriteFile(path, Encoding.UTF8.GetBytes("This is not an audio file."));
}
/// <summary>
/// Writes the provided bytes at <paramref name="path"/>, creating the containing directory when it does not exist yet.
/// </summary>
/// <param name="path">The path where the bytes are written.</param>
/// <param name="contents">The bytes of the file.</param>
private static void WriteFile(string path, byte[] contents)
{
string? directory = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
File.WriteAllBytes(path, contents);
}
/// <summary>
/// Builds the bytes of a minimal, valid PCM WAV file with a single silent audio channel.
/// </summary>
/// <param name="durationMs">The duration of the audio of the file, in milliseconds.</param>
/// <returns>The bytes of the WAV file.</returns>
private static byte[] BuildWav(int durationMs)
{
const int SAMPLE_RATE = 44100;
const short CHANNELS = 1;
const short BITS_PER_SAMPLE = 16;
int bytesPerSample = BITS_PER_SAMPLE / 8;
int dataSize = SAMPLE_RATE * CHANNELS * bytesPerSample * durationMs / 1000;
using (MemoryStream memoryStream = new())
{
using (BinaryWriter writer = new(memoryStream))
{
writer.Write(Encoding.ASCII.GetBytes("RIFF"));
writer.Write(36 + dataSize);
writer.Write(Encoding.ASCII.GetBytes("WAVE"));
writer.Write(Encoding.ASCII.GetBytes("fmt "));
writer.Write(16);
writer.Write((short)1);
writer.Write(CHANNELS);
writer.Write(SAMPLE_RATE);
writer.Write(SAMPLE_RATE * CHANNELS * bytesPerSample);
writer.Write((short)(CHANNELS * bytesPerSample));
writer.Write(BITS_PER_SAMPLE);
writer.Write(Encoding.ASCII.GetBytes("data"));
writer.Write(dataSize);
writer.Write(new byte[dataSize]);
}
return memoryStream.ToArray();
}
}
}
@@ -0,0 +1,91 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
#endregion
namespace Lumina.Plugins.LocalMusicArtwork.Fixtures.Core;
/// <summary>
/// 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.
/// </summary>
[ExcludeFromCodeCoverage]
public static class TestImageFileFactory
{
/// <summary>
/// Creates a JPEG image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
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]);
}
/// <summary>
/// Creates a PNG image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreatePng(string path)
{
WriteFile(path, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52]);
}
/// <summary>
/// Creates a WebP image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateWebp(string path)
{
WriteFile(path, [.. Encoding.ASCII.GetBytes("RIFF"), 0x00, 0x00, 0x00, 0x00, .. Encoding.ASCII.GetBytes("WEBP")]);
}
/// <summary>
/// Creates a BMP image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateBmp(string path)
{
WriteFile(path, [0x42, 0x4D, 0x00, 0x00, 0x00, 0x00]);
}
/// <summary>
/// Creates a GIF image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateGif(string path)
{
WriteFile(path, [.. Encoding.ASCII.GetBytes("GIF89a")]);
}
/// <summary>
/// Creates a TIFF image file at the provided path.
/// </summary>
/// <param name="path">The path where the image is written.</param>
public static void CreateTiff(string path)
{
WriteFile(path, [0x49, 0x49, 0x2A, 0x00]);
}
/// <summary>
/// Creates a file whose content is not an image, so that the exclusion of non image files can be exercised.
/// </summary>
/// <param name="path">The path where the file is written.</param>
public static void CreateTextFile(string path)
{
WriteFile(path, Encoding.UTF8.GetBytes("This is not an image."));
}
/// <summary>
/// Writes the provided bytes at <paramref name="path"/>, creating the containing directory when it does not exist yet.
/// </summary>
/// <param name="path">The path where the bytes are written.</param>
/// <param name="contents">The bytes of the file.</param>
private static void WriteFile(string path, byte[] contents)
{
string? directory = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
File.WriteAllBytes(path, contents);
}
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
<IsPackable>false</IsPackable>
<IsTestProject>false</IsTestProject>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" />
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="TagLibSharp" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.LocalMusicArtwork\Lumina.Plugins.LocalMusicArtwork.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,21 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lumina.Plugins.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")]
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="LocalMusicAlbumArtworkProvider"/> class, reading real image and audio files from the file system.
/// </summary>
[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;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicAlbumArtworkProviderTests"/> class.
/// </summary>
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<LibraryType> 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<ArtworkDto> result = await sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
List<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<OperationCanceledException>(Act);
}
}
/// <summary>
/// Creates a <see cref="LocalMusicAlbumArtworkProvider"/> whose settings provider carries the provided embedded cover extraction setting.
/// </summary>
/// <param name="shouldExtractEmbeddedCover">Whether the cover embedded in the audio files is extracted when the album has no cover image on disk.</param>
/// <returns>The created provider.</returns>
private LocalMusicAlbumArtworkProvider CreateProvider(bool shouldExtractEmbeddedCover)
{
LocalMusicArtworkSettingsProvider settingsProvider = new(
null,
Guid.NewGuid(),
_localMusicArtworkSettingsDtoFixture.Create(shouldExtractEmbeddedCover: shouldExtractEmbeddedCover));
return new LocalMusicAlbumArtworkProvider(settingsProvider);
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,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;
/// <summary>
/// Contains integration tests for the <see cref="LocalMusicArtistArtworkProvider"/> class, reading real image files from the file system.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtistArtworkProviderTests : IDisposable
{
private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new();
private readonly LocalMusicArtistArtworkProvider _sut = new();
private readonly string _temporaryDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicArtistArtworkProviderTests"/> class.
/// </summary>
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<LibraryType> result = _sut.SupportedLibraryTypes;
// Assert
Assert.Equal([LibraryType.Music], result);
}
[Fact]
public void RequiresWebAccess_WhenCalled_ShouldReturnFalse()
{
// Act
bool result = _sut.RequiresWebAccess;
// Assert
Assert.False(result);
}
[Fact]
public async Task 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<ArtworkDto> result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
// Assert
List<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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);
}
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,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;
/// <summary>
/// Contains integration tests for the <see cref="LocalMusicArtworkEmbeddedCoverExtractor"/> class, reading real audio containers that carry embedded pictures.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtworkEmbeddedCoverExtractorTests : IDisposable
{
private static readonly byte[] s_coverBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0x11, 0x22, 0x33, 0xFF, 0xD9];
private readonly string _temporaryDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicArtworkEmbeddedCoverExtractorTests"/> class.
/// </summary>
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);
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,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;
/// <summary>
/// Contains integration tests for the <see cref="LocalMusicArtworkScanner"/> class, scanning real image files on the file system.
/// </summary>
[ExcludeFromCodeCoverage]
public class LocalMusicArtworkScannerTests : IDisposable
{
private readonly string _temporaryDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMusicArtworkScannerTests"/> class.
/// </summary>
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<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> 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<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> 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<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> 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<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> result = LocalMusicArtworkScanner.ScanAlbumArtwork(trackPath);
// Assert
List<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
List<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> result = LocalMusicArtworkScanner.ScanArtistArtwork(trackPath);
// Assert
Assert.Empty(result);
}
/// <summary>
/// Removes the temporary directory created for the test.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectory))
Directory.Delete(_temporaryDirectory, recursive: true);
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,49 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="TagLibSharp" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.LocalMusicArtwork\Lumina.Plugins.LocalMusicArtwork.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Plugins.LocalMusicArtwork.Fixtures\Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="LocalMusicArtworkServices"/> class.
/// </summary>
[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<ArgumentNullException>(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<IArtworkProvider> providers = [.. serviceProvider.GetKeyedServices<IArtworkProvider>(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<IArtworkProvider>(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)));
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="LocalMusicArtworkPlugin"/> class.
/// </summary>
[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<PluginSettingDescriptorDto> 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<PluginSettingDescriptorDto> 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<IArtworkProvider> providers = [.. serviceProvider.GetKeyedServices<IArtworkProvider>(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<IArtworkProvider>(Guid.NewGuid()));
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="LocalMusicArtworkSettingsProvider"/> class.
/// </summary>
[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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IReadOnlyDictionary<string, string>?)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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { ["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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { ["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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<string, string>());
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<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<string, string>());
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<Guid>(), Arg.Any<CancellationToken>());
}
[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<OperationCanceledException>(Act);
}
}
/// <summary>
/// Creates the default settings used by the tests of the provider.
/// </summary>
/// <param name="shouldExtractEmbeddedCover">Whether the cover embedded in the audio files is extracted when the album has no cover image on disk.</param>
/// <returns>The default settings.</returns>
private LocalMusicArtworkSettingsDto CreateDefaults(bool shouldExtractEmbeddedCover)
{
return _localMusicArtworkSettingsDtoFixture.Create(shouldExtractEmbeddedCover: shouldExtractEmbeddedCover);
}
}
@@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.LocalMusicArtwork\Lumina.Plugins.LocalMusicArtwork.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Plugins.LocalMusicArtwork.Fixtures\Lumina.Plugins.LocalMusicArtwork.Fixtures.csproj" />
</ItemGroup>
</Project>