Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,437 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Common.Http;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models.
/// </summary>
internal sealed class MusicBrainzHttpClient
{
private readonly HttpClient _httpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
private readonly MusicBrainzRequestThrottle _requestThrottle;
private readonly MusicBrainzResponseCache _responseCache;
private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web)
{
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
// 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 = 4;
// The redirects of a self hosted mirror are followed explicitly, so the host redirect policy can be opted out of and only the same host can be reached.
private const int MAXIMUM_REDIRECT_COUNT = 5;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzHttpClient"/> class.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
/// <param name="requestThrottle">The process-wide throttle that spaces out the requests sent to the MusicBrainz web service.</param>
/// <param name="responseCache">The process-wide cache that avoids fetching the same entity more than once during a run.</param>
public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache)
{
_httpClient = httpClient;
_settingsProvider = settingsProvider;
_requestThrottle = requestThrottle;
_responseCache = responseCache;
}
/// <summary>
/// Looks up the artist identified by <paramref name="musicBrainzArtistId"/>.
/// </summary>
/// <param name="musicBrainzArtistId">The MusicBrainz identifier of the artist.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artist, or <see langword="null"/> when no artist was found.</returns>
public Task<MusicBrainzArtistResponse?> GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzArtistResponse>(
$"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for artists matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching artists.</returns>
public async Task<IReadOnlyList<MusicBrainzArtistResponse>> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzArtistSearchResponse>(
$"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Artists ?? [];
}
/// <summary>
/// Looks up 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 release group, or <see langword="null"/> when no release group was found.</returns>
public Task<MusicBrainzReleaseGroupResponse?> GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseGroupResponse>(
$"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for release groups matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching release groups.</returns>
public async Task<IReadOnlyList<MusicBrainzReleaseGroupResponse>> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseGroupSearchResponse>(
$"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.ReleaseGroups ?? [];
}
/// <summary>
/// Looks up 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 release, or <see langword="null"/> when no release was found.</returns>
public Task<MusicBrainzReleaseResponse?> GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
$"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken);
}
/// <summary>
/// Browses the releases that belong to the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
/// </summary>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="limit">The maximum number of releases to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of releases of the release group.</returns>
public async Task<IReadOnlyList<MusicBrainzReleaseResponse>> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken)
{
MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseBrowseResponse>(
$"release?release-group={musicBrainzReleaseGroupId:D}&inc=artist-credits+labels+media&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Releases ?? [];
}
/// <summary>
/// Looks up the recording identified by <paramref name="musicBrainzRecordingId"/>.
/// </summary>
/// <param name="musicBrainzRecordingId">The MusicBrainz identifier of the recording.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The recording, or <see langword="null"/> when no recording was found.</returns>
public Task<MusicBrainzRecordingResponse?> GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzRecordingResponse>(
$"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for recordings matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching recordings.</returns>
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingSearchResponse>(
$"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Recordings ?? [];
}
/// <summary>
/// Looks up the recordings that carry the provided ISRC.
/// </summary>
/// <param name="isrc">The ISRC to look up.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of recordings that carry the ISRC.</returns>
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken)
{
MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingListResponse>(
$"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false);
return response?.Recordings ?? [];
}
/// <summary>
/// Looks up the work identified by <paramref name="musicBrainzWorkId"/>, together with its credited contributors.
/// </summary>
/// <param name="musicBrainzWorkId">The MusicBrainz identifier of the work.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The work, or <see langword="null"/> when no work was found.</returns>
public Task<MusicBrainzWorkResponse?> GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzWorkResponse>(
$"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken);
}
/// <summary>
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>, together with its media, tracks, recordings and all the data needed
/// to enrich those tracks, so that every track of the release is enriched from a single request.
/// </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 release, with its media, tracks and recordings, or <see langword="null"/> when no release was found.</returns>
public Task<MusicBrainzReleaseResponse?> GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
$"release/{musicBrainzReleaseId:D}?inc=recordings+isrcs+artist-credits+tags+genres+ratings+work-rels+recording-level-rels+work-level-rels+artist-rels+release-groups+labels+media&fmt=json", 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>
/// <remarks>Transient failures and rate limiting are handled by retrying the request up to three times.</remarks>
private async Task<TModel?> GetJsonOrNullAsync<TModel>(string relativeUrl, CancellationToken cancellationToken)
{
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
string cacheKey = string.Concat(settings.BaseUrl, relativeUrl);
if (_responseCache.TryGet(cacheKey, out string? cachedJson) && cachedJson is not null)
return JsonSerializer.Deserialize<TModel>(cachedJson, s_serializerOptions);
using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false);
// A 404 means the entity does not exist in MusicBrainz, which is a normal miss rather than an error, so it is reported as no result.
if (response.StatusCode == HttpStatusCode.NotFound)
return default;
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
_responseCache.Set(cacheKey, json);
return JsonSerializer.Deserialize<TModel>(json, s_serializerOptions);
}
/// <summary>
/// Sends a GET request to the MusicBrainz web service, following its redirects explicitly so they are confined to the configured host, and throttled to
/// respect the configured minimum request interval unless the configured base URL is not the real MusicBrainz service, in which case no rate limit is imposed.
/// Transient failures, rate limiting and transport exceptions are retried, preferring the delay requested by the web service when it is provided.
/// </summary>
/// <param name="settings">The settings that configure the MusicBrainz web service 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>
/// <exception cref="HttpRequestException">The service redirected the request to a host or a scheme that is not allowed, or too many times.</exception>
private async Task<HttpResponseMessage> SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken)
{
Uri baseUri = new(settings.BaseUrl, UriKind.Absolute);
// The permission to reach a private address is scoped to the host of the configured base URL, so a mirror cannot redirect the request to another
// private host, and the link local and cloud metadata ranges stay blocked even when the permission is granted.
string? allowedPrivateHost = settings.DoesAllowPrivateBaseUrl ? baseUri.IdnHost : null;
Uri requestUri = BuildRequestUri(settings.BaseUrl, relativeUrl);
for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++)
{
HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, allowedPrivateHost, 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 is followed only to the configured host, and never from HTTPS to HTTP, so a compromised or misbehaving mirror cannot redirect the
// request to any other host, while a plain HTTP self hosted mirror keeps working across the redirects of its reverse proxy.
if (redirectUri is null || !IsAllowedRedirect(baseUri, redirectUri))
throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "The MusicBrainz service redirected the request to a disallowed target.");
requestUri = redirectUri;
}
throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "The MusicBrainz service redirected the request too many times.");
}
/// <summary>
/// Sends a GET request to the provided URI, 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 MusicBrainz web service requests.</param>
/// <param name="requestUri">The absolute URI of the resource to request.</param>
/// <param name="allowedPrivateHost">The host that may be private, or <see langword="null"/> when no such permission was granted.</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(MusicBrainzSettingsDto settings, Uri requestUri, string? allowedPrivateHost, CancellationToken cancellationToken)
{
EnsureRequestHeaders(settings);
// The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted
// mirror, or any other configured base URL that is not the real service, is not limited by this process.
bool shouldThrottle = IsRealMusicBrainzService(settings.BaseUrl);
// 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 real MusicBrainz web service.
for (int attempt = 1; ; attempt++)
{
if (shouldThrottle)
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"));
// The client follows the redirects itself, confined to the configured host, so it opts out of the host redirect handling.
request.Options.Set(OutboundRequestOptions.FollowRedirects, false);
if (allowedPrivateHost is not null && string.Equals(requestUri.IdnHost, allowedPrivateHost, StringComparison.OrdinalIgnoreCase))
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, allowedPrivateHost);
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
}
catch (HttpRequestException exception) when (!isLastAttempt && !IsPolicyRejection(exception))
{
// A rejection by the host outbound address policy is deterministic and is reported as ConfigurationLimitExceeded, so it is not retried.
await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
continue;
}
if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500))
{
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>
/// Determines whether the provided redirect target may be followed: it must stay on the host of the configured base address, and it may not downgrade an HTTPS base address to plain HTTP.
/// </summary>
/// <param name="baseUri">The URI of the configured base address.</param>
/// <param name="redirectUri">The URI of the redirect target.</param>
/// <returns><see langword="true"/> when the redirect may be followed, otherwise <see langword="false"/>.</returns>
private static bool IsAllowedRedirect(Uri baseUri, Uri redirectUri)
{
bool isSchemeAllowed = redirectUri.Scheme == Uri.UriSchemeHttps || (baseUri.Scheme == Uri.UriSchemeHttp && redirectUri.Scheme == Uri.UriSchemeHttp);
return isSchemeAllowed && string.Equals(baseUri.IdnHost, redirectUri.IdnHost, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service 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>
private static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response)
{
if (response?.Headers.RetryAfter is { } retryAfter)
{
if (retryAfter.Delta is TimeSpan delta)
return delta;
if (retryAfter.Date is DateTimeOffset date)
{
TimeSpan wait = date - DateTimeOffset.UtcNow;
if (wait > TimeSpan.Zero)
return wait;
}
}
return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
}
/// <summary>
/// Determines whether the provided exception, or one of its inner exceptions, reports a rejection by the host outbound address policy.
/// </summary>
/// <param name="exception">The exception to inspect.</param>
/// <returns><see langword="true"/> when the exception chain contains a policy rejection, otherwise <see langword="false"/>.</returns>
/// <remarks>
/// SocketsHttpHandler wraps an exception thrown by the connect callback in an HttpRequestException with the ConnectionError error, so the policy rejection is only visible on the inner exception.
/// </remarks>
private static bool IsPolicyRejection(HttpRequestException exception)
{
for (Exception? currentException = exception; currentException is not null; currentException = currentException.InnerException)
if (currentException is HttpRequestException httpRequestException && httpRequestException.HttpRequestError == HttpRequestError.ConfigurationLimitExceeded)
return true;
return false;
}
/// <summary>
/// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
/// <returns><see langword="true"/> when the base URL points to the real MusicBrainz web service, otherwise <see langword="false"/>.</returns>
private static bool IsRealMusicBrainzService(string baseUrl)
{
if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out Uri? baseUri))
return false;
return baseUri.Host.Equals("musicbrainz.org", StringComparison.OrdinalIgnoreCase)
|| baseUri.Host.EndsWith(".musicbrainz.org", StringComparison.OrdinalIgnoreCase);
}
/// <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 MusicBrainz web service requests.</param>
private void EnsureRequestHeaders(MusicBrainzSettingsDto 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);
}
}
/// <summary>
/// Combines the configured base URL with the given relative URL into the absolute URI of a request.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
/// <param name="relativeUrl">The URL of the resource, relative to the base URL.</param>
/// <returns>The absolute URI of the request.</returns>
private static Uri BuildRequestUri(string baseUrl, string relativeUrl)
{
string normalizedBaseUrl = baseUrl.EndsWith('/') ? baseUrl : string.Concat(baseUrl, "/");
return new Uri(new Uri(normalizedBaseUrl, UriKind.Absolute), relativeUrl);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// Spaces out the requests sent to the MusicBrainz web service, so the configured minimum request interval is respected across every caller in the process.
/// </summary>
internal sealed class MusicBrainzRequestThrottle
{
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,140 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// In-memory cache of the responses returned by the MusicBrainz web service, keyed by the requested URL.
/// It removes the repeated lookups of the same entity during a run, and expires its entries after a bounded time.
/// </summary>
internal sealed class MusicBrainzResponseCache
{
/// <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="MusicBrainzResponseCache"/> class with the default budgets and time to live.
/// </summary>
public MusicBrainzResponseCache()
{
_maximumEntryCount = MAXIMUM_ENTRY_COUNT;
_maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
_timeToLive = s_timeToLive;
}
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> 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 MusicBrainzResponseCache(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,760 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Mapping;
/// <summary>
/// Maps MusicBrainz web service responses into the application's media metadata DTOs.
/// </summary>
internal static partial class MusicBrainzMapper
{
/// <summary>
/// The neutral cultures of the process, indexed by both their two letter and three letter ISO 639 codes.
/// Built once, because the available cultures do not change during the lifetime of the process.
/// </summary>
private static readonly IReadOnlyDictionary<string, CultureInfo> s_neutralCulturesByCode = BuildNeutralCultureLookup();
/// <summary>
/// Matches a four digit year.
/// </summary>
[GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")]
private static partial Regex YearPattern();
/// <summary>
/// Maps a MusicBrainz artist response into artist metadata.
/// </summary>
/// <param name="artist">The artist response to map.</param>
/// <returns>The mapped artist metadata.</returns>
public static ArtistMetadataDto MapArtist(MusicBrainzArtistResponse artist)
{
(List<MediaContributorDto> contributors, string? website) = MapArtistRelations(artist.Relations);
return new ArtistMetadataDto(
Name: NullIfWhiteSpace(artist.Name),
SortName: NullIfWhiteSpace(artist.SortName),
Disambiguation: NullIfWhiteSpace(artist.Disambiguation),
Type: MapArtistType(artist.Type),
Gender: MapArtistGender(artist.Gender),
Country: NullIfWhiteSpace(artist.Country),
Area: MapArea(artist.Area),
BeginArea: MapArea(artist.BeginArea),
EndArea: MapArea(artist.EndArea),
LifeSpanBegin: ParseDate(artist.LifeSpan?.Begin).Date,
LifeSpanEnd: ParseDate(artist.LifeSpan?.End).Date,
IsEnded: artist.LifeSpan?.IsEnded ?? false,
Website: website,
MusicBrainzArtistId: ParseGuid(artist.Id),
Ipis: [.. artist.Ipis.Where(ipi => !string.IsNullOrWhiteSpace(ipi))],
Isnis: [.. artist.Isnis.Where(isni => !string.IsNullOrWhiteSpace(isni))],
Aliases: [.. artist.Aliases.Select(MapAlias)],
Genres: MapGenres(artist.Genres),
Tags: MapTags(artist.Tags),
Ratings: MapRating(artist.Rating),
Contributors: contributors);
}
/// <summary>
/// Maps a MusicBrainz release group, and optionally one of its releases, into album metadata.
/// </summary>
/// <param name="releaseGroup">The release group response to map.</param>
/// <param name="release">The selected release of the release group, or <see langword="null"/> when no release was selected.</param>
/// <returns>The mapped album metadata.</returns>
public static AlbumMetadataDto MapAlbum(MusicBrainzReleaseGroupResponse releaseGroup, MusicBrainzReleaseResponse? release)
{
(DateOnly? originalDate, int? originalYear) = ParseDate(releaseGroup.FirstReleaseDate);
(DateOnly? reReleaseDate, int? reReleaseYear) = ParseDate(release?.Date);
if (reReleaseDate is not null && originalDate is not null && reReleaseDate.Value.Year == originalDate.Value.Year)
{
reReleaseDate = null;
reReleaseYear = null;
}
string? releaseArtistId = releaseGroup.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id))
?? release?.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
List<MediaContributorDto> contributors = MapArtistCredit(releaseGroup.ArtistCredit);
if (contributors.Count == 0 && release is not null)
contributors = MapArtistCredit(release.ArtistCredit);
if (release is not null)
AddContributors(contributors, MapContributorsFromRelations(release.Relations));
List<MusicBrainzMediumResponse> media = release?.Media ?? [];
int totalTracks = media.Sum(medium => medium.TrackCount);
// A MusicBrainz release can carry several labels and catalog numbers: the label stores the first one, while every catalog number is kept.
string? label = release?.LabelInfo.FirstOrDefault()?.Label?.Name;
List<string> catalogNumbers = [.. (release?.LabelInfo ?? [])
.Select(labelInfo => NullIfWhiteSpace(labelInfo.CatalogNumber))
.Where(catalogNumber => catalogNumber is not null)
.Select(catalogNumber => catalogNumber!)
.Distinct(StringComparer.OrdinalIgnoreCase)];
return new AlbumMetadataDto(
Title: NullIfWhiteSpace(releaseGroup.Title) ?? NullIfWhiteSpace(release?.Title),
OriginalTitle: null,
Description: null,
Disambiguation: NullIfWhiteSpace(releaseGroup.Disambiguation),
ReleaseInfo: new ReleaseInfoDto(
OriginalReleaseDate: originalDate,
OriginalReleaseYear: originalYear,
ReReleaseDate: reReleaseDate,
ReReleaseYear: reReleaseYear,
ReleaseCountry: MapReleaseCountry(release?.Country),
ReleaseVersion: NullIfWhiteSpace(release?.Disambiguation)),
Language: MapLanguage(release?.TextRepresentation?.Language),
OriginalLanguage: null,
Tags: MapTags(releaseGroup.Tags),
Genres: MapGenres(releaseGroup.Genres),
Script: NullIfWhiteSpace(release?.TextRepresentation?.Script),
ReleaseTypes: MapReleaseTypes(releaseGroup.PrimaryType, releaseGroup.SecondaryTypes),
ReleaseStatus: MapReleaseStatus(release?.Status),
MediaFormat: MapMediaFormat(media.FirstOrDefault()?.Format),
Packaging: MapPackaging(release?.Packaging),
TotalDiscs: media.Count > 0 ? media.Count : null,
TotalTracks: totalTracks > 0 ? totalTracks : null,
Barcode: NullIfWhiteSpace(release?.Barcode),
CatalogNumbers: catalogNumbers,
Label: NullIfWhiteSpace(label),
ASIN: NullIfWhiteSpace(release?.Asin),
MusicBrainzReleaseId: ParseGuid(release?.Id),
MusicBrainzReleaseGroupId: ParseGuid(releaseGroup.Id),
MusicBrainzReleaseArtistId: ParseGuid(releaseArtistId),
Contributors: contributors,
Ratings: MapRating(releaseGroup.Rating),
ReleaseTitle: NullIfWhiteSpace(release?.Title));
}
/// <summary>
/// Maps a MusicBrainz recording, and optionally its work and release, into track metadata.
/// </summary>
/// <param name="recording">The recording response to map.</param>
/// <param name="work">The work the recording is an instance of, or <see langword="null"/> when the recording has no work.</param>
/// <param name="release">The release the recording appears on, or <see langword="null"/> when it is not known.</param>
/// <returns>The mapped track metadata.</returns>
public static AudioMetadataDto MapTrack(MusicBrainzRecordingResponse recording, MusicBrainzWorkResponse? work, MusicBrainzReleaseResponse? release)
{
(DateOnly? releaseDate, int? releaseYear) = ParseDate(recording.FirstReleaseDate);
// A recording embedded in a release lookup does not carry its own first release date, so the date of the release the track appears on is used
// instead, rather than leaving the track without any release date at all.
if (releaseYear is null)
(releaseDate, releaseYear) = ParseDate(release?.Date);
List<MediaContributorDto> contributors = MapArtistCredit(recording.ArtistCredit);
AddContributors(contributors, MapContributorsFromRelations(recording.Relations));
if (work is not null)
AddContributors(contributors, MapContributorsFromRelations(work.Relations));
return new AudioMetadataDto(
Title: NullIfWhiteSpace(recording.Title),
OriginalTitle: null,
Description: null,
Disambiguation: NullIfWhiteSpace(recording.Disambiguation),
ReleaseInfo: new ReleaseInfoDto(
OriginalReleaseDate: releaseDate,
OriginalReleaseYear: releaseYear,
ReReleaseDate: null,
ReReleaseYear: null,
ReleaseCountry: null,
ReleaseVersion: null),
Language: MapLanguage(release?.TextRepresentation?.Language),
OriginalLanguage: null,
Tags: MapTags(recording.Tags),
Genres: MapGenres(recording.Genres),
Script: NullIfWhiteSpace(release?.TextRepresentation?.Script),
Key: null,
Bpm: null,
IsVideo: recording.IsVideo ?? false,
Work: work is null ? null : MapWork(work),
Isrcs: [.. recording.Isrcs.Where(isrc => !string.IsNullOrWhiteSpace(isrc)).Select(isrc => new IsrcDto(isrc))],
Moods: null,
DurationInSeconds: recording.Length is long length && length > 0 ? (int)(length / 1000) : null,
SampleRate: null,
Channels: null,
BitDepth: null,
AudioCodec: null,
Container: null,
Bitrate: null,
MusicBrainzRecordingId: ParseGuid(recording.Id),
MusicBrainzTrackId: null,
Contributors: contributors,
Ratings: MapRating(recording.Rating));
}
/// <summary>
/// Maps a MusicBrainz work into a work DTO.
/// </summary>
/// <param name="work">The work response to map.</param>
/// <returns>The mapped work.</returns>
public static MusicWorkDto MapWork(MusicBrainzWorkResponse work)
{
return new MusicWorkDto(
MusicBrainzWorkId: ParseGuid(work.Id),
Title: NullIfWhiteSpace(work.Title),
Type: NullIfWhiteSpace(work.Type),
Languages: [.. work.Languages.Select(MapLanguage).Where(language => language is not null).Select(language => language!)],
Iswcs: [.. work.Iswcs.Where(iswc => !string.IsNullOrWhiteSpace(iswc))]);
}
/// <summary>
/// Maps a MusicBrainz area into an area DTO.
/// </summary>
/// <param name="area">The area response to map.</param>
/// <returns>The mapped area, or <see langword="null"/> when no area is provided.</returns>
public static MusicAreaDto? MapArea(MusicBrainzAreaResponse? area)
{
if (area is null)
return null;
string? isoCode = area.Iso3166Part1Codes.FirstOrDefault() ?? area.Iso3166Part2Codes.FirstOrDefault();
return new MusicAreaDto(
MusicBrainzAreaId: ParseGuid(area.Id),
Name: NullIfWhiteSpace(area.Name),
SortName: NullIfWhiteSpace(area.SortName),
Disambiguation: NullIfWhiteSpace(area.Disambiguation),
Type: NullIfWhiteSpace(area.Type),
Iso3166Code: NullIfWhiteSpace(isoCode));
}
/// <summary>
/// Maps a MusicBrainz alias into an alias DTO.
/// </summary>
/// <param name="alias">The alias response to map.</param>
/// <returns>The mapped alias.</returns>
private static MusicArtistAliasDto MapAlias(MusicBrainzAliasResponse alias)
{
return new MusicArtistAliasDto(
Name: NullIfWhiteSpace(alias.Name),
SortName: NullIfWhiteSpace(alias.SortName),
Type: NullIfWhiteSpace(alias.Type),
Locale: NullIfWhiteSpace(alias.Locale),
IsPrimary: alias.IsPrimary ?? false,
BeginDate: ParseDate(alias.Begin).Date,
EndDate: ParseDate(alias.End).Date,
IsEnded: alias.IsEnded ?? false);
}
/// <summary>
/// Maps the genres of a MusicBrainz entity into genre DTOs.
/// </summary>
/// <param name="genres">The genre responses to map.</param>
/// <returns>The mapped genre DTOs.</returns>
private static List<GenreDto> MapGenres(IReadOnlyCollection<MusicBrainzTagResponse> genres)
{
return [.. genres
.Where(genre => !string.IsNullOrWhiteSpace(genre.Name))
.Select(genre => new GenreDto(genre.Name))
.DistinctBy(genre => genre.Name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Maps the tags of a MusicBrainz entity into tag DTOs.
/// </summary>
/// <param name="tags">The tag responses to map.</param>
/// <returns>The mapped tag DTOs.</returns>
private static List<TagDto> MapTags(IReadOnlyCollection<MusicBrainzTagResponse> tags)
{
return [.. tags
.Where(tag => !string.IsNullOrWhiteSpace(tag.Name))
.Select(tag => new TagDto(tag.Name))
.DistinctBy(tag => tag.Name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Maps the rating of a MusicBrainz entity into a rating DTO.
/// </summary>
/// <param name="rating">The rating response to map.</param>
/// <returns>The mapped rating DTO, or an empty list when no rating is provided.</returns>
private static List<AudioRatingDto> MapRating(MusicBrainzRatingResponse? rating)
{
if (rating is null || (rating.Value is null && rating.VotesCount is null))
return [];
return [new AudioRatingDto(rating.Value, 5m, AudioRatingSource.MusicBrainz, rating.VotesCount)];
}
/// <summary>
/// Maps an ISO 639-3 language code into a language DTO.
/// </summary>
/// <param name="rawCode">The code to map.</param>
/// <returns>The mapped language, or <see langword="null"/> when the code is empty.</returns>
private static LanguageInfoDto? MapLanguage(string? rawCode)
{
if (string.IsNullOrWhiteSpace(rawCode))
return null;
string code = rawCode.Trim().ToLowerInvariant();
// A language code can list several languages, such as "eng/ara"; the first one is the language of the release.
string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code;
// These ISO 639-3 codes describe a language absence rather than a culture, so they cannot be resolved through a culture.
switch (primaryCode)
{
case "zxx":
return new LanguageInfoDto(primaryCode, "No linguistic content", null);
case "mul":
return new LanguageInfoDto(primaryCode, "Multiple languages", null);
case "und":
return new LanguageInfoDto(primaryCode, "Undetermined", null);
default:
break;
}
// Only neutral cultures are matched, because a specific culture would resolve to an arbitrary regional name such as "German (Austria)".
return s_neutralCulturesByCode.TryGetValue(primaryCode, out CultureInfo? culture)
? new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName)
: new LanguageInfoDto(primaryCode, primaryCode, null);
}
/// <summary>
/// Builds the lookup of the process' neutral cultures, indexed by both their two letter and three letter ISO 639 codes.
/// </summary>
/// <returns>The neutral cultures, indexed by their ISO 639 codes.</returns>
private static IReadOnlyDictionary<string, CultureInfo> BuildNeutralCultureLookup()
{
Dictionary<string, CultureInfo> culturesByCode = new(StringComparer.OrdinalIgnoreCase);
foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
{
// A culture without a two letter ISO 639 code is not a language, so it is skipped; the two letter code is the one carried by the DTOs.
if (culture.TwoLetterISOLanguageName.Length != 2)
continue;
culturesByCode.TryAdd(culture.ThreeLetterISOLanguageName, culture);
culturesByCode.TryAdd(culture.TwoLetterISOLanguageName, culture);
}
return culturesByCode;
}
/// <summary>
/// Maps the artist credit of a MusicBrainz entity into attributed performing contributors.
/// </summary>
/// <param name="artistCredit">The artist credit to map.</param>
/// <returns>The mapped contributors.</returns>
private static List<MediaContributorDto> MapArtistCredit(IReadOnlyCollection<MusicBrainzArtistCreditResponse> artistCredit)
{
List<MediaContributorDto> contributors = [];
foreach (MusicBrainzArtistCreditResponse credit in artistCredit)
{
string? name = NullIfWhiteSpace(credit.Name) ?? NullIfWhiteSpace(credit.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MediaContributorRole.Performer);
}
return contributors;
}
/// <summary>
/// Maps the artist relations of a MusicBrainz entity into contributors, excluding the URL relations.
/// </summary>
/// <param name="relations">The relations to map.</param>
/// <returns>The mapped contributors.</returns>
private static List<MediaContributorDto> MapContributorsFromRelations(IReadOnlyCollection<MusicBrainzRelationResponse> relations)
{
List<MediaContributorDto> contributors = [];
foreach (MusicBrainzRelationResponse relation in relations)
{
if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase))
continue;
string? name = NullIfWhiteSpace(relation.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes));
}
return contributors;
}
/// <summary>
/// Maps the relations of an artist into its contributing members, and its official homepage.
/// </summary>
/// <param name="relations">The relations of the artist.</param>
/// <returns>The mapped contributors, and the official homepage of the artist.</returns>
private static (List<MediaContributorDto> Contributors, string? Website) MapArtistRelations(IReadOnlyCollection<MusicBrainzRelationResponse> relations)
{
List<MediaContributorDto> contributors = [];
string? website = null;
foreach (MusicBrainzRelationResponse relation in relations)
{
if (string.Equals(relation.TargetType, "url", StringComparison.OrdinalIgnoreCase))
{
if (website is null && string.Equals(relation.Type, "official homepage", StringComparison.OrdinalIgnoreCase))
website = NullIfWhiteSpace(relation.Url?.Resource);
continue;
}
if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase))
continue;
string? name = NullIfWhiteSpace(relation.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes));
}
return (contributors, website);
}
/// <summary>
/// Adds a contributor to the provided list, unless an identical name and role pair is already present.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="displayName">The display name of the contributor.</param>
/// <param name="role">The role the contributor played.</param>
private static void AddContributor(List<MediaContributorDto> contributors, string displayName, MediaContributorRole role)
{
if (contributors.Any(contributor =>
string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) &&
contributor.Role == role))
return;
contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName, null), role));
}
/// <summary>
/// Adds the <paramref name="incoming"/> contributors to <paramref name="contributors"/>, skipping the duplicate name and role pairs.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="incoming">The contributors to add.</param>
private static void AddContributors(List<MediaContributorDto> contributors, IReadOnlyCollection<MediaContributorDto> incoming)
{
foreach (MediaContributorDto contributor in incoming)
{
if (contributor.Name?.DisplayName is not string displayName)
continue;
AddContributor(contributors, displayName, contributor.Role ?? MediaContributorRole.Other);
}
}
/// <summary>
/// Maps a MusicBrainz relationship type, and its attributes, into a canonical media contributor role.
/// </summary>
/// <param name="relationType">The relationship type to map.</param>
/// <param name="attributes">The attributes of the relationship.</param>
/// <returns>The mapped contributor role.</returns>
private static MediaContributorRole MapRole(string? relationType, IReadOnlyCollection<string> attributes)
{
// An instrument attribute is more specific than the generic relationship type, so it is preferred.
foreach (string attribute in attributes)
{
MediaContributorRole? attributed = MapInstrument(attribute);
if (attributed is not null)
return attributed.Value;
}
if (string.IsNullOrWhiteSpace(relationType))
return MediaContributorRole.Other;
string type = relationType.Trim().ToLowerInvariant();
if (type.Contains("executive producer", StringComparison.Ordinal))
return MediaContributorRole.ExecutiveProducer;
if (type.Contains("producer", StringComparison.Ordinal))
return MediaContributorRole.Producer;
if (type.Contains("remixer", StringComparison.Ordinal))
return MediaContributorRole.Remixer;
if (type.Contains("mix", StringComparison.Ordinal))
return MediaContributorRole.Mixer;
if (type.Contains("engineer", StringComparison.Ordinal) || type.Contains("mastering", StringComparison.Ordinal))
return MediaContributorRole.Engineer;
if (type.Contains("composer", StringComparison.Ordinal))
return MediaContributorRole.Composer;
if (type.Contains("writer", StringComparison.Ordinal))
return MediaContributorRole.Author;
if (type.Contains("lyricist", StringComparison.Ordinal))
return MediaContributorRole.Lyricist;
if (type.Contains("librettist", StringComparison.Ordinal))
return MediaContributorRole.Lyricist;
if (type.Contains("arranger", StringComparison.Ordinal))
return MediaContributorRole.Arranger;
if (type.Contains("conductor", StringComparison.Ordinal))
return MediaContributorRole.Conductor;
if (type.Contains("orchestrator", StringComparison.Ordinal))
return MediaContributorRole.Orchestrator;
if (type.Contains("backing vocals", StringComparison.Ordinal))
return MediaContributorRole.BackingVocals;
if (type.Contains("vocal", StringComparison.Ordinal))
return MediaContributorRole.Vocals;
if (type.Contains("member of band", StringComparison.Ordinal) || type.Contains("performer", StringComparison.Ordinal) || type.Contains("orchestra", StringComparison.Ordinal) || type.Contains("choir", StringComparison.Ordinal))
return MediaContributorRole.Performer;
return MediaContributorRole.Other;
}
/// <summary>
/// Maps a MusicBrainz instrument attribute into a canonical media contributor role.
/// </summary>
/// <param name="attribute">The instrument attribute to map.</param>
/// <returns>The mapped contributor role, or <see langword="null"/> when the attribute is not an instrument.</returns>
private static MediaContributorRole? MapInstrument(string? attribute)
{
if (string.IsNullOrWhiteSpace(attribute))
return null;
string value = attribute.Trim().ToLowerInvariant();
if (value.Contains("backing vocal", StringComparison.Ordinal))
return MediaContributorRole.BackingVocals;
if (value.Contains("vocal", StringComparison.Ordinal))
return MediaContributorRole.Vocals;
if (value.Contains("bass guitar", StringComparison.Ordinal))
return MediaContributorRole.BassGuitar;
if (value.Contains("guitar", StringComparison.Ordinal))
return MediaContributorRole.Guitar;
if (value.Contains("drum", StringComparison.Ordinal))
return MediaContributorRole.Drums;
if (value.Contains("percussion", StringComparison.Ordinal))
return MediaContributorRole.Percussion;
if (value.Contains("keyboard", StringComparison.Ordinal))
return MediaContributorRole.Keyboards;
if (value.Contains("piano", StringComparison.Ordinal))
return MediaContributorRole.Piano;
if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal))
return MediaContributorRole.Synthesizer;
if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal))
return MediaContributorRole.Strings;
if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal))
return MediaContributorRole.Brass;
if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal))
return MediaContributorRole.Woodwinds;
return null;
}
/// <summary>
/// Maps a MusicBrainz artist type into the application enum.
/// </summary>
/// <param name="type">The artist type to map.</param>
/// <returns>The mapped artist type, or <see langword="null"/> when the type is unknown.</returns>
private static MusicArtistType? MapArtistType(string? type)
{
if (string.IsNullOrWhiteSpace(type))
return null;
return type.Trim().ToLowerInvariant() switch
{
"person" => MusicArtistType.Person,
"group" => MusicArtistType.Group,
"orchestra" => MusicArtistType.Orchestra,
"choir" => MusicArtistType.Choir,
"character" => MusicArtistType.Character,
"other" => MusicArtistType.Other,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz gender into the application enum.
/// </summary>
/// <param name="gender">The gender to map.</param>
/// <returns>The mapped gender, or <see langword="null"/> when the gender is unknown.</returns>
private static MusicArtistGender? MapArtistGender(string? gender)
{
if (string.IsNullOrWhiteSpace(gender))
return null;
return gender.Trim().ToLowerInvariant() switch
{
"male" => MusicArtistGender.Male,
"female" => MusicArtistGender.Female,
"other" => MusicArtistGender.Other,
"not applicable" => MusicArtistGender.NotApplicable,
_ => null
};
}
/// <summary>
/// Maps the primary and secondary types of a release group into the application enum.
/// </summary>
/// <param name="primaryType">The primary type of the release group.</param>
/// <param name="secondaryTypes">The secondary types of the release group.</param>
/// <returns>The mapped release types.</returns>
private static List<MusicReleaseType> MapReleaseTypes(string? primaryType, IReadOnlyCollection<string> secondaryTypes)
{
List<MusicReleaseType> releaseTypes = [];
MusicReleaseType? primary = MapReleaseType(primaryType);
if (primary is not null)
releaseTypes.Add(primary.Value);
foreach (string secondaryType in secondaryTypes)
{
MusicReleaseType? mapped = MapReleaseType(secondaryType);
if (mapped is not null && !releaseTypes.Contains(mapped.Value))
releaseTypes.Add(mapped.Value);
}
return releaseTypes;
}
/// <summary>
/// Maps a single MusicBrainz release type into the application enum.
/// </summary>
/// <param name="type">The release type to map.</param>
/// <returns>The mapped release type, or <see langword="null"/> when the type is unknown.</returns>
private static MusicReleaseType? MapReleaseType(string? type)
{
if (string.IsNullOrWhiteSpace(type))
return null;
return type.Trim().ToLowerInvariant() switch
{
"album" => MusicReleaseType.Album,
"single" => MusicReleaseType.Single,
"ep" => MusicReleaseType.Ep,
"broadcast" => MusicReleaseType.Broadcast,
"other" => MusicReleaseType.Other,
"compilation" => MusicReleaseType.Compilation,
"live" => MusicReleaseType.Live,
"soundtrack" => MusicReleaseType.Soundtrack,
"spokenword" => MusicReleaseType.SpokenWord,
"audio drama" => MusicReleaseType.AudioDrama,
"audiobook" => MusicReleaseType.AudioBook,
"demo" => MusicReleaseType.Demo,
"dj-mix" => MusicReleaseType.DjMix,
"field recording" => MusicReleaseType.FieldRecording,
"interview" => MusicReleaseType.Interview,
"mixtape/street" => MusicReleaseType.Mixtape,
"remix" => MusicReleaseType.Remix,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz release status into the application enum.
/// </summary>
/// <param name="status">The release status to map.</param>
/// <returns>The mapped release status, or <see langword="null"/> when the status is unknown.</returns>
private static MusicReleaseStatus? MapReleaseStatus(string? status)
{
if (string.IsNullOrWhiteSpace(status))
return null;
return status.Trim().ToLowerInvariant() switch
{
"official" => MusicReleaseStatus.Official,
"promotion" => MusicReleaseStatus.Promotion,
"bootleg" => MusicReleaseStatus.Bootleg,
"pseudo-release" => MusicReleaseStatus.PseudoRelease,
"withdrawn" => MusicReleaseStatus.Withdrawn,
"cancelled" => MusicReleaseStatus.Cancelled,
"expunged" => MusicReleaseStatus.Expunged,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz medium format into the application enum.
/// </summary>
/// <param name="format">The format to map.</param>
/// <returns>The mapped media format, or <see langword="null"/> when the format is unknown.</returns>
private static MusicMediaFormat? MapMediaFormat(string? format)
{
if (string.IsNullOrWhiteSpace(format))
return null;
return format.Trim().ToLowerInvariant() switch
{
"cd" => MusicMediaFormat.CD,
"vinyl" => MusicMediaFormat.Vinyl,
"12\" vinyl" => MusicMediaFormat.Inch12Vinyl,
"10\" vinyl" => MusicMediaFormat.Inch10Vinyl,
"7\" vinyl" => MusicMediaFormat.Inch7Vinyl,
"digital media" => MusicMediaFormat.DigitalMedia,
"cassette" => MusicMediaFormat.Cassette,
"dvd" => MusicMediaFormat.DVD,
"dvd-video" => MusicMediaFormat.DVDVideo,
"dvd-audio" => MusicMediaFormat.DVDAudio,
"sacd" => MusicMediaFormat.SACD,
"hybrid sacd" => MusicMediaFormat.HybridSACD,
"blu-ray" => MusicMediaFormat.BluRay,
"minidisc" => MusicMediaFormat.MiniDisc,
"8cm cd" => MusicMediaFormat.Cm8CD,
"dat" => MusicMediaFormat.DAT,
"other" => MusicMediaFormat.Other,
_ => MusicMediaFormat.Other
};
}
/// <summary>
/// Maps a MusicBrainz release packaging into the application enum.
/// </summary>
/// <param name="packaging">The packaging to map.</param>
/// <returns>The mapped packaging, or <see langword="null"/> when the packaging is unknown.</returns>
private static MusicReleasePackaging? MapPackaging(string? packaging)
{
if (string.IsNullOrWhiteSpace(packaging))
return null;
return packaging.Trim().ToLowerInvariant() switch
{
"book" => MusicReleasePackaging.Book,
"box" => MusicReleasePackaging.Box,
"cardboard/paper sleeve" => MusicReleasePackaging.CardboardPaperSleeve,
"cassette case" => MusicReleasePackaging.CassetteCase,
"clamshell case" => MusicReleasePackaging.ClamshellCase,
"digibook" => MusicReleasePackaging.Digibook,
"digifile" => MusicReleasePackaging.Digifile,
"digipak" => MusicReleasePackaging.Digipak,
"discbox slider" => MusicReleasePackaging.DiscboxSlider,
"fatbox" => MusicReleasePackaging.Fatbox,
"gatefold cover" => MusicReleasePackaging.GatefoldCover,
"jewel case" => MusicReleasePackaging.JewelCase,
"keep case" => MusicReleasePackaging.KeepCase,
"longbox" => MusicReleasePackaging.Longbox,
"metal tin" => MusicReleasePackaging.MetalTin,
"plastic sleeve" => MusicReleasePackaging.PlasticSleeve,
"slidepack" => MusicReleasePackaging.Slidepack,
"slim jewel case" => MusicReleasePackaging.SlimJewelCase,
"slipcase" => MusicReleasePackaging.Slipcase,
"snap case" => MusicReleasePackaging.SnapCase,
"snappack" => MusicReleasePackaging.SnapPack,
"super jewel box" => MusicReleasePackaging.SuperJewelBox,
"none" => MusicReleasePackaging.None,
"other" => MusicReleasePackaging.Other,
_ => MusicReleasePackaging.Other
};
}
/// <summary>
/// Maps an ISO 3166-1 alpha-2 country code into the application enum.
/// </summary>
/// <param name="country">The country code to map.</param>
/// <returns>The mapped release country, or <see langword="null"/> when the code is unknown.</returns>
private static ReleaseCountry? MapReleaseCountry(string? country)
{
if (string.IsNullOrWhiteSpace(country))
return null;
return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null;
}
/// <summary>
/// Parses a MusicBrainz identifier into a <see cref="Guid"/>.
/// </summary>
/// <param name="value">The MusicBrainz identifier to parse.</param>
/// <returns>The parsed identifier, or <see langword="null"/> when the value is not a valid identifier.</returns>
private static Guid? ParseGuid(string? value)
{
return Guid.TryParse(value, out Guid parsed) ? parsed : null;
}
/// <summary>
/// Parses a MusicBrainz date string into a date and a year.
/// </summary>
/// <param name="value">The date string to parse.</param>
/// <returns>The parsed date and year, or <see langword="null"/> values when the string could not be parsed.</returns>
private static (DateOnly? Date, int? Year) ParseDate(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return (null, null);
if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact))
return (exact, exact.Year);
Match yearMatch = YearPattern().Match(value);
return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null);
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,206 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Mapping;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Provides album metadata from MusicBrainz by resolving lookups into album metadata DTOs.
/// A MusicBrainz release group is the logical album, while one of its releases is selected as the edition the local files match.
/// </summary>
internal sealed class MusicBrainzAlbumMetadataProvider : IMetadataProvider<AlbumMetadataLookupDto, AlbumMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzAlbumMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzAlbumMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of album metadata candidates found.</returns>
public async Task<IReadOnlyList<AlbumMetadataDto>> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Title))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzReleaseGroupResponse> releaseGroups = await _musicBrainzHttpClient
.SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<AlbumMetadataDto> candidates = [];
foreach (MusicBrainzReleaseGroupResponse releaseGroup in releaseGroups)
if (!string.IsNullOrWhiteSpace(releaseGroup.Title))
candidates.Add(MusicBrainzMapper.MapAlbum(releaseGroup, null));
return candidates;
}
/// <summary>
/// Gets the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the album, or <see langword="null"/> when no album was found.</returns>
public async Task<AlbumMetadataDto?> GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
MusicBrainzReleaseResponse? release = null;
MusicBrainzReleaseGroupResponse? releaseGroup = null;
// A release identifier pins the exact edition, so it is fetched first, and its release group is then resolved for the album level fields.
// The release is fetched together with its recordings, so that the track level enrichment of the same release is served from the response cache.
if (lookup.MusicBrainzReleaseId is not null)
release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
Guid? releaseGroupId = lookup.MusicBrainzReleaseGroupId;
if (releaseGroupId is null && release?.ReleaseGroup?.Id is string releaseGroupIdValue && Guid.TryParse(releaseGroupIdValue, out Guid parsedReleaseGroupId))
releaseGroupId = parsedReleaseGroupId;
if (releaseGroupId is not null)
releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(releaseGroupId.Value, cancellationToken).ConfigureAwait(false);
// Without any identifier, the album is searched by title and artist, and the first match is resolved in full.
if (release is null && releaseGroup is null && !string.IsNullOrWhiteSpace(lookup.Title))
{
IReadOnlyList<MusicBrainzReleaseGroupResponse> results = await _musicBrainzHttpClient
.SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), 1, cancellationToken).ConfigureAwait(false);
MusicBrainzReleaseGroupResponse? searchResult = results.Count > 0 ? results[0] : null;
if (searchResult?.Id is string searchResultId && Guid.TryParse(searchResultId, out Guid parsedSearchResultId))
releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(parsedSearchResultId, cancellationToken).ConfigureAwait(false);
}
if (releaseGroup is null)
return release is null ? null : MusicBrainzMapper.MapAlbum(new MusicBrainzReleaseGroupResponse { Id = release.ReleaseGroup?.Id, Title = release.Title }, release);
// When the exact release was not pinned by the lookup, the best edition of the release group is selected.
if (release is null && releaseGroup.Id is string releaseGroupIdentifier && Guid.TryParse(releaseGroupIdentifier, out Guid releaseGroupGuid))
{
IReadOnlyList<MusicBrainzReleaseResponse> releases = await _musicBrainzHttpClient
.BrowseReleasesByReleaseGroupAsync(releaseGroupGuid, settings.ReleaseLookupLimit, cancellationToken).ConfigureAwait(false);
release = SelectRelease(releases, lookup);
}
return MusicBrainzMapper.MapAlbum(releaseGroup, release);
}
/// <summary>
/// Selects the release of a release group that best matches the lookup, favoring official releases and those released in the lookup year.
/// </summary>
/// <param name="releases">The releases to select from.</param>
/// <param name="lookup">The lookup the selected release must match.</param>
/// <returns>The best matching release, or <see langword="null"/> when no release was provided.</returns>
private static MusicBrainzReleaseResponse? SelectRelease(IReadOnlyList<MusicBrainzReleaseResponse> releases, AlbumMetadataLookupDto lookup)
{
// Only a release whose tracklist matches the local album is selected, so that an edition of the release group that does not correspond to the
// local files is never attached to the album; without a known local track count, no release can be confidently matched, so none is selected.
if (lookup.TrackCount is not int trackCount)
return null;
List<MusicBrainzReleaseResponse> matchingReleases = [.. releases.Where(release => release.Media.Sum(medium => medium.TrackCount) == trackCount)];
if (matchingReleases.Count == 0)
return null;
return matchingReleases
.Select((release, index) => new
{
Release = release,
Index = index,
Score = ScoreRelease(release, lookup)
})
.OrderByDescending(item => item.Score)
.ThenBy(item => item.Index)
.Select(item => item.Release)
.First();
}
/// <summary>
/// Scores a release against the lookup to rank how well it matches.
/// </summary>
/// <param name="release">The release to score.</param>
/// <param name="lookup">The lookup the release must match.</param>
/// <returns>The match score of the release, where a higher score is a better match.</returns>
private static int ScoreRelease(MusicBrainzReleaseResponse release, AlbumMetadataLookupDto lookup)
{
int score = 0;
if (string.Equals(release.Status, "Official", StringComparison.OrdinalIgnoreCase))
score += 10_000;
if (lookup.ReleaseYear is int wantedYear && TryGetYear(release.Date) is int releaseYear && releaseYear == wantedYear)
score += 1_000;
if (!string.IsNullOrWhiteSpace(release.Barcode))
score += 100;
if (release.LabelInfo.Count > 0)
score += 50;
if (release.Media.Count > 0)
score += 10;
return score;
}
/// <summary>
/// Gets the year of a MusicBrainz date string.
/// </summary>
/// <param name="date">The date string to read.</param>
/// <returns>The year of the date, or <see langword="null"/> when it could not be read.</returns>
private static int? TryGetYear(string? date)
{
if (string.IsNullOrWhiteSpace(date))
return null;
string year = date.Length >= 4 ? date[..4] : date;
return int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? parsed : null;
}
/// <summary>
/// Builds the MusicBrainz release group search query for the provided title and artist.
/// </summary>
/// <param name="title">The title of the release group.</param>
/// <param name="artistName">The name of the artist, if applicable.</param>
/// <returns>The built search query.</returns>
private static string BuildReleaseGroupQuery(string title, string? artistName)
{
string query = $"releasegroup:\"{title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"";
if (!string.IsNullOrWhiteSpace(artistName))
query += $" AND artist:\"{artistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"";
return query;
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Mapping;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Provides music artist metadata from MusicBrainz by resolving lookups into artist metadata DTOs.
/// </summary>
internal sealed class MusicBrainzArtistMetadataProvider : IMetadataProvider<ArtistMetadataLookupDto, ArtistMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzArtistMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzArtistMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of artist metadata candidates found.</returns>
public async Task<IReadOnlyList<ArtistMetadataDto>> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Name))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzArtistResponse> artists = await _musicBrainzHttpClient
.SearchArtistsAsync(lookup.Name.Trim(), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<ArtistMetadataDto> candidates = [];
foreach (MusicBrainzArtistResponse artist in artists)
if (!string.IsNullOrWhiteSpace(artist.Name))
candidates.Add(MusicBrainzMapper.MapArtist(artist));
return candidates;
}
/// <summary>
/// Gets the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the artist, or <see langword="null"/> when no artist was found.</returns>
public async Task<ArtistMetadataDto?> GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
// A MusicBrainz identifier is the most precise lookup, so it is used first, if present.
if (lookup.MusicBrainzArtistId is not null)
{
MusicBrainzArtistResponse? artist = await _musicBrainzHttpClient.GetArtistAsync(lookup.MusicBrainzArtistId.Value, cancellationToken).ConfigureAwait(false);
return artist is null ? null : MusicBrainzMapper.MapArtist(artist);
}
if (string.IsNullOrWhiteSpace(lookup.Name))
return null;
// Without an identifier, the artist is searched by name, and the first match is resolved in full.
IReadOnlyList<MusicBrainzArtistResponse> artists = await _musicBrainzHttpClient
.SearchArtistsAsync(lookup.Name.Trim(), 1, cancellationToken).ConfigureAwait(false);
MusicBrainzArtistResponse? searchResult = artists.Count > 0 ? artists[0] : null;
if (searchResult?.Id is null)
return null;
MusicBrainzArtistResponse? detailedArtist = System.Guid.TryParse(searchResult.Id, out System.Guid artistId)
? await _musicBrainzHttpClient.GetArtistAsync(artistId, cancellationToken).ConfigureAwait(false)
: null;
return detailedArtist is null ? MusicBrainzMapper.MapArtist(searchResult) : MusicBrainzMapper.MapArtist(detailedArtist);
}
}
@@ -0,0 +1,97 @@
#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.MusicBrainz.Common.DependencyInjection;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Plugin that provides music metadata retrieval from MusicBrainz.
/// </summary>
public sealed class MusicBrainzPlugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3");
/// <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 => "MusicBrainz Metadata";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Retrieves artist, album and track metadata from MusicBrainz.";
/// <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: MusicBrainzSettingsKeys.BASE_URL,
Label: "Base URL",
Type: PluginSettingType.Text,
DefaultValue: "https://musicbrainz.org/ws/2/"),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL,
Label: "Allow LAN/Private Base URL",
Type: PluginSettingType.Boolean,
DefaultValue: "false"),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.CONTACT_EMAIL,
Label: "Contact Email",
Type: PluginSettingType.Text),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT,
Label: "Search Result Limit",
Type: PluginSettingType.Number,
DefaultValue: "10"),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT,
Label: "Release Lookup Limit",
Type: PluginSettingType.Number,
DefaultValue: "25"),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.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.AddMusicBrainzMetadataProviders(pluginId: Id);
}
}
@@ -0,0 +1,270 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Mapping;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Provides track metadata from MusicBrainz by resolving lookups into audio metadata DTOs.
/// </summary>
internal sealed class MusicBrainzTrackMetadataProvider : IMetadataProvider<TrackMetadataLookupDto, AudioMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzTrackMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzTrackMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of track metadata candidates found.</returns>
public async Task<IReadOnlyList<AudioMetadataDto>> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Title))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzRecordingResponse> recordings = await _musicBrainzHttpClient
.SearchRecordingsAsync(BuildRecordingQuery(lookup), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<AudioMetadataDto> candidates = [];
foreach (MusicBrainzRecordingResponse recording in recordings)
if (!string.IsNullOrWhiteSpace(recording.Title))
candidates.Add(MusicBrainzMapper.MapTrack(recording, null, null));
return candidates;
}
/// <summary>
/// Gets the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the track, or <see langword="null"/> when no track was found.</returns>
public async Task<AudioMetadataDto?> GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
// When the release the track belongs to is known, the release is fetched once, with all its recordings, and the track is resolved from its
// tracklist; the recording of that response already carries its work, so every track of the release is enriched from a single request.
if (lookup.MusicBrainzReleaseId is not null)
{
MusicBrainzReleaseResponse? release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
MusicBrainzTrackResponse? releaseTrack = release is null ? null : FindTrack(release, lookup);
if (releaseTrack?.Recording is not null)
{
MusicBrainzWorkResponse? inlineWork = await ResolveFallbackWorkAsync(ResolveInlineWork(releaseTrack.Recording), lookup, cancellationToken).ConfigureAwait(false);
return MusicBrainzMapper.MapTrack(releaseTrack.Recording, inlineWork, release);
}
}
MusicBrainzRecordingResponse? recording = null;
// A recording identifier is the most precise lookup, so it is used next, if present.
if (lookup.MusicBrainzRecordingId is not null)
recording = await _musicBrainzHttpClient.GetRecordingAsync(lookup.MusicBrainzRecordingId.Value, cancellationToken).ConfigureAwait(false);
// An ISRC lookup returns the recordings that carry the code, the first of which is then resolved in full.
if (recording is null && !string.IsNullOrWhiteSpace(lookup.Isrc))
{
IReadOnlyList<MusicBrainzRecordingResponse> recordings = await _musicBrainzHttpClient
.GetRecordingsByIsrcAsync(lookup.Isrc.Trim(), cancellationToken).ConfigureAwait(false);
MusicBrainzRecordingResponse? match = recordings.FirstOrDefault();
recording = await ResolveRecordingAsync(match, cancellationToken).ConfigureAwait(false);
}
// Without an identifier or a code, the track is searched, and the first match is resolved in full.
if (recording is null && !string.IsNullOrWhiteSpace(lookup.Title))
{
IReadOnlyList<MusicBrainzRecordingResponse> recordings = await _musicBrainzHttpClient
.SearchRecordingsAsync(BuildRecordingQuery(lookup), 1, cancellationToken).ConfigureAwait(false);
recording = await ResolveRecordingAsync(recordings.FirstOrDefault(), cancellationToken).ConfigureAwait(false);
}
if (recording is null)
return null;
MusicBrainzWorkResponse? work = await ResolveWorkAsync(recording, cancellationToken).ConfigureAwait(false);
work = await ResolveFallbackWorkAsync(work, lookup, cancellationToken).ConfigureAwait(false);
MusicBrainzReleaseResponse? resolvedRelease = await ResolveReleaseAsync(recording, cancellationToken).ConfigureAwait(false);
return MusicBrainzMapper.MapTrack(recording, work, resolvedRelease);
}
/// <summary>
/// Falls back to the work identifier of the tags when MusicBrainz did not link the recording to a work.
/// </summary>
/// <param name="work">The work resolved from MusicBrainz, if any.</param>
/// <param name="lookup">The lookup describing the local track.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The provided work, the work resolved from the work identifier of the tags, or <see langword="null"/> when neither is available.</returns>
private async Task<MusicBrainzWorkResponse?> ResolveFallbackWorkAsync(MusicBrainzWorkResponse? work, TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
// The title of the tags means the work of the tags is already complete, so it is kept as is and MusicBrainz is not queried again for it.
if (work is not null || lookup.MusicBrainzWorkId is not Guid musicBrainzWorkId || !string.IsNullOrWhiteSpace(lookup.WorkTitle))
return work;
return await _musicBrainzHttpClient.GetWorkAsync(musicBrainzWorkId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Finds the track of <paramref name="release"/> that matches the provided <paramref name="lookup"/>, matching the recording identifier first,
/// then the disc and track numbers, then the title, and finally the duration.
/// </summary>
/// <param name="release">The release whose tracklist is searched.</param>
/// <param name="lookup">The lookup describing the local track.</param>
/// <returns>The matching track, or <see langword="null"/> when no track matched.</returns>
private static MusicBrainzTrackResponse? FindTrack(MusicBrainzReleaseResponse release, TrackMetadataLookupDto lookup)
{
// The recording identifier is the most precise match, so it is used first, if present.
if (lookup.MusicBrainzRecordingId is Guid musicBrainzRecordingId)
{
foreach (MusicBrainzMediumResponse medium in release.Media)
foreach (MusicBrainzTrackResponse track in medium.Tracks)
if (track.Recording?.Id is string recordingId && Guid.TryParse(recordingId, out Guid trackRecordingId) && trackRecordingId == musicBrainzRecordingId)
return track;
}
List<MusicBrainzTrackResponse> candidates = [];
foreach (MusicBrainzMediumResponse medium in release.Media)
{
if (lookup.DiscNumber is int discNumber && medium.Position != discNumber)
continue;
foreach (MusicBrainzTrackResponse track in medium.Tracks)
{
if (lookup.TrackNumber is int trackNumber && track.Position != trackNumber)
continue;
candidates.Add(track);
}
}
if (candidates.Count <= 1)
return candidates.Count == 1 ? candidates[0] : null;
// The disc and track numbers were not enough to single the track out, so the title is used next, and the duration breaks any remaining tie.
if (!string.IsNullOrWhiteSpace(lookup.Title))
{
List<MusicBrainzTrackResponse> titledCandidates = [.. candidates.Where(candidate => string.Equals(candidate.Title, lookup.Title, StringComparison.OrdinalIgnoreCase))];
if (titledCandidates.Count == 1)
return titledCandidates[0];
if (titledCandidates.Count > 1)
candidates = titledCandidates;
}
if (candidates.Count > 1 && lookup.DurationInSeconds is int duration)
return candidates.OrderBy(candidate => Math.Abs((candidate.Length ?? 0) / 1000 - duration)).First();
return candidates[0];
}
/// <summary>
/// Gets the work the provided <paramref name="recording"/> is a performance of, from the relations already embedded in the response.
/// </summary>
/// <param name="recording">The recording whose work is resolved.</param>
/// <returns>The embedded work, or <see langword="null"/> when the recording has no work.</returns>
private static MusicBrainzWorkResponse? ResolveInlineWork(MusicBrainzRecordingResponse recording)
{
return recording.Relations
.Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
.Select(relation => relation.Work)
.FirstOrDefault(work => work is not null);
}
/// <summary>
/// Resolves the full recording of the provided search or ISRC lookup result.
/// </summary>
/// <param name="recording">The partial recording to resolve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The full recording, or <see langword="null"/> when the recording could not be resolved.</returns>
private async Task<MusicBrainzRecordingResponse?> ResolveRecordingAsync(MusicBrainzRecordingResponse? recording, CancellationToken cancellationToken)
{
if (recording?.Id is null || !Guid.TryParse(recording.Id, out Guid recordingId))
return recording;
return await _musicBrainzHttpClient.GetRecordingAsync(recordingId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resolves the work the provided recording is an instance of, together with its credited contributors.
/// </summary>
/// <param name="recording">The recording whose work is resolved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The work of the recording, or <see langword="null"/> when the recording has no work.</returns>
private async Task<MusicBrainzWorkResponse?> ResolveWorkAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken)
{
string? workId = recording.Relations
.Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
.Select(relation => relation.Work?.Id)
.FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
if (workId is null || !Guid.TryParse(workId, out Guid parsedWorkId))
return recording.Relations
.Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
.Select(relation => relation.Work)
.FirstOrDefault(work => work is not null);
return await _musicBrainzHttpClient.GetWorkAsync(parsedWorkId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resolves the release the provided recording appears on, for the release level language and script.
/// </summary>
/// <param name="recording">The recording whose release is resolved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release of the recording, or <see langword="null"/> when the recording does not reference a release.</returns>
private async Task<MusicBrainzReleaseResponse?> ResolveReleaseAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken)
{
string? releaseId = recording.Releases.Select(release => release.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
if (releaseId is null || !Guid.TryParse(releaseId, out Guid parsedReleaseId))
return null;
return await _musicBrainzHttpClient.GetReleaseAsync(parsedReleaseId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Builds the MusicBrainz recording search query for the provided lookup.
/// </summary>
/// <param name="lookup">The lookup describing the track.</param>
/// <returns>The built search query.</returns>
private static string BuildRecordingQuery(TrackMetadataLookupDto lookup)
{
List<string> parts = [];
if (!string.IsNullOrWhiteSpace(lookup.Title))
parts.Add($"recording:\"{lookup.Title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
if (!string.IsNullOrWhiteSpace(lookup.ArtistName))
parts.Add($"artist:\"{lookup.ArtistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
if (!string.IsNullOrWhiteSpace(lookup.ReleaseName))
parts.Add($"release:\"{lookup.ReleaseName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
return string.Join(" AND ", parts);
}
}
@@ -0,0 +1,37 @@
namespace Lumina.Plugins.MusicBrainz.Core.Settings;
/// <summary>
/// Keys of the settings of the MusicBrainz metadata plugin, shared by the settings schema and the settings loader.
/// </summary>
internal static class MusicBrainzSettingsKeys
{
/// <summary>
/// The key of the setting defining the base URL of the MusicBrainz web service.
/// </summary>
internal const string BASE_URL = "BaseUrl";
/// <summary>
/// The key of the setting that allows the base URL to point at a private or local host, for a self hosted mirror on a local network.
/// </summary>
internal const string DOES_ALLOW_PRIVATE_BASE_URL = "DoesAllowPrivateBaseUrl";
/// <summary>
/// The key of the setting defining the contact email sent to the MusicBrainz API.
/// </summary>
internal const string CONTACT_EMAIL = "ContactEmail";
/// <summary>
/// The key of the setting defining the maximum number of results returned by a single search.
/// </summary>
internal const string SEARCH_RESULT_LIMIT = "SearchResultLimit";
/// <summary>
/// The key of the setting defining the maximum number of releases fetched for a single release group.
/// </summary>
internal const string RELEASE_LOOKUP_LIMIT = "ReleaseLookupLimit";
/// <summary>
/// The key of the setting defining the minimum interval between consecutive requests to the MusicBrainz API, in seconds.
/// </summary>
internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds";
}
@@ -0,0 +1,252 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Settings;
/// <summary>
/// Provides the runtime settings of the MusicBrainz metadata plugin, overlaying the settings persisted by the host over the configured defaults.
/// </summary>
internal sealed class MusicBrainzSettingsProvider
{
// 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 MusicBrainzSettingsDto _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 MusicBrainzSettingsDto? _runtimeSettings;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzSettingsProvider"/> 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 MusicBrainzSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, MusicBrainzSettingsDto 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<MusicBrainzSettingsDto> GetAsync(CancellationToken cancellationToken)
{
// Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact.
MusicBrainzSettingsDto? 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 = Clone(_defaults);
if (_settingsStore is not null)
{
IReadOnlyDictionary<string, string>? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
if (storedSettings is not null)
Apply(runtimeSettings, storedSettings);
}
// 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>
/// Overlays the persisted settings onto the provided runtime settings, keeping the default values of the settings that were not persisted.
/// </summary>
/// <param name="settings">The runtime settings onto which the persisted settings are applied.</param>
/// <param name="storedSettings">The settings persisted by the host, keyed by setting key.</param>
private static void Apply(MusicBrainzSettingsDto settings, IReadOnlyDictionary<string, string> storedSettings)
{
// The private host opt-in must be resolved first, because it governs whether a private base URL is accepted below.
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, out string? doesAllowPrivateBaseUrl) &&
bool.TryParse(doesAllowPrivateBaseUrl, out bool doesAllowPrivateBaseUrlValue))
settings.DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrlValue;
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.BASE_URL, out string? baseUrl) &&
Uri.TryCreate(baseUrl?.Trim(), UriKind.Absolute, out Uri? parsedBaseUrl) &&
(parsedBaseUrl.Scheme == Uri.UriSchemeHttp || parsedBaseUrl.Scheme == Uri.UriSchemeHttps) &&
(settings.DoesAllowPrivateBaseUrl || IsPublicHost(parsedBaseUrl.Host)))
settings.BaseUrl = parsedBaseUrl.AbsoluteUri;
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.CONTACT_EMAIL, out string? contactEmail))
{
string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim();
settings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null;
}
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, out string? searchResultLimit) &&
int.TryParse(searchResultLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int searchResultLimitValue))
settings.SearchResultLimit = Math.Max(1, searchResultLimitValue);
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, out string? releaseLookupLimit) &&
int.TryParse(releaseLookupLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int releaseLookupLimitValue))
settings.ReleaseLookupLimit = Math.Max(1, releaseLookupLimitValue);
// 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(MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) &&
double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue) &&
double.IsFinite(minimumRequestIntervalValue))
settings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Clamp(minimumRequestIntervalValue, 0, MAXIMUM_REQUEST_INTERVAL_SECONDS));
}
/// <summary>
/// Determines whether the host of the persisted base URL is a public host, so the setting cannot be used to reach a local or private service.
/// </summary>
/// <param name="host">The host of the persisted base URL.</param>
/// <returns><see langword="true"/> when the host is public, otherwise <see langword="false"/>.</returns>
/// <remarks>
/// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. The host that runs the plugin
/// resolves it again when the request is sent, and rejects it when any address it resolves to is private, unless <see cref="MusicBrainzSettingsDto.DoesAllowPrivateBaseUrl"/>
/// enabled the private base address. That permission applies only to the host of the configured base address, so a redirect to another private host is still
/// rejected, and the link local and cloud metadata ranges are always rejected. Enabling the setting supports self hosted mirrors on a local network.
/// The address classification matches the one the host applies to a resolved address, so the settings layer does not accept a base URL that the host later
/// rejects.
/// </remarks>
private static bool IsPublicHost(string host)
{
if (string.IsNullOrWhiteSpace(host))
return false;
// Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept, and a fully qualified name may end with a dot.
string normalizedHost = host.Trim('[', ']').TrimEnd('.');
if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase))
return false;
if (!IPAddress.TryParse(normalizedHost, out IPAddress? address))
return true;
if (address.IsIPv4MappedToIPv6)
address = address.MapToIPv4();
if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
return false;
// IPv4-mapped IPv6 addresses were converted to IPv4 above, so the family split never sees one.
return address.AddressFamily == AddressFamily.InterNetwork
? IsPublicIPv4Address(address)
: IsPublicIPv6Address(address);
}
/// <summary>
/// Determines whether the provided IPv4 address is public.
/// </summary>
/// <param name="address">The IPv4 address to check.</param>
/// <returns><see langword="true"/> when the address is public, otherwise <see langword="false"/>.</returns>
private static bool IsPublicIPv4Address(IPAddress address)
{
byte[] octets = address.GetAddressBytes();
return octets[0] switch
{
0 => false, // The 0.0.0.0/8 "this network" range.
10 => false, // The 10.0.0.0/8 private range.
100 when octets[1] is >= 64 and <= 127 => false, // The 100.64.0.0/10 carrier grade NAT range.
127 => false, // The 127.0.0.0/8 loopback range.
169 when octets[1] == 254 => false, // The 169.254.0.0/16 link local range, including the cloud metadata endpoints.
172 when octets[1] is >= 16 and <= 31 => false, // The 172.16.0.0/12 private range.
192 when octets[1] == 168 => false, // The 192.168.0.0/16 private range.
192 when octets[1] == 0 && (octets[2] is 0 or 2) => false, // The IETF protocol assignments and TEST-NET-1 documentation ranges.
198 when octets[1] is >= 18 and <= 19 => false, // The 198.18.0.0/15 benchmarking range.
198 when octets[1] == 51 && octets[2] == 100 => false, // The TEST-NET-2 documentation range.
203 when octets[1] == 0 && octets[2] == 113 => false, // The TEST-NET-3 documentation range.
>= 224 => false, // The multicast range, the reserved range, and the broadcast address.
_ => true
};
}
/// <summary>
/// Determines whether the provided IPv6 address is public.
/// </summary>
/// <param name="address">The IPv6 address to check.</param>
/// <returns><see langword="true"/> when the address is public, otherwise <see langword="false"/>.</returns>
private static bool IsPublicIPv6Address(IPAddress address)
{
if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal || address.IsIPv6Multicast || address.IsIPv6Teredo || address.IsIPv6UniqueLocal)
return false;
byte[] addressBytes = address.GetAddressBytes();
// The ::/96 IPv4 compatible and ::ffff:0:0/96 IPv4 translated ranges embed an IPv4 address, and the mapped form is already converted to IPv4, so no
// address with an all zero first eighty bits is public.
if (addressBytes[0] == 0 && addressBytes[1] == 0 && addressBytes[2] == 0 && addressBytes[3] == 0 &&
addressBytes[4] == 0 && addressBytes[5] == 0 && addressBytes[6] == 0 && addressBytes[7] == 0 &&
addressBytes[8] == 0 && addressBytes[9] == 0)
return false;
return addressBytes[0] switch
{
0x00 when addressBytes[1] == 0x64 && addressBytes[2] == 0xFF && addressBytes[3] == 0x9B => false, // The 64:ff9b::/96 NAT64 prefix, which can map to private IPv4 addresses.
0x01 when addressBytes[1] == 0x00 && addressBytes[2] == 0x00 && addressBytes[3] == 0x00 => false, // The 100::/64 discard only range.
0x20 when addressBytes[1] == 0x01 && addressBytes[2] == 0x0D && addressBytes[3] == 0xB8 => false, // The 2001:db8::/32 documentation range.
0x20 when addressBytes[1] == 0x02 => false, // The 2002::/16 6to4 range.
_ => true
};
}
/// <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;
}
/// <summary>
/// Creates a copy of the given runtime settings.
/// </summary>
/// <param name="source">The runtime settings to copy.</param>
/// <returns>A copy of the given runtime settings.</returns>
private static MusicBrainzSettingsDto Clone(MusicBrainzSettingsDto source)
{
return new MusicBrainzSettingsDto
{
BaseUrl = source.BaseUrl,
DoesAllowPrivateBaseUrl = source.DoesAllowPrivateBaseUrl,
UserAgent = source.UserAgent,
ContactEmail = source.ContactEmail,
SearchResultLimit = source.SearchResultLimit,
ReleaseLookupLimit = source.ReleaseLookupLimit,
MinimumRequestInterval = source.MinimumRequestInterval
};
}
}