mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Refactors metadata provider contracts to typed interfaces
This commit is contained in:
1 parent
c82fadc7a2
commit
04927a95af
14 files changed
+274
-117
No files matched your search
+6
-15
@@ -8,8 +8,6 @@ using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.Common.DependencyInjection;
|
||||
@@ -30,27 +28,20 @@ internal static class OpenLibraryServices
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
// Build the runtime settings per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
|
||||
// Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
|
||||
services.TryAddScoped(serviceProvider =>
|
||||
{
|
||||
OpenLibrarySettingsDto openLibrarySettings = new();
|
||||
settingsCallback?.Invoke(openLibrarySettings);
|
||||
OpenLibrarySettingsDto defaults = new();
|
||||
settingsCallback?.Invoke(defaults);
|
||||
|
||||
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
|
||||
if (settingsStore is not null)
|
||||
{
|
||||
IReadOnlyDictionary<string, string>? storedSettings = settingsStore.GetSettingsAsync(pluginId, CancellationToken.None).GetAwaiter().GetResult();
|
||||
if (storedSettings is not null)
|
||||
OpenLibrarySettingsLoader.Apply(openLibrarySettings, storedSettings);
|
||||
}
|
||||
|
||||
return openLibrarySettings;
|
||||
return new OpenLibrarySettingsProvider(settingsStore, pluginId, defaults);
|
||||
});
|
||||
|
||||
services.AddHttpClient<OpenLibraryHttpClient>();
|
||||
|
||||
// Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IRemoteMetadataProvider implementations.
|
||||
services.AddKeyedTransient<IRemoteMetadataProvider, OpenLibraryBookMetadataProvider>(pluginId);
|
||||
// Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations.
|
||||
services.AddKeyedTransient<IMetadataProvider, OpenLibraryBookMetadataProvider>(pluginId);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Mapping;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
@@ -25,7 +26,7 @@ namespace Lumina.Plugins.OpenLibrary.Core.Api;
|
||||
internal sealed class OpenLibraryHttpClient
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly OpenLibrarySettingsDto _openLibrarySettings;
|
||||
private readonly OpenLibrarySettingsProvider _settingsProvider;
|
||||
private readonly SemaphoreSlim _requestGate = new(1, 1);
|
||||
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
|
||||
|
||||
@@ -44,18 +45,26 @@ internal sealed class OpenLibraryHttpClient
|
||||
/// Initializes a new instance of the <see cref="OpenLibraryHttpClient"/> class.
|
||||
/// </summary>
|
||||
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the Open Library API.</param>
|
||||
/// <param name="openLibrarySettings">The settings that configure the Open Library API requests.</param>
|
||||
public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsDto openLibrarySettings)
|
||||
/// <param name="settingsProvider">The provider of the settings that configure the Open Library API requests.</param>
|
||||
public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsProvider settingsProvider)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_openLibrarySettings = openLibrarySettings;
|
||||
_settingsProvider = settingsProvider;
|
||||
|
||||
_httpClient.BaseAddress ??= new("https://openlibrary.org/");
|
||||
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
|
||||
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(openLibrarySettings.UserAgent);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(openLibrarySettings.ContactEmail) && _httpClient.DefaultRequestHeaders.From is null)
|
||||
_httpClient.DefaultRequestHeaders.From = openLibrarySettings.ContactEmail!;
|
||||
/// <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 Open Library API requests.</param>
|
||||
private void EnsureRequestHeaders(OpenLibrarySettingsDto settings)
|
||||
{
|
||||
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
|
||||
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(settings.UserAgent);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(settings.ContactEmail) && _httpClient.DefaultRequestHeaders.From is null)
|
||||
_httpClient.DefaultRequestHeaders.From = settings.ContactEmail!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -214,10 +223,13 @@ internal sealed class OpenLibraryHttpClient
|
||||
/// <returns>The HTTP response message for the request.</returns>
|
||||
private async Task<HttpResponseMessage> SendAsync(string relativeUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
|
||||
EnsureRequestHeaders(settings);
|
||||
|
||||
await _requestGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
DateTimeOffset earliestNextRequest = _lastRequestAt + _openLibrarySettings.MinimumRequestInterval;
|
||||
DateTimeOffset earliestNextRequest = _lastRequestAt + settings.MinimumRequestInterval;
|
||||
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
|
||||
if (delay > TimeSpan.Zero)
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -30,7 +30,7 @@ internal static partial class OpenLibraryMapper
|
||||
/// <summary>
|
||||
/// Matches a volume number in a series or volume string.
|
||||
/// </summary>
|
||||
[GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?<number>\d+)\b", RegexOptions.IgnoreCase)]
|
||||
[GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?<number>\d+(?:\.\d+)?)\b", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex VolumePattern();
|
||||
|
||||
/// <summary>
|
||||
@@ -111,8 +111,8 @@ internal static partial class OpenLibraryMapper
|
||||
editionRelease.Date?.Year ?? editionRelease.Year,
|
||||
NullIfWhiteSpace(releaseCountry),
|
||||
NullIfWhiteSpace(releaseVersion)),
|
||||
genreNames.Select(name => new GenreDto(name)).ToList(),
|
||||
subjects.Select(name => new TagDto(name)).ToList(),
|
||||
[.. genreNames.Select(name => new GenreDto(name))],
|
||||
[.. subjects.Select(name => new TagDto(name))],
|
||||
MapLanguage(currentLanguageCode),
|
||||
MapLanguage(originalLanguageCode),
|
||||
edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(),
|
||||
@@ -347,14 +347,14 @@ internal static partial class OpenLibraryMapper
|
||||
/// </summary>
|
||||
/// <param name="candidates">The strings that may contain a volume number.</param>
|
||||
/// <returns>The parsed volume number, or <see langword="null"/> when no candidate contains one.</returns>
|
||||
private static int? ParseVolumeNumber(params string?[] candidates)
|
||||
private static float? ParseVolumeNumber(params string?[] candidates)
|
||||
{
|
||||
foreach (string? candidate in candidates)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(candidate))
|
||||
continue;
|
||||
Match match = VolumePattern().Match(candidate);
|
||||
if (match.Success && int.TryParse(match.Groups["number"].Value, out int number))
|
||||
if (match.Success && float.TryParse(match.Groups["number"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float number))
|
||||
return number;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -7,6 +7,7 @@ using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Api;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Mapping;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -19,10 +20,10 @@ namespace Lumina.Plugins.OpenLibrary.Core;
|
||||
/// <summary>
|
||||
/// Provides book metadata from the Open Library by resolving lookups into book metadata DTOs.
|
||||
/// </summary>
|
||||
internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
|
||||
internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
|
||||
{
|
||||
private readonly OpenLibraryHttpClient _openLibraryHttpClient;
|
||||
private readonly OpenLibrarySettingsDto _openLibrarySettings;
|
||||
private readonly OpenLibrarySettingsProvider _settingsProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the metadata provider.
|
||||
@@ -30,9 +31,9 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
public string Name => "Open Library";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library type this metadata provider supports.
|
||||
/// Gets the media library types this metadata provider supports.
|
||||
/// </summary>
|
||||
public LibraryType SupportedLibraryType => LibraryType.Book;
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
|
||||
@@ -43,11 +44,11 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
/// Initializes a new instance of the <see cref="OpenLibraryBookMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="openLibraryHttpClient">The HTTP client used to call the Open Library API.</param>
|
||||
/// <param name="openLibrarySettings">The settings that configure the Open Library API requests.</param>
|
||||
public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsDto openLibrarySettings)
|
||||
/// <param name="settingsProvider">The provider of the settings that configure the Open Library API requests.</param>
|
||||
public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsProvider settingsProvider)
|
||||
{
|
||||
_openLibraryHttpClient = openLibraryHttpClient;
|
||||
_openLibrarySettings = openLibrarySettings;
|
||||
_settingsProvider = settingsProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -60,6 +61,8 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
{
|
||||
ValidateLookup(bookMetadataLookup);
|
||||
|
||||
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId))
|
||||
{
|
||||
AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
|
||||
@@ -90,11 +93,11 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
exactBookRequestMatch.ISBNs,
|
||||
exactBookRequestMatch.Contributors,
|
||||
exactBookRequestMatch.Ratings,
|
||||
CoverImageUrl: null
|
||||
CoverImagePath: null
|
||||
)];
|
||||
}
|
||||
|
||||
IReadOnlyList<OpenLibrarySearchDocumentResponse> openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, _openLibrarySettings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<OpenLibrarySearchDocumentResponse> openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return [.. openLibrarySearchDocuments
|
||||
.Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title))
|
||||
@@ -128,7 +131,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
addBookRequest.ISBNs,
|
||||
addBookRequest.Contributors,
|
||||
addBookRequest.Ratings,
|
||||
CoverImageUrl: null
|
||||
CoverImagePath: null
|
||||
);
|
||||
})];
|
||||
}
|
||||
@@ -169,7 +172,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
exactBookRequestMatch.ISBNs,
|
||||
exactBookRequestMatch.Contributors,
|
||||
exactBookRequestMatch.Ratings,
|
||||
CoverImageUrl: null
|
||||
CoverImagePath: null
|
||||
);
|
||||
}
|
||||
|
||||
@@ -183,6 +186,8 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
{
|
||||
ValidateLookup(bookMetadataLookup);
|
||||
|
||||
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
OpenLibraryEditionResponse? openLibraryEditionResponse = null;
|
||||
OpenLibraryWorkResponse? openLibraryWorkResponse = null;
|
||||
OpenLibrarySearchDocumentResponse? openLibrarySearchDocumentResponse = null;
|
||||
@@ -199,7 +204,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
// A work has no publisher-specific details on its own (no ISBN, page count, etc.), so we still need to pull it for its work-level fields (e.g. description, subjects).
|
||||
openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(olid, cancellationToken).ConfigureAwait(false);
|
||||
// A work can have many editions; SelectEdition picks the one that best matches the lookup criteria (language, format, etc.) instead of assuming the first result is right.
|
||||
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(olid, _openLibrarySettings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
|
||||
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(olid, settings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("A book Open Library ID must be a work ID ending in W or an edition ID ending in M.", nameof(bookMetadataLookup));
|
||||
@@ -221,7 +226,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
|
||||
if (workId is not null)
|
||||
{
|
||||
openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(workId, cancellationToken).ConfigureAwait(false);
|
||||
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(workId, _openLibrarySettings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
|
||||
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(workId, settings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
|
||||
}
|
||||
|
||||
if (openLibraryEditionResponse is null && searchResults[0].EditionKeys.Count > 0)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Provides the runtime settings of the Open Library metadata plugin, overlaying the settings persisted by the host over the configured defaults.
|
||||
/// </summary>
|
||||
internal sealed class OpenLibrarySettingsProvider
|
||||
{
|
||||
private readonly IPluginSettingsStore? _settingsStore;
|
||||
private readonly Guid _pluginId;
|
||||
private readonly OpenLibrarySettingsDto _defaults;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private OpenLibrarySettingsDto? _runtimeSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OpenLibrarySettingsProvider"/> 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 OpenLibrarySettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, OpenLibrarySettingsDto 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<OpenLibrarySettingsDto> GetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
OpenLibrarySettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings);
|
||||
if (runtimeSettings is not null)
|
||||
return runtimeSettings;
|
||||
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
runtimeSettings = Volatile.Read(ref _runtimeSettings);
|
||||
if (runtimeSettings is null)
|
||||
{
|
||||
runtimeSettings = Clone(_defaults);
|
||||
if (_settingsStore is not null)
|
||||
{
|
||||
IReadOnlyDictionary<string, string>? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (storedSettings is not null)
|
||||
OpenLibrarySettingsLoader.Apply(runtimeSettings, storedSettings);
|
||||
}
|
||||
|
||||
Volatile.Write(ref _runtimeSettings, runtimeSettings);
|
||||
}
|
||||
|
||||
return runtimeSettings;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 OpenLibrarySettingsDto Clone(OpenLibrarySettingsDto source)
|
||||
{
|
||||
return new OpenLibrarySettingsDto
|
||||
{
|
||||
UserAgent = source.UserAgent,
|
||||
ContactEmail = source.ContactEmail,
|
||||
SearchResultLimit = source.SearchResultLimit,
|
||||
WorkEditionLimit = source.WorkEditionLimit,
|
||||
MinimumRequestInterval = source.MinimumRequestInterval
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user