mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the local music artwork plugin, its fixtures, and its unit and integration test suites
This commit is contained in:
1 parent
fb05561619
commit
62b0e9297a
25 files changed
+2720
No files matched your search
+43
@@ -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;
|
||||
}
|
||||
}
|
||||
+13
@@ -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));
|
||||
}
|
||||
}
|
||||
+73
@@ -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
|
||||
);
|
||||
}
|
||||
+12
@@ -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";
|
||||
}
|
||||
+85
@@ -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")]
|
||||
Reference in new issue
Block a user