mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the Cover Art Archive music artwork plugin, its fixtures, and its unit and security test suites
This commit is contained in:
1 parent
c8a8d8750b
commit
fb05561619
36 files changed
+4029
No files matched your search
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.CoverArtArchive.Core;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Api;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Utility class for registering the services of the Cover Art Archive artwork provider into the Dependency Injection container.
|
||||
/// </summary>
|
||||
internal static class CoverArtArchiveServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the services of the Cover Art Archive artwork provider 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>
|
||||
/// <param name="settingsCallback">Action used to configure the <see cref="CoverArtArchiveSettingsDto"/>.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
internal static IServiceCollection AddCoverArtArchiveArtworkProvider(this IServiceCollection services, Guid pluginId, Action<CoverArtArchiveSettingsDto>? settingsCallback = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
// Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
|
||||
services.TryAddScoped(serviceProvider =>
|
||||
{
|
||||
CoverArtArchiveSettingsDto defaults = new();
|
||||
settingsCallback?.Invoke(defaults);
|
||||
|
||||
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
|
||||
return new CoverArtArchiveSettingsProvider(settingsStore, pluginId, defaults);
|
||||
});
|
||||
|
||||
// The throttle must be process-wide, because the Cover Art Archive API enforces its request policy across all callers, not per scope.
|
||||
services.TryAddSingleton<CoverArtArchiveRequestThrottle>();
|
||||
|
||||
// The response cache is process-wide, so that an entity shared by many items, like the release group shared by the releases of an album,
|
||||
// is fetched only once during a run.
|
||||
services.TryAddSingleton<CoverArtArchiveResponseCache>();
|
||||
|
||||
// Automatic redirects are disabled on purpose: the metadata endpoints answer with a temporary redirect to the Internet Archive, and the client
|
||||
// follows that redirect itself, checking every hop against CoverArtArchiveHosts. Letting the primary handler follow redirects automatically
|
||||
// would make it follow whatever Location the response carries, which is server controlled, and would bypass that host check, which is the SSRF
|
||||
// control here; the base URL being a constant does not make the redirect target trustworthy.
|
||||
services.AddHttpClient<CoverArtArchiveHttpClient>()
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
// Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations.
|
||||
services.AddKeyedTransient<IArtworkProvider, CoverArtArchiveAlbumArtworkProvider>(pluginId);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the artwork of a release or a release group from the Cover Art Archive API.
|
||||
/// </summary>
|
||||
internal sealed record CoverArtArchiveArtworkResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the images of the artwork. It is nullable because the deserializer writes a JSON null over the initializer, and may also contain null elements.
|
||||
/// </summary>
|
||||
[JsonPropertyName("images")]
|
||||
public List<CoverArtArchiveImageResponse?>? Images { get; init; }
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for a single image of the artwork of a release or a release group from the Cover Art Archive API.
|
||||
/// </summary>
|
||||
internal sealed record CoverArtArchiveImageResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the URL of the full size image.
|
||||
/// </summary>
|
||||
[JsonPropertyName("image")]
|
||||
public string? Image { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the URL of the thumbnail of the image.
|
||||
/// </summary>
|
||||
[JsonPropertyName("thumbnail")]
|
||||
public string? Thumbnail { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the types of the image, like "Front", "Back", "Booklet", "Medium", "Tray", "Spine" or "Poster".
|
||||
/// It is nullable because the deserializer writes a JSON null over the initializer, and may also contain null elements.
|
||||
/// </summary>
|
||||
[JsonPropertyName("types")]
|
||||
public List<string?>? Types { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the image is the front cover.
|
||||
/// </summary>
|
||||
[JsonPropertyName("front")]
|
||||
public bool IsFront { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the image is the back cover.
|
||||
/// </summary>
|
||||
[JsonPropertyName("back")]
|
||||
public bool IsBack { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional comment describing the image.
|
||||
/// </summary>
|
||||
[JsonPropertyName("comment")]
|
||||
public string? Comment { get; init; }
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the settings that configure the Cover Art Archive artwork plugin.
|
||||
/// </summary>
|
||||
internal sealed class CoverArtArchiveSettingsDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the user agent sent with every request to the Cover Art Archive API.
|
||||
/// </summary>
|
||||
public string UserAgent { get; set; } = "Lumina-CoverArtArchive/1.0";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the contact email sent with every request to the Cover Art Archive API.
|
||||
/// The MetaBrainz services expect a meaningful user agent that carries a way to contact its author.
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the minimum interval between consecutive requests to the Cover Art Archive API, so that the public service is not overwhelmed.
|
||||
/// </summary>
|
||||
public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0);
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Settings;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP client that calls the Cover Art Archive API and deserializes its JSON responses into typed response models.
|
||||
/// </summary>
|
||||
internal sealed class CoverArtArchiveHttpClient
|
||||
{
|
||||
private const string BASE_URL = "https://coverartarchive.org/";
|
||||
|
||||
// Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich.
|
||||
private const int MAXIMUM_ATTEMPT_COUNT = 3;
|
||||
|
||||
// The metadata endpoints of the Cover Art Archive answer with a temporary redirect to the Internet Archive, so a bounded number of redirects is followed.
|
||||
private const int MAXIMUM_REDIRECT_COUNT = 3;
|
||||
|
||||
// The delay requested by a rate limited response is honored, but only up to this many seconds, so a misbehaving server cannot stall the scan.
|
||||
private const double MAXIMUM_RETRY_DELAY_SECONDS = 60;
|
||||
|
||||
private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly CoverArtArchiveSettingsProvider _settingsProvider;
|
||||
private readonly CoverArtArchiveRequestThrottle _requestThrottle;
|
||||
private readonly CoverArtArchiveResponseCache _responseCache;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CoverArtArchiveHttpClient"/> class.
|
||||
/// </summary>
|
||||
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the Cover Art Archive API.</param>
|
||||
/// <param name="settingsProvider">The provider of the settings that configure the Cover Art Archive API requests.</param>
|
||||
/// <param name="requestThrottle">The process-wide throttle that spaces out the requests sent to the Cover Art Archive API.</param>
|
||||
/// <param name="responseCache">The process-wide cache that avoids fetching the same entity more than once during a run.</param>
|
||||
public CoverArtArchiveHttpClient(HttpClient httpClient, CoverArtArchiveSettingsProvider settingsProvider, CoverArtArchiveRequestThrottle requestThrottle, CoverArtArchiveResponseCache responseCache)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_settingsProvider = settingsProvider;
|
||||
_requestThrottle = requestThrottle;
|
||||
_responseCache = responseCache;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artwork of the release identified by <paramref name="musicBrainzReleaseId"/>.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artwork of the release, or <see langword="null"/> when the release has no artwork.</returns>
|
||||
public Task<CoverArtArchiveArtworkResponse?> GetReleaseArtworkAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetJsonOrNullAsync<CoverArtArchiveArtworkResponse>($"release/{musicBrainzReleaseId:D}", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artwork of the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
|
||||
/// </summary>
|
||||
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artwork of the release group, or <see langword="null"/> when the release group has no artwork.</returns>
|
||||
public Task<CoverArtArchiveArtworkResponse?> GetReleaseGroupArtworkAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetJsonOrNullAsync<CoverArtArchiveArtworkResponse>($"release-group/{musicBrainzReleaseGroupId:D}", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the JSON resource at the given relative URL and deserializes it into <typeparamref name="TModel"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The type to deserialize the JSON response into.</typeparam>
|
||||
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized resource, or <see langword="null"/> when the resource was not found.</returns>
|
||||
private async Task<TModel?> GetJsonOrNullAsync<TModel>(string relativeUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
// A cached response, including a confirmed absence of artwork, removes the repeated lookups of the same entity, like the release group that the
|
||||
// releases of an edition heavy library share, or the same library scanned again while the entry is still valid.
|
||||
if (_responseCache.TryGet(relativeUrl, out string? cachedJson))
|
||||
return string.IsNullOrEmpty(cachedJson) ? default : JsonSerializer.Deserialize<TModel>(cachedJson, s_serializerOptions);
|
||||
|
||||
CoverArtArchiveSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false);
|
||||
// A 404 means the entity exists but has no artwork, which is a normal miss rather than an error, so it is reported as no result and cached as such.
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
_responseCache.Set(relativeUrl, string.Empty);
|
||||
return default;
|
||||
}
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
TModel? model = JsonSerializer.Deserialize<TModel>(json, s_serializerOptions);
|
||||
_responseCache.Set(relativeUrl, json);
|
||||
return model;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to the Cover Art Archive API, throttled to respect the configured minimum request interval. Transient failures and
|
||||
/// rate limiting are retried, so a single hiccup does not surface as a failed resolution.
|
||||
/// </summary>
|
||||
/// <param name="settings">The settings that configure the Cover Art Archive API requests.</param>
|
||||
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The HTTP response message for the request.</returns>
|
||||
private async Task<HttpResponseMessage> SendAsync(CoverArtArchiveSettingsDto settings, string relativeUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
EnsureRequestHeaders(settings);
|
||||
|
||||
Uri requestUri = new(new Uri(BASE_URL, UriKind.Absolute), relativeUrl);
|
||||
|
||||
// The metadata endpoints answer with a temporary redirect to the Internet Archive, so the redirect is followed explicitly, which keeps the
|
||||
// automatic redirects disabled and confines the following to the hosts the Cover Art Archive is allowed to delegate its responses to.
|
||||
for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++)
|
||||
{
|
||||
HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!IsRedirect(response.StatusCode) || response.Headers.Location is null)
|
||||
return response;
|
||||
|
||||
Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location);
|
||||
// The response of a redirect is not returned, so it must be disposed here to release its connection.
|
||||
response.Dispose();
|
||||
|
||||
// A redirect that is not an absolute HTTPS URL, or that points to a host other than the Cover Art Archive or the Internet Archive, is refused,
|
||||
// so a compromised or misbehaving endpoint cannot redirect the request to any other host.
|
||||
if (redirectUri is null || redirectUri.Scheme != Uri.UriSchemeHttps || !CoverArtArchiveHosts.IsAllowed(redirectUri.Host))
|
||||
throw new HttpRequestException($"The Cover Art Archive redirected the request to the disallowed host '{redirectUri?.Host}'.");
|
||||
|
||||
requestUri = redirectUri;
|
||||
}
|
||||
|
||||
throw new HttpRequestException("The Cover Art Archive redirected the request too many times.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to <paramref name="requestUri"/>, throttled to respect the configured minimum request interval.
|
||||
/// Transient failures and rate limiting are retried, so a single hiccup does not surface as a failed resolution.
|
||||
/// </summary>
|
||||
/// <param name="settings">The settings that configure the Cover Art Archive API requests.</param>
|
||||
/// <param name="requestUri">The absolute URI of the resource to request.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The HTTP response message for the request.</returns>
|
||||
private async Task<HttpResponseMessage> SendWithRetriesAsync(CoverArtArchiveSettingsDto settings, Uri requestUri, CancellationToken cancellationToken)
|
||||
{
|
||||
// A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every
|
||||
// attempt, so that the retries of a failed request cannot burst past the rate limit of the public service.
|
||||
for (int attempt = 1; ; attempt++)
|
||||
{
|
||||
await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT;
|
||||
HttpResponseMessage response;
|
||||
try
|
||||
{
|
||||
HttpRequestMessage request = new(HttpMethod.Get, requestUri);
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpRequestException) when (!isLastAttempt)
|
||||
{
|
||||
await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500))
|
||||
{
|
||||
// The delay is read before the response is disposed, because a rate limited response tells the caller how long to wait.
|
||||
TimeSpan retryDelay = GetRetryDelay(attempt, response);
|
||||
// The response of a failed attempt is not returned, so it must be disposed here to release its connection.
|
||||
response.Dispose();
|
||||
await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided status code is a redirect.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code to check.</param>
|
||||
/// <returns><see langword="true"/> when the status code is a redirect, otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsRedirect(HttpStatusCode statusCode)
|
||||
{
|
||||
return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther
|
||||
or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the location of a redirect against the URI of the request it was returned for.
|
||||
/// </summary>
|
||||
/// <param name="requestUri">The URI of the request the redirect was returned for.</param>
|
||||
/// <param name="location">The location of the redirect.</param>
|
||||
/// <returns>The absolute URI of the redirect, or <see langword="null"/> when it could not be resolved.</returns>
|
||||
private static Uri? ResolveRedirect(Uri requestUri, Uri location)
|
||||
{
|
||||
if (location.IsAbsoluteUri)
|
||||
return location;
|
||||
return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the delay to wait before the next attempt, preferring the delay requested by the Cover Art Archive when it is provided.
|
||||
/// </summary>
|
||||
/// <param name="attempt">The one based number of the attempt that just failed.</param>
|
||||
/// <param name="response">The response of the failed attempt, when the failure was a response rather than a transport exception.</param>
|
||||
/// <returns>The delay to wait before the next attempt.</returns>
|
||||
internal static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response)
|
||||
{
|
||||
// The delay requested by the response is preferred when it is provided, so the rate limit policy of the Cover Art Archive is honored.
|
||||
if (response?.Headers.RetryAfter is { } retryAfter)
|
||||
{
|
||||
TimeSpan? requestedDelay = retryAfter.Delta;
|
||||
if (requestedDelay is null && retryAfter.Date is DateTimeOffset date)
|
||||
{
|
||||
TimeSpan wait = date - DateTimeOffset.UtcNow;
|
||||
if (wait > TimeSpan.Zero)
|
||||
requestedDelay = wait;
|
||||
}
|
||||
if (requestedDelay is TimeSpan delay)
|
||||
{
|
||||
// A misbehaving server could ask for an extremely long delay, which would stall the scan until it is cancelled, so the wait is capped.
|
||||
TimeSpan maximumDelay = TimeSpan.FromSeconds(MAXIMUM_RETRY_DELAY_SECONDS);
|
||||
return delay > maximumDelay ? maximumDelay : delay;
|
||||
}
|
||||
}
|
||||
return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the request headers configured in the <paramref name="settings"/> onto the underlying HTTP client, unless they are already set.
|
||||
/// </summary>
|
||||
/// <param name="settings">The settings that configure the Cover Art Archive API requests.</param>
|
||||
private void EnsureRequestHeaders(CoverArtArchiveSettingsDto settings)
|
||||
{
|
||||
// The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once.
|
||||
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
|
||||
{
|
||||
string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail)
|
||||
? settings.UserAgent
|
||||
: $"{settings.UserAgent} ( {settings.ContactEmail} )";
|
||||
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Class for spacing out the requests sent to the Cover Art Archive API, so the configured minimum request interval is respected across every caller in the process.
|
||||
/// </summary>
|
||||
internal sealed class CoverArtArchiveRequestThrottle
|
||||
{
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
// The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter which caller sends them.
|
||||
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot.
|
||||
/// </summary>
|
||||
/// <param name="minimumRequestInterval">The minimum amount of time that must elapse between two consecutive requests.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that completes once the caller may send its request.</returns>
|
||||
public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken)
|
||||
{
|
||||
// The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the
|
||||
// previous reserved slot.
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it.
|
||||
if (minimumRequestInterval > TimeSpan.Zero)
|
||||
{
|
||||
DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval;
|
||||
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
|
||||
if (delay > TimeSpan.Zero)
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_lastRequestAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// In-memory cache of the responses returned by the Cover Art Archive API, keyed by the requested URL.
|
||||
/// It removes the repeated lookups of the same entity during a run, which is significant because the releases of an edition heavy library share their
|
||||
/// release groups, and it expires its entries after a bounded time.
|
||||
/// </summary>
|
||||
internal sealed class CoverArtArchiveResponseCache
|
||||
{
|
||||
/// <summary>
|
||||
/// The maximum number of responses the cache keeps.
|
||||
/// </summary>
|
||||
internal const int MAXIMUM_ENTRY_COUNT = 20_000;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum total number of characters of the cached response bodies.
|
||||
/// </summary>
|
||||
internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000;
|
||||
|
||||
/// <summary>
|
||||
/// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the
|
||||
/// eviction from running on every write once a budget is reached.
|
||||
/// </summary>
|
||||
private const int TRIM_TARGET_PERCENT = 90;
|
||||
|
||||
private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15);
|
||||
|
||||
private readonly int _maximumEntryCount;
|
||||
private readonly long _maximumCharacterCount;
|
||||
private readonly TimeSpan _timeToLive;
|
||||
private readonly ConcurrentDictionary<string, CacheEntry> _entries = new(StringComparer.Ordinal);
|
||||
|
||||
// The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction
|
||||
// are guarded by a lock, while reads stay lock free.
|
||||
private readonly Lock _sizeGate = new();
|
||||
private long _cachedCharacterCount;
|
||||
|
||||
// Monotonically increasing insertion stamp, used to evict the oldest entries first.
|
||||
private long _sequence;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CoverArtArchiveResponseCache"/> class with the default budgets and time to live.
|
||||
/// </summary>
|
||||
public CoverArtArchiveResponseCache()
|
||||
{
|
||||
_maximumEntryCount = MAXIMUM_ENTRY_COUNT;
|
||||
_maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
|
||||
_timeToLive = s_timeToLive;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CoverArtArchiveResponseCache"/> class with the provided budgets and time to live.
|
||||
/// </summary>
|
||||
/// <param name="maximumEntryCount">The maximum number of responses the cache keeps.</param>
|
||||
/// <param name="maximumCharacterCount">The maximum total number of characters of the cached response bodies.</param>
|
||||
/// <param name="timeToLive">The amount of time a cached response stays valid.</param>
|
||||
internal CoverArtArchiveResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive)
|
||||
{
|
||||
_maximumEntryCount = maximumEntryCount;
|
||||
_maximumCharacterCount = maximumCharacterCount;
|
||||
_timeToLive = timeToLive;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the cached response body for <paramref name="key"/>.
|
||||
/// </summary>
|
||||
/// <param name="key">The key of the cached response.</param>
|
||||
/// <param name="json">The cached response body, when found.</param>
|
||||
/// <returns><see langword="true"/> when an unexpired response was found, otherwise <see langword="false"/>.</returns>
|
||||
public bool TryGet(string key, out string? json)
|
||||
{
|
||||
// An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it.
|
||||
if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow)
|
||||
{
|
||||
json = entry.Json;
|
||||
return true;
|
||||
}
|
||||
json = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds or replaces the cached response body for <paramref name="key"/>, then trims the cache back to its budgets.
|
||||
/// </summary>
|
||||
/// <param name="key">The key of the cached response.</param>
|
||||
/// <param name="json">The response body to cache.</param>
|
||||
public void Set(string key, string json)
|
||||
{
|
||||
// A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache.
|
||||
if (json.Length > _maximumCharacterCount)
|
||||
return;
|
||||
|
||||
lock (_sizeGate)
|
||||
{
|
||||
if (_entries.TryRemove(key, out CacheEntry? existing))
|
||||
_cachedCharacterCount -= existing.Json.Length;
|
||||
|
||||
_entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence);
|
||||
_cachedCharacterCount += json.Length;
|
||||
|
||||
if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount)
|
||||
TrimToBudget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets.
|
||||
/// </summary>
|
||||
private void TrimToBudget()
|
||||
{
|
||||
DateTime utcNow = DateTime.UtcNow;
|
||||
bool isOverEntryCount = _entries.Count > _maximumEntryCount;
|
||||
bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount;
|
||||
int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100);
|
||||
long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100);
|
||||
|
||||
// Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when
|
||||
// a budget was not exceeded, so the cache keeps reclaiming dead entries.
|
||||
foreach (KeyValuePair<string, CacheEntry> candidate in _entries.OrderBy(entry => entry.Value.Sequence))
|
||||
{
|
||||
bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow;
|
||||
bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget;
|
||||
bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget;
|
||||
if (!isExpired && !needsEntryTrim && !needsCharacterTrim)
|
||||
break;
|
||||
|
||||
if (_entries.TryRemove(candidate.Key, out CacheEntry? removed))
|
||||
_cachedCharacterCount -= removed.Json.Length;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#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.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Api;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Mapping;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Provides the artwork of an album from the Cover Art Archive, by resolving the MusicBrainz identifiers of the album into artwork DTOs.
|
||||
/// The artwork of the exact release is preferred, and the artwork of its release group is used when the release itself carries none.
|
||||
/// </summary>
|
||||
internal sealed class CoverArtArchiveAlbumArtworkProvider : IArtworkProvider<AlbumMetadataLookupDto>
|
||||
{
|
||||
private readonly CoverArtArchiveHttpClient _coverArtArchiveHttpClient;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the artwork provider.
|
||||
/// </summary>
|
||||
public string Name => "Cover Art Archive";
|
||||
|
||||
/// <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 => true;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CoverArtArchiveAlbumArtworkProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="coverArtArchiveHttpClient">The HTTP client used to call the Cover Art Archive API.</param>
|
||||
public CoverArtArchiveAlbumArtworkProvider(CoverArtArchiveHttpClient coverArtArchiveHttpClient)
|
||||
{
|
||||
_coverArtArchiveHttpClient = coverArtArchiveHttpClient;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
CoverArtArchiveArtworkResponse? artwork = null;
|
||||
|
||||
// The identifier of the exact release pins the edition the local files match, so its artwork is preferred.
|
||||
if (lookup.MusicBrainzReleaseId is not null)
|
||||
artwork = await _coverArtArchiveHttpClient.GetReleaseArtworkAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// A release can carry no artwork of its own while its release group does, so the release group is the fallback.
|
||||
// The collection is guarded here too, because the deserializer can produce a null collection regardless of the initializer.
|
||||
if ((artwork?.Images is null || artwork.Images.Count == 0) && lookup.MusicBrainzReleaseGroupId is not null)
|
||||
artwork = await _coverArtArchiveHttpClient.GetReleaseGroupArtworkAsync(lookup.MusicBrainzReleaseGroupId.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return CoverArtArchiveMapper.MapArtwork(artwork);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Defines the hosts of the Cover Art Archive and the Internet Archive, which are the only hosts the plugin queries, the only hosts it may follow a
|
||||
/// redirect to, and the only hosts it may fetch artwork from. The Cover Art Archive is not self hostable, so no other host can be a legitimate source.
|
||||
/// </summary>
|
||||
internal static class CoverArtArchiveHosts
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether the provided host is one of the hosts the Cover Art Archive may delegate its responses to.
|
||||
/// </summary>
|
||||
/// <param name="host">The host to check.</param>
|
||||
/// <returns><see langword="true"/> when the host is allowed, otherwise <see langword="false"/>.</returns>
|
||||
public static bool IsAllowed(string host)
|
||||
{
|
||||
return host.Equals("coverartarchive.org", StringComparison.OrdinalIgnoreCase)
|
||||
|| host.EndsWith(".coverartarchive.org", StringComparison.OrdinalIgnoreCase)
|
||||
|| host.Equals("archive.org", StringComparison.OrdinalIgnoreCase)
|
||||
|| host.EndsWith(".archive.org", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
#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.CoverArtArchive.Common.DependencyInjection;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Plugin that provides music album artwork retrieval from the Cover Art Archive.
|
||||
/// </summary>
|
||||
public sealed class CoverArtArchivePlugin : IPlugin, IPluginServiceRegistrator
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public static readonly Guid s_pluginId = new("b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14");
|
||||
|
||||
/// <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 => "Cover Art Archive";
|
||||
|
||||
/// <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 => "Retrieves the cover, back, booklet, medium and other artwork of music albums from the Cover Art Archive.";
|
||||
|
||||
/// <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: CoverArtArchiveSettingsKeys.CONTACT_EMAIL,
|
||||
Label: "Contact Email",
|
||||
Type: PluginSettingType.Text),
|
||||
new PluginSettingDescriptorDto(
|
||||
Key: CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS,
|
||||
Label: "Minimum Request Interval (seconds)",
|
||||
Type: PluginSettingType.Number,
|
||||
DefaultValue: "1.0")
|
||||
];
|
||||
}
|
||||
|
||||
/// <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.AddCoverArtArchiveArtworkProvider(pluginId: Id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core.Mapping;
|
||||
|
||||
/// <summary>
|
||||
/// Maps the responses of the Cover Art Archive API into artwork DTOs.
|
||||
/// </summary>
|
||||
internal static class CoverArtArchiveMapper
|
||||
{
|
||||
/// <summary>
|
||||
/// Maps the artwork carried by <paramref name="response"/> into artwork DTOs, one for every type each image is tagged with.
|
||||
/// </summary>
|
||||
/// <param name="response">The artwork response to map.</param>
|
||||
/// <returns>The mapped artworks, ordered as they appear in the response, or an empty collection when there is no artwork.</returns>
|
||||
public static IReadOnlyList<ArtworkDto> MapArtwork(CoverArtArchiveArtworkResponse? response)
|
||||
{
|
||||
// The collection and its elements are guarded, because the deserializer can produce a null collection, or null elements, regardless of the initializers.
|
||||
if (response?.Images is null)
|
||||
return [];
|
||||
|
||||
List<ArtworkDto> artworks = [];
|
||||
// The ordinals are tracked per type, so that multiple images of the same type, like the pages of a booklet, are ordered among themselves.
|
||||
Dictionary<ArtworkType, int> nextOrdinals = [];
|
||||
foreach (CoverArtArchiveImageResponse? image in response.Images)
|
||||
{
|
||||
if (image is null || !TryResolveArtworkUrl(image.Image, out string artworkUrl))
|
||||
continue;
|
||||
|
||||
foreach (ArtworkType artworkType in ResolveArtworkTypes(image))
|
||||
{
|
||||
int ordinal = nextOrdinals.TryGetValue(artworkType, out int nextOrdinal) ? nextOrdinal : 0;
|
||||
nextOrdinals[artworkType] = ordinal + 1;
|
||||
artworks.Add(new ArtworkDto(artworkType, ordinal, LocalPath: null, RemoteUrl: artworkUrl));
|
||||
}
|
||||
}
|
||||
return artworks;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the URL of an artwork image, keeping it only when it points, over an encrypted connection, at a host the Cover Art Archive may serve
|
||||
/// artwork from. An image URL of any other shape or host is dropped, so a compromised response cannot make the host download from an internal address.
|
||||
/// </summary>
|
||||
/// <param name="candidate">The image URL carried by the response.</param>
|
||||
/// <param name="artworkUrl">The resolved, encrypted image URL, when it is usable.</param>
|
||||
/// <returns><see langword="true"/> when the image URL is usable, otherwise <see langword="false"/>.</returns>
|
||||
private static bool TryResolveArtworkUrl(string? candidate, out string artworkUrl)
|
||||
{
|
||||
artworkUrl = string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(candidate))
|
||||
return false;
|
||||
|
||||
if (!Uri.TryCreate(candidate.Trim(), UriKind.Absolute, out Uri? uri) || !CoverArtArchiveHosts.IsAllowed(uri.Host))
|
||||
return false;
|
||||
|
||||
// The artwork is always fetched over an encrypted connection, so a plain HTTP reference to a trusted host is upgraded to HTTPS,
|
||||
// and a reference that uses any other scheme is dropped.
|
||||
if (uri.Scheme == Uri.UriSchemeHttps)
|
||||
artworkUrl = uri.AbsoluteUri;
|
||||
else if (uri.Scheme == Uri.UriSchemeHttp)
|
||||
artworkUrl = new UriBuilder(uri) { Scheme = Uri.UriSchemeHttps, Port = -1 }.Uri.AbsoluteUri;
|
||||
else
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork types an image is tagged with, falling back to the front and back flags when the image carries no type.
|
||||
/// </summary>
|
||||
/// <param name="image">The image whose types are resolved.</param>
|
||||
/// <returns>The distinct artwork types of the image, in the order they appear in the response.</returns>
|
||||
private static List<ArtworkType> ResolveArtworkTypes(CoverArtArchiveImageResponse image)
|
||||
{
|
||||
// A list de-duplicated on insertion keeps the order of the response, unlike a set, whose iteration order is not deterministic.
|
||||
List<ArtworkType> artworkTypes = [];
|
||||
// The collection and its elements are guarded, because the deserializer can produce a null collection, or null elements, regardless of the initializers.
|
||||
foreach (string? type in image.Types ?? [])
|
||||
if (TryMapArtworkType(type, out ArtworkType artworkType) && !artworkTypes.Contains(artworkType))
|
||||
artworkTypes.Add(artworkType);
|
||||
|
||||
// An image that carries no known type still describes the front or the back of the release when it is flagged as such.
|
||||
if (artworkTypes.Count == 0)
|
||||
{
|
||||
if (image.IsFront)
|
||||
artworkTypes.Add(ArtworkType.Cover);
|
||||
if (image.IsBack)
|
||||
artworkTypes.Add(ArtworkType.Back);
|
||||
}
|
||||
return artworkTypes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a Cover Art Archive image type onto an artwork type.
|
||||
/// </summary>
|
||||
/// <param name="type">The Cover Art Archive image type.</param>
|
||||
/// <param name="artworkType">The mapped artwork type, when the type is recognized.</param>
|
||||
/// <returns><see langword="true"/> when the type was recognized, otherwise <see langword="false"/>.</returns>
|
||||
private static bool TryMapArtworkType(string? type, out ArtworkType artworkType)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(type))
|
||||
{
|
||||
artworkType = ArtworkType.Other;
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (type.Trim().ToLowerInvariant())
|
||||
{
|
||||
case "front":
|
||||
artworkType = ArtworkType.Cover;
|
||||
return true;
|
||||
case "back":
|
||||
artworkType = ArtworkType.Back;
|
||||
return true;
|
||||
case "booklet":
|
||||
artworkType = ArtworkType.Booklet;
|
||||
return true;
|
||||
case "medium":
|
||||
artworkType = ArtworkType.Medium;
|
||||
return true;
|
||||
case "tray":
|
||||
artworkType = ArtworkType.Tray;
|
||||
return true;
|
||||
case "spine":
|
||||
artworkType = ArtworkType.Spine;
|
||||
return true;
|
||||
case "obi":
|
||||
artworkType = ArtworkType.Obi;
|
||||
return true;
|
||||
case "sticker":
|
||||
artworkType = ArtworkType.Sticker;
|
||||
return true;
|
||||
case "poster":
|
||||
artworkType = ArtworkType.Poster;
|
||||
return true;
|
||||
case "liner":
|
||||
artworkType = ArtworkType.Liner;
|
||||
return true;
|
||||
case "watermark":
|
||||
artworkType = ArtworkType.Watermark;
|
||||
return true;
|
||||
default:
|
||||
// The Cover Art Archive also uses a free form "Other" type and may add new types over time, which are all kept as generic artwork.
|
||||
artworkType = ArtworkType.Other;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Keys of the settings of the Cover Art Archive artwork plugin, shared by the settings schema and the settings loader.
|
||||
/// </summary>
|
||||
internal static class CoverArtArchiveSettingsKeys
|
||||
{
|
||||
/// <summary>
|
||||
/// The key of the setting defining the contact email sent to the Cover Art Archive API.
|
||||
/// </summary>
|
||||
internal const string CONTACT_EMAIL = "ContactEmail";
|
||||
|
||||
/// <summary>
|
||||
/// The key of the setting defining the minimum interval between consecutive requests to the Cover Art Archive API, in seconds.
|
||||
/// </summary>
|
||||
internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds";
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Core.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Provides the runtime settings of the Cover Art Archive artwork plugin, overlaying the settings persisted by the host over the configured defaults.
|
||||
/// </summary>
|
||||
internal sealed class CoverArtArchiveSettingsProvider
|
||||
{
|
||||
// The minimum request interval is clamped to a sane range, so a persisted value can neither be a non finite value that cannot be turned into a
|
||||
// duration, nor be so large that waiting for it overflows the delay of the requests.
|
||||
private const double MAXIMUM_REQUEST_INTERVAL_SECONDS = 60;
|
||||
|
||||
private readonly IPluginSettingsStore? _settingsStore;
|
||||
private readonly Guid _pluginId;
|
||||
private readonly CoverArtArchiveSettingsDto _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 CoverArtArchiveSettingsDto? _runtimeSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CoverArtArchiveSettingsProvider"/> 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 CoverArtArchiveSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, CoverArtArchiveSettingsDto 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<CoverArtArchiveSettingsDto> GetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact.
|
||||
CoverArtArchiveSettingsDto? 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)
|
||||
{
|
||||
runtimeSettings = await ResolveAsync(cancellationToken).ConfigureAwait(false);
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the runtime settings by overlaying the settings persisted by the host over the configured defaults.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The runtime settings of the plugin.</returns>
|
||||
private async Task<CoverArtArchiveSettingsDto> ResolveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes.
|
||||
CoverArtArchiveSettingsDto runtimeSettings = new()
|
||||
{
|
||||
UserAgent = _defaults.UserAgent,
|
||||
ContactEmail = _defaults.ContactEmail,
|
||||
MinimumRequestInterval = _defaults.MinimumRequestInterval
|
||||
};
|
||||
|
||||
if (_settingsStore is null)
|
||||
return runtimeSettings;
|
||||
|
||||
IReadOnlyDictionary<string, string>? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (storedSettings is null)
|
||||
return runtimeSettings;
|
||||
|
||||
if (storedSettings.TryGetValue(CoverArtArchiveSettingsKeys.CONTACT_EMAIL, out string? contactEmail))
|
||||
{
|
||||
string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim();
|
||||
runtimeSettings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null;
|
||||
}
|
||||
|
||||
// A persisted value that is not a finite number is rejected, and a finite one is clamped, so that neither a NaN, nor an infinity, nor an
|
||||
// out of range value can make the conversion to a duration or the waiting for it throw.
|
||||
if (storedSettings.TryGetValue(CoverArtArchiveSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) &&
|
||||
double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue) &&
|
||||
double.IsFinite(minimumRequestIntervalValue))
|
||||
runtimeSettings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Clamp(minimumRequestIntervalValue, 0, MAXIMUM_REQUEST_INTERVAL_SECONDS));
|
||||
|
||||
return runtimeSettings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header.
|
||||
/// </summary>
|
||||
/// <param name="contactEmail">The persisted contact email.</param>
|
||||
/// <returns><see langword="true"/> when the email is safe, otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsSafeContactEmail(string contactEmail)
|
||||
{
|
||||
// The email is embedded in the User-Agent header, and an invalid character there throws when the header is parsed, which would break every request of the plugin,
|
||||
// so, anything outside a conservative email charset is rejected.
|
||||
foreach (char character in contactEmail)
|
||||
if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+'))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<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>
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.UnitTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.SecurityTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.CoverArtArchive.Fixtures")]
|
||||
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
|
||||
Reference in new issue
Block a user