Refactors metadata provider contracts to typed interfaces

This commit is contained in:
BinaryAlley committed 2026-08-24 14:17:29 -07:00
1 parent c82fadc7a2
commit 04927a95af
14 files changed
+274 -117

No files matched your search

@@ -8,8 +8,6 @@ using Lumina.Plugins.OpenLibrary.Core.Settings;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.DependencyInjection.Extensions;
using System; using System;
using System.Collections.Generic;
using System.Threading;
#endregion #endregion
namespace Lumina.Plugins.OpenLibrary.Common.DependencyInjection; namespace Lumina.Plugins.OpenLibrary.Common.DependencyInjection;
@@ -30,27 +28,20 @@ internal static class OpenLibraryServices
{ {
ArgumentNullException.ThrowIfNull(services); 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 => services.TryAddScoped(serviceProvider =>
{ {
OpenLibrarySettingsDto openLibrarySettings = new(); OpenLibrarySettingsDto defaults = new();
settingsCallback?.Invoke(openLibrarySettings); settingsCallback?.Invoke(defaults);
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>(); IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
if (settingsStore is not null) return new OpenLibrarySettingsProvider(settingsStore, pluginId, defaults);
{
IReadOnlyDictionary<string, string>? storedSettings = settingsStore.GetSettingsAsync(pluginId, CancellationToken.None).GetAwaiter().GetResult();
if (storedSettings is not null)
OpenLibrarySettingsLoader.Apply(openLibrarySettings, storedSettings);
}
return openLibrarySettings;
}); });
services.AddHttpClient<OpenLibraryHttpClient>(); services.AddHttpClient<OpenLibraryHttpClient>();
// Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IRemoteMetadataProvider implementations. // Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations.
services.AddKeyedTransient<IRemoteMetadataProvider, OpenLibraryBookMetadataProvider>(pluginId); services.AddKeyedTransient<IMetadataProvider, OpenLibraryBookMetadataProvider>(pluginId);
return services; 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.Contracts.Responses;
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Core.Mapping; using Lumina.Plugins.OpenLibrary.Core.Mapping;
using Lumina.Plugins.OpenLibrary.Core.Settings;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
@@ -25,7 +26,7 @@ namespace Lumina.Plugins.OpenLibrary.Core.Api;
internal sealed class OpenLibraryHttpClient internal sealed class OpenLibraryHttpClient
{ {
private readonly HttpClient _httpClient; private readonly HttpClient _httpClient;
private readonly OpenLibrarySettingsDto _openLibrarySettings; private readonly OpenLibrarySettingsProvider _settingsProvider;
private readonly SemaphoreSlim _requestGate = new(1, 1); private readonly SemaphoreSlim _requestGate = new(1, 1);
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue; private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
@@ -44,18 +45,26 @@ internal sealed class OpenLibraryHttpClient
/// Initializes a new instance of the <see cref="OpenLibraryHttpClient"/> class. /// Initializes a new instance of the <see cref="OpenLibraryHttpClient"/> class.
/// </summary> /// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the Open Library API.</param> /// <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> /// <param name="settingsProvider">The provider of the settings that configure the Open Library API requests.</param>
public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsDto openLibrarySettings) public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsProvider settingsProvider)
{ {
_httpClient = httpClient; _httpClient = httpClient;
_openLibrarySettings = openLibrarySettings; _settingsProvider = settingsProvider;
_httpClient.BaseAddress ??= new("https://openlibrary.org/"); _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) /// <summary>
_httpClient.DefaultRequestHeaders.From = openLibrarySettings.ContactEmail!; /// 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> /// <summary>
@@ -214,10 +223,13 @@ internal sealed class OpenLibraryHttpClient
/// <returns>The HTTP response message for the request.</returns> /// <returns>The HTTP response message for the request.</returns>
private async Task<HttpResponseMessage> SendAsync(string relativeUrl, CancellationToken cancellationToken) 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); await _requestGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try try
{ {
DateTimeOffset earliestNextRequest = _lastRequestAt + _openLibrarySettings.MinimumRequestInterval; DateTimeOffset earliestNextRequest = _lastRequestAt + settings.MinimumRequestInterval;
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow; TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero) if (delay > TimeSpan.Zero)
await Task.Delay(delay, cancellationToken).ConfigureAwait(false); await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
@@ -30,7 +30,7 @@ internal static partial class OpenLibraryMapper
/// <summary> /// <summary>
/// Matches a volume number in a series or volume string. /// Matches a volume number in a series or volume string.
/// </summary> /// </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(); private static partial Regex VolumePattern();
/// <summary> /// <summary>
@@ -111,8 +111,8 @@ internal static partial class OpenLibraryMapper
editionRelease.Date?.Year ?? editionRelease.Year, editionRelease.Date?.Year ?? editionRelease.Year,
NullIfWhiteSpace(releaseCountry), NullIfWhiteSpace(releaseCountry),
NullIfWhiteSpace(releaseVersion)), NullIfWhiteSpace(releaseVersion)),
genreNames.Select(name => new GenreDto(name)).ToList(), [.. genreNames.Select(name => new GenreDto(name))],
subjects.Select(name => new TagDto(name)).ToList(), [.. subjects.Select(name => new TagDto(name))],
MapLanguage(currentLanguageCode), MapLanguage(currentLanguageCode),
MapLanguage(originalLanguageCode), MapLanguage(originalLanguageCode),
edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(), edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(),
@@ -347,14 +347,14 @@ internal static partial class OpenLibraryMapper
/// </summary> /// </summary>
/// <param name="candidates">The strings that may contain a volume number.</param> /// <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> /// <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) foreach (string? candidate in candidates)
{ {
if (string.IsNullOrWhiteSpace(candidate)) if (string.IsNullOrWhiteSpace(candidate))
continue; continue;
Match match = VolumePattern().Match(candidate); 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 number;
} }
return null; 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.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Core.Api; using Lumina.Plugins.OpenLibrary.Core.Api;
using Lumina.Plugins.OpenLibrary.Core.Mapping; using Lumina.Plugins.OpenLibrary.Core.Mapping;
using Lumina.Plugins.OpenLibrary.Core.Settings;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -19,10 +20,10 @@ namespace Lumina.Plugins.OpenLibrary.Core;
/// <summary> /// <summary>
/// Provides book metadata from the Open Library by resolving lookups into book metadata DTOs. /// Provides book metadata from the Open Library by resolving lookups into book metadata DTOs.
/// </summary> /// </summary>
internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<BookMetadataLookupDto, BookMetadataDto> internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
{ {
private readonly OpenLibraryHttpClient _openLibraryHttpClient; private readonly OpenLibraryHttpClient _openLibraryHttpClient;
private readonly OpenLibrarySettingsDto _openLibrarySettings; private readonly OpenLibrarySettingsProvider _settingsProvider;
/// <summary> /// <summary>
/// Gets the display name of the metadata provider. /// Gets the display name of the metadata provider.
@@ -30,9 +31,9 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
public string Name => "Open Library"; public string Name => "Open Library";
/// <summary> /// <summary>
/// Gets the media library type this metadata provider supports. /// Gets the media library types this metadata provider supports.
/// </summary> /// </summary>
public LibraryType SupportedLibraryType => LibraryType.Book; public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book];
/// <summary> /// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. /// 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. /// Initializes a new instance of the <see cref="OpenLibraryBookMetadataProvider"/> class.
/// </summary> /// </summary>
/// <param name="openLibraryHttpClient">The HTTP client used to call the Open Library API.</param> /// <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> /// <param name="settingsProvider">The provider of the settings that configure the Open Library API requests.</param>
public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsDto openLibrarySettings) public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsProvider settingsProvider)
{ {
_openLibraryHttpClient = openLibraryHttpClient; _openLibraryHttpClient = openLibraryHttpClient;
_openLibrarySettings = openLibrarySettings; _settingsProvider = settingsProvider;
} }
/// <summary> /// <summary>
@@ -60,6 +61,8 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
{ {
ValidateLookup(bookMetadataLookup); ValidateLookup(bookMetadataLookup);
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId)) if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId))
{ {
AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
@@ -90,11 +93,11 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
exactBookRequestMatch.ISBNs, exactBookRequestMatch.ISBNs,
exactBookRequestMatch.Contributors, exactBookRequestMatch.Contributors,
exactBookRequestMatch.Ratings, 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 return [.. openLibrarySearchDocuments
.Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title)) .Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title))
@@ -128,7 +131,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
addBookRequest.ISBNs, addBookRequest.ISBNs,
addBookRequest.Contributors, addBookRequest.Contributors,
addBookRequest.Ratings, addBookRequest.Ratings,
CoverImageUrl: null CoverImagePath: null
); );
})]; })];
} }
@@ -169,7 +172,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
exactBookRequestMatch.ISBNs, exactBookRequestMatch.ISBNs,
exactBookRequestMatch.Contributors, exactBookRequestMatch.Contributors,
exactBookRequestMatch.Ratings, exactBookRequestMatch.Ratings,
CoverImageUrl: null CoverImagePath: null
); );
} }
@@ -183,6 +186,8 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<
{ {
ValidateLookup(bookMetadataLookup); ValidateLookup(bookMetadataLookup);
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
OpenLibraryEditionResponse? openLibraryEditionResponse = null; OpenLibraryEditionResponse? openLibraryEditionResponse = null;
OpenLibraryWorkResponse? openLibraryWorkResponse = null; OpenLibraryWorkResponse? openLibraryWorkResponse = null;
OpenLibrarySearchDocumentResponse? openLibrarySearchDocumentResponse = 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). // 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); 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. // 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 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)); 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) if (workId is not null)
{ {
openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(workId, cancellationToken).ConfigureAwait(false); 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) 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
};
}
}
@@ -9,9 +9,9 @@ using System.Threading.Tasks;
namespace Lumina.Plugins.Contracts.Core.Metadata; namespace Lumina.Plugins.Contracts.Core.Metadata;
/// <summary> /// <summary>
/// Contract for a plugin that provides metadata for media items from a remote source. /// Contract for a plugin that provides metadata for media items.
/// </summary> /// </summary>
public interface IRemoteMetadataProvider public interface IMetadataProvider
{ {
/// <summary> /// <summary>
/// Gets the display name of the metadata provider. /// Gets the display name of the metadata provider.
@@ -19,9 +19,9 @@ public interface IRemoteMetadataProvider
string Name { get; } string Name { get; }
/// <summary> /// <summary>
/// Gets the media library type this metadata provider supports. /// Gets the media library types this metadata provider supports.
/// </summary> /// </summary>
LibraryType SupportedLibraryType { get; } IReadOnlyList<LibraryType> SupportedLibraryTypes { get; }
/// <summary> /// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
@@ -29,18 +29,18 @@ public interface IRemoteMetadataProvider
bool RequiresWebAccess { get; } bool RequiresWebAccess { get; }
/// <summary> /// <summary>
/// Searches for the metadata of the media item described by <paramref name="lookup"/>. /// Searches for the metadata of the media item described by <paramref name="metadataLookup"/>.
/// </summary> /// </summary>
/// <param name="lookup">The lookup describing the media item to search for.</param> /// <param name="metadataLookup">The lookup describing the media item to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of metadata candidates found for the media item.</returns> /// <returns>The collection of metadata candidates found for the media item.</returns>
Task<IReadOnlyList<MetadataDto>> GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); Task<IReadOnlyList<MetadataDto>> GetSearchResultsAsync(MetadataLookupDto metadataLookup, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Gets the metadata of the media item described by <paramref name="lookup"/>. /// Gets the metadata of the media item described by <paramref name="metadataLookup"/>.
/// </summary> /// </summary>
/// <param name="lookup">The lookup describing the media item to get the metadata for.</param> /// <param name="metadataLookup">The lookup describing the media item to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns> /// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns>
Task<MetadataDto?> GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); Task<MetadataDto?> GetMetadataAsync(MetadataLookupDto metadataLookup, CancellationToken cancellationToken);
} }
@@ -8,11 +8,11 @@ using System.Threading.Tasks;
namespace Lumina.Plugins.Contracts.Core.Metadata; namespace Lumina.Plugins.Contracts.Core.Metadata;
/// <summary> /// <summary>
/// Contract for a plugin that provides metadata for media items from a remote source, typed to the media item lookup and metadata types. /// Contract for a plugin that provides metadata for media items, typed to the media item lookup and metadata types.
/// </summary> /// </summary>
/// <typeparam name="TLookup">The type of the lookup describing the media item.</typeparam> /// <typeparam name="TLookup">The type of the lookup describing the media item.</typeparam>
/// <typeparam name="TMetadata">The type of the metadata of the media item.</typeparam> /// <typeparam name="TMetadata">The type of the metadata of the media item.</typeparam>
public interface IRemoteMetadataProvider<TLookup, TMetadata> : IRemoteMetadataProvider public interface IMetadataProvider<TLookup, TMetadata> : IMetadataProvider
where TLookup : MetadataLookupDto where TLookup : MetadataLookupDto
where TMetadata : MetadataDto where TMetadata : MetadataDto
{ {
@@ -38,7 +38,7 @@ public interface IRemoteMetadataProvider<TLookup, TMetadata> : IRemoteMetadataPr
/// <param name="lookup">The lookup describing the media item to search for.</param> /// <param name="lookup">The lookup describing the media item to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of metadata candidates found for the media item.</returns> /// <returns>The collection of metadata candidates found for the media item.</returns>
async Task<IReadOnlyList<MetadataDto>> IRemoteMetadataProvider.GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) async Task<IReadOnlyList<MetadataDto>> IMetadataProvider.GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken)
{ {
return await GetSearchResultsAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false); return await GetSearchResultsAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false);
} }
@@ -49,7 +49,7 @@ public interface IRemoteMetadataProvider<TLookup, TMetadata> : IRemoteMetadataPr
/// <param name="lookup">The lookup describing the media item to get the metadata for.</param> /// <param name="lookup">The lookup describing the media item to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns> /// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns>
async Task<MetadataDto?> IRemoteMetadataProvider.GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) async Task<MetadataDto?> IMetadataProvider.GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken)
{ {
return await GetMetadataAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false); return await GetMetadataAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false);
} }
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Contracts.Fixtures.Core.DTO.Common;
/// <summary>
/// Test double deriving from <see cref="MetadataLookupDto"/> for a runtime type other than <see cref="BookMetadataLookupDto"/>.
/// </summary>
[ExcludeFromCodeCoverage]
public sealed record OtherMetadataLookupDto : MetadataLookupDto;
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.DTO.Common;
/// <summary>
/// Fixture class for the <see cref="OtherMetadataLookupDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class OtherMetadataLookupDtoFixture
{
/// <summary>
/// Creates a <see cref="OtherMetadataLookupDto"/>.
/// </summary>
/// <returns>The created <see cref="OtherMetadataLookupDto"/>.</returns>
public OtherMetadataLookupDto Create()
{
return new OtherMetadataLookupDto();
}
/// <summary>
/// Creates a list of <see cref="OtherMetadataLookupDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<OtherMetadataLookupDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,13 +1,13 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata; using Lumina.Plugins.Contracts.Core.Metadata;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#endregion #endregion
@@ -15,13 +15,14 @@ using System.Threading.Tasks;
namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata; namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata;
/// <summary> /// <summary>
/// Contains unit tests for the <see cref="IRemoteMetadataProvider{TLookup, TMetadata}"/> interface. /// Contains unit tests for the <see cref="IMetadataProvider{TLookup, TMetadata}"/> interface.
/// </summary> /// </summary>
[ExcludeFromCodeCoverage] [ExcludeFromCodeCoverage]
public class IRemoteMetadataProviderGenericTests public class IMetadataProviderGenericTests
{ {
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
private readonly OtherMetadataLookupDtoFixture _otherMetadataLookupDtoFixture = new();
[Fact] [Fact]
public async Task GetSearchResultsAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation() public async Task GetSearchResultsAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation()
@@ -31,7 +32,7 @@ public class IRemoteMetadataProviderGenericTests
CancellationToken cancellationToken = CancellationToken.None; CancellationToken cancellationToken = CancellationToken.None;
BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false); BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false);
TestBookMetadataProvider provider = new(expectedMetadata); TestBookMetadataProvider provider = new(expectedMetadata);
IRemoteMetadataProvider baseProvider = provider; IMetadataProvider baseProvider = provider;
// Act // Act
IReadOnlyList<MetadataDto> result = await baseProvider.GetSearchResultsAsync(lookup, cancellationToken); IReadOnlyList<MetadataDto> result = await baseProvider.GetSearchResultsAsync(lookup, cancellationToken);
@@ -51,7 +52,7 @@ public class IRemoteMetadataProviderGenericTests
CancellationToken cancellationToken = CancellationToken.None; CancellationToken cancellationToken = CancellationToken.None;
BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false); BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false);
TestBookMetadataProvider provider = new(expectedMetadata); TestBookMetadataProvider provider = new(expectedMetadata);
IRemoteMetadataProvider baseProvider = provider; IMetadataProvider baseProvider = provider;
// Act // Act
MetadataDto? result = await baseProvider.GetMetadataAsync(lookup, cancellationToken); MetadataDto? result = await baseProvider.GetMetadataAsync(lookup, cancellationToken);
@@ -66,9 +67,9 @@ public class IRemoteMetadataProviderGenericTests
public async Task GetSearchResultsAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() public async Task GetSearchResultsAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException()
{ {
// Arrange // Arrange
MetadataLookupDto otherLookup = new OtherMetadataLookupDto(); MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create();
TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false)); TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false));
IRemoteMetadataProvider baseProvider = provider; IMetadataProvider baseProvider = provider;
// Act // Act
async Task Act() async Task Act()
@@ -85,9 +86,9 @@ public class IRemoteMetadataProviderGenericTests
public async Task GetMetadataAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() public async Task GetMetadataAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException()
{ {
// Arrange // Arrange
MetadataLookupDto otherLookup = new OtherMetadataLookupDto(); MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create();
TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false)); TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false));
IRemoteMetadataProvider baseProvider = provider; IMetadataProvider baseProvider = provider;
// Act // Act
async Task Act() async Task Act()
@@ -104,7 +105,7 @@ public class IRemoteMetadataProviderGenericTests
/// Test double for the typed metadata provider interface that records the forwarded arguments. /// Test double for the typed metadata provider interface that records the forwarded arguments.
/// </summary> /// </summary>
[ExcludeFromCodeCoverage] [ExcludeFromCodeCoverage]
private sealed class TestBookMetadataProvider : IRemoteMetadataProvider<BookMetadataLookupDto, BookMetadataDto> private sealed class TestBookMetadataProvider : IMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
{ {
private readonly BookMetadataDto _metadata; private readonly BookMetadataDto _metadata;
@@ -131,7 +132,7 @@ public class IRemoteMetadataProviderGenericTests
public string Name => "Test Provider"; public string Name => "Test Provider";
/// <inheritdoc/> /// <inheritdoc/>
public LibraryType SupportedLibraryType => LibraryType.Book; public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book];
/// <inheritdoc/> /// <inheritdoc/>
public bool RequiresWebAccess => false; public bool RequiresWebAccess => false;
@@ -152,10 +153,4 @@ public class IRemoteMetadataProviderGenericTests
return Task.FromResult<BookMetadataDto?>(_metadata); return Task.FromResult<BookMetadataDto?>(_metadata);
} }
} }
/// <summary>
/// Test double deriving from <see cref="MetadataLookupDto"/> for a runtime type other than <see cref="BookMetadataLookupDto"/>.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed record OtherMetadataLookupDto : MetadataLookupDto;
} }
@@ -60,8 +60,8 @@ public class OpenLibraryServicesTests
ServiceProvider serviceProvider = services.BuildServiceProvider(); ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert // Assert
Assert.NotNull(serviceProvider.GetKeyedService<IRemoteMetadataProvider>(pluginId)); Assert.NotNull(serviceProvider.GetKeyedService<IMetadataProvider>(pluginId));
Assert.Null(serviceProvider.GetKeyedService<IRemoteMetadataProvider>(Guid.NewGuid())); Assert.Null(serviceProvider.GetKeyedService<IMetadataProvider>(Guid.NewGuid()));
} }
[Fact] [Fact]
@@ -79,7 +79,7 @@ public class OpenLibraryServicesTests
} }
[Fact] [Fact]
public void AddOpenLibraryBookMetadataProvider_WhenSettingsCallbackIsProvided_ShouldApplyTheCallbackToTheRuntimeSettings() public async Task AddOpenLibraryBookMetadataProvider_WhenSettingsCallbackIsProvided_ShouldApplyTheCallbackToTheRuntimeSettings()
{ {
// Arrange // Arrange
ServiceCollection services = new(); ServiceCollection services = new();
@@ -88,16 +88,17 @@ public class OpenLibraryServicesTests
services.AddOpenLibraryBookMetadataProvider( services.AddOpenLibraryBookMetadataProvider(
pluginId: Guid.NewGuid(), pluginId: Guid.NewGuid(),
settingsCallback: settings => settings.ContactEmail = "callback@example.com"); settingsCallback: settings => settings.ContactEmail = "callback@example.com");
ServiceProvider serviceProvider = services.BuildServiceProvider(); using ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert // Assert
OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService<OpenLibrarySettingsDto>(); OpenLibrarySettingsProvider settingsProvider = serviceProvider.GetRequiredService<OpenLibrarySettingsProvider>();
OpenLibrarySettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None);
Assert.Equal("callback@example.com", settings.ContactEmail); Assert.Equal("callback@example.com", settings.ContactEmail);
Assert.Equal(10, settings.SearchResultLimit); Assert.Equal(10, settings.SearchResultLimit);
} }
[Fact] [Fact]
public void AddOpenLibraryBookMetadataProvider_WhenASettingsStoreIsRegistered_ShouldApplyTheStoredSettings() public async Task AddOpenLibraryBookMetadataProvider_WhenASettingsStoreIsRegistered_ShouldApplyTheStoredSettings()
{ {
// Arrange // Arrange
Guid pluginId = Guid.NewGuid(); Guid pluginId = Guid.NewGuid();
@@ -112,16 +113,17 @@ public class OpenLibraryServicesTests
// Act // Act
services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId); services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId);
ServiceProvider serviceProvider = services.BuildServiceProvider(); using ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert // Assert
OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService<OpenLibrarySettingsDto>(); OpenLibrarySettingsProvider settingsProvider = serviceProvider.GetRequiredService<OpenLibrarySettingsProvider>();
OpenLibrarySettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None);
Assert.Equal(25, settings.SearchResultLimit); Assert.Equal(25, settings.SearchResultLimit);
Assert.Equal(50, settings.WorkEditionLimit); Assert.Equal(50, settings.WorkEditionLimit);
} }
[Fact] [Fact]
public void AddOpenLibraryBookMetadataProvider_WhenTheSettingsStoreReturnsNull_ShouldKeepTheDefaultSettings() public async Task AddOpenLibraryBookMetadataProvider_WhenTheSettingsStoreReturnsNull_ShouldKeepTheDefaultSettings()
{ {
// Arrange // Arrange
Guid pluginId = Guid.NewGuid(); Guid pluginId = Guid.NewGuid();
@@ -133,27 +135,30 @@ public class OpenLibraryServicesTests
// Act // Act
services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId); services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId);
ServiceProvider serviceProvider = services.BuildServiceProvider(); using ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert // Assert
OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService<OpenLibrarySettingsDto>(); OpenLibrarySettingsProvider settingsProvider = serviceProvider.GetRequiredService<OpenLibrarySettingsProvider>();
OpenLibrarySettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None);
Assert.Equal(10, settings.SearchResultLimit); Assert.Equal(10, settings.SearchResultLimit);
Assert.Equal(50, settings.WorkEditionLimit); Assert.Equal(50, settings.WorkEditionLimit);
} }
[Fact] [Fact]
public void AddOpenLibraryBookMetadataProvider_WhenResolvedAcrossScopes_ShouldReturnDistinctRuntimeSettingsInstances() public async Task AddOpenLibraryBookMetadataProvider_WhenResolvedAcrossScopes_ShouldReturnDistinctRuntimeSettingsInstances()
{ {
// Arrange // Arrange
ServiceCollection services = new(); ServiceCollection services = new();
services.AddOpenLibraryBookMetadataProvider(pluginId: Guid.NewGuid()); services.AddOpenLibraryBookMetadataProvider(pluginId: Guid.NewGuid());
ServiceProvider serviceProvider = services.BuildServiceProvider(); using ServiceProvider serviceProvider = services.BuildServiceProvider();
// Act // Act
using IServiceScope firstScope = serviceProvider.CreateScope(); using IServiceScope firstScope = serviceProvider.CreateScope();
using IServiceScope secondScope = serviceProvider.CreateScope(); using IServiceScope secondScope = serviceProvider.CreateScope();
OpenLibrarySettingsDto first = firstScope.ServiceProvider.GetRequiredService<OpenLibrarySettingsDto>(); OpenLibrarySettingsProvider firstProvider = firstScope.ServiceProvider.GetRequiredService<OpenLibrarySettingsProvider>();
OpenLibrarySettingsDto second = secondScope.ServiceProvider.GetRequiredService<OpenLibrarySettingsDto>(); OpenLibrarySettingsProvider secondProvider = secondScope.ServiceProvider.GetRequiredService<OpenLibrarySettingsProvider>();
OpenLibrarySettingsDto first = await firstProvider.GetAsync(CancellationToken.None);
OpenLibrarySettingsDto second = await secondProvider.GetAsync(CancellationToken.None);
// Assert // Assert
Assert.NotSame(first, second); Assert.NotSame(first, second);
@@ -4,6 +4,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Core.Api; using Lumina.Plugins.OpenLibrary.Core.Api;
using Lumina.Plugins.OpenLibrary.Core.Settings;
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup;
using System; using System;
@@ -35,7 +36,7 @@ public class OpenLibraryHttpClientTests
HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler());
// Act // Act
_ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create()); _ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create()));
// Assert // Assert
Assert.Equal(new Uri("https://openlibrary.org/"), httpClient.BaseAddress); Assert.Equal(new Uri("https://openlibrary.org/"), httpClient.BaseAddress);
@@ -52,61 +53,72 @@ public class OpenLibraryHttpClientTests
}; };
// Act // Act
_ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create()); _ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create()));
// Assert // Assert
Assert.Equal(existingBaseAddress, httpClient.BaseAddress); Assert.Equal(existingBaseAddress, httpClient.BaseAddress);
} }
[Fact] [Fact]
public void Constructor_WhenHttpClientHasNoUserAgent_ShouldAddTheConfiguredUserAgent() public async Task GetEditionAsync_WhenHttpClientHasNoUserAgent_ShouldAddTheConfiguredUserAgent()
{ {
// Arrange // Arrange
HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); StubOpenLibraryHttpMessageHandler handler = new();
OpenLibrarySettingsDto settings = _settingsFixture.Create(userAgent: "CustomAgent/2.0"); handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
HttpClient httpClient = new(handler);
OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(userAgent: "CustomAgent/2.0")));
// Act // Act
_ = new OpenLibraryHttpClient(httpClient, settings); await sut.GetEditionAsync("OL1M", CancellationToken.None);
// Assert // Assert
Assert.Equal("CustomAgent/2.0", httpClient.DefaultRequestHeaders.UserAgent.ToString()); Assert.Equal("CustomAgent/2.0", httpClient.DefaultRequestHeaders.UserAgent.ToString());
} }
[Fact] [Fact]
public void Constructor_WhenHttpClientAlreadyHasUserAgent_ShouldKeepTheExistingUserAgent() public async Task GetEditionAsync_WhenHttpClientAlreadyHasUserAgent_ShouldKeepTheExistingUserAgent()
{ {
// Arrange // Arrange
HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); StubOpenLibraryHttpMessageHandler handler = new();
handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
HttpClient httpClient = new(handler);
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("ExistingAgent/1.0"); httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("ExistingAgent/1.0");
OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(userAgent: "ConfiguredAgent/2.0")));
// Act // Act
_ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(userAgent: "ConfiguredAgent/2.0")); await sut.GetEditionAsync("OL1M", CancellationToken.None);
// Assert // Assert
Assert.Equal("ExistingAgent/1.0", httpClient.DefaultRequestHeaders.UserAgent.ToString()); Assert.Equal("ExistingAgent/1.0", httpClient.DefaultRequestHeaders.UserAgent.ToString());
} }
[Fact] [Fact]
public void Constructor_WhenContactEmailIsConfigured_ShouldSetTheFromHeader() public async Task GetEditionAsync_WhenContactEmailIsConfigured_ShouldSetTheFromHeader()
{ {
// Arrange // Arrange
HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); StubOpenLibraryHttpMessageHandler handler = new();
handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
HttpClient httpClient = new(handler);
OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(contactEmail: "contact@example.com")));
// Act // Act
_ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(contactEmail: "contact@example.com")); await sut.GetEditionAsync("OL1M", CancellationToken.None);
// Assert // Assert
Assert.Equal("contact@example.com", httpClient.DefaultRequestHeaders.From); Assert.Equal("contact@example.com", httpClient.DefaultRequestHeaders.From);
} }
[Fact] [Fact]
public void Constructor_WhenContactEmailIsNotConfigured_ShouldNotSetTheFromHeader() public async Task GetEditionAsync_WhenContactEmailIsNotConfigured_ShouldNotSetTheFromHeader()
{ {
// Arrange // Arrange
HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); StubOpenLibraryHttpMessageHandler handler = new();
handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
HttpClient httpClient = new(handler);
OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(contactEmail: null)));
// Act // Act
_ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(contactEmail: null)); await sut.GetEditionAsync("OL1M", CancellationToken.None);
// Assert // Assert
Assert.Null(httpClient.DefaultRequestHeaders.From); Assert.Null(httpClient.DefaultRequestHeaders.From);
@@ -541,9 +553,16 @@ public class OpenLibraryHttpClientTests
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act); await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
} }
/// <summary>
/// Creates the Open Library HTTP client under test backed by the given handler and settings.
/// </summary>
/// <param name="handler">The stub HTTP message handler used to serve responses.</param>
/// <param name="settings">Optional. The Open Library settings used by the client. When omitted, randomized settings are used.</param>
/// <returns>The created <see cref="OpenLibraryHttpClient"/>.</returns>
private OpenLibraryHttpClient CreateSut(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null) private OpenLibraryHttpClient CreateSut(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null)
{ {
HttpClient httpClient = new(handler); HttpClient httpClient = new(handler);
return new OpenLibraryHttpClient(httpClient, settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero));
return new OpenLibraryHttpClient(httpClient, settingsProvider);
} }
} }
@@ -7,12 +7,12 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Core; using Lumina.Plugins.OpenLibrary.Core;
using Lumina.Plugins.OpenLibrary.Core.Api; using Lumina.Plugins.OpenLibrary.Core.Api;
using Lumina.Plugins.OpenLibrary.Core.Settings;
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -30,13 +30,9 @@ public class OpenLibraryBookMetadataProviderTests
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
private const string EDITION_JSON = """{"key":"/books/OL100M","title":"Edition Title","publish_date":"2010-05-01","number_of_pages":320,"physical_format":"Hardcover","edition_name":"First Edition","series":["The Series"],"volume":"Vol. 3","publishers":["Publisher Co"],"isbn_13":["9780306406157"],"languages":[{"key":"/languages/eng"}],"works":[{"key":"/works/OL200W"}]}"""; private const string EDITION_JSON = """{"key":"/books/OL100M","title":"Edition Title","publish_date":"2010-05-01","number_of_pages":320,"physical_format":"Hardcover","edition_name":"First Edition","series":["The Series"],"volume":"Vol. 3","publishers":["Publisher Co"],"isbn_13":["9780306406157"],"languages":[{"key":"/languages/eng"}],"works":[{"key":"/works/OL200W"}]}""";
private const string WORK_JSON = """{"key":"/works/OL200W","title":"Work Title","first_publish_date":"2001-01-01","description":{"value":"A work description"},"subjects":["Science fiction"],"authors":[{"author":{"key":"/authors/OL1A"}}]}"""; private const string WORK_JSON = """{"key":"/works/OL200W","title":"Work Title","first_publish_date":"2001-01-01","description":{"value":"A work description"},"subjects":["Science fiction"],"authors":[{"author":{"key":"/authors/OL1A"}}]}""";
private const string AUTHOR_JSON = """{"key":"/authors/OL1A","name":"Test Author"}"""; private const string AUTHOR_JSON = """{"key":"/authors/OL1A","name":"Test Author"}""";
private const string RATINGS_JSON = """{"summary":{"average":4.2,"count":100}}"""; private const string RATINGS_JSON = """{"summary":{"average":4.2,"count":100}}""";
private const string EDITIONS_JSON = """{"entries":[{"key":"/books/OL100M","title":"Edition Title","languages":[{"key":"/languages/eng"}]}]}"""; private const string EDITIONS_JSON = """{"entries":[{"key":"/books/OL100M","title":"Edition Title","languages":[{"key":"/languages/eng"}]}]}""";
[Fact] [Fact]
@@ -53,16 +49,17 @@ public class OpenLibraryBookMetadataProviderTests
} }
[Fact] [Fact]
public void SupportedLibraryType_WhenCalled_ShouldReturnBook() public void SupportedLibraryTypes_WhenCalled_ShouldReturnBook()
{ {
// Arrange // Arrange
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
// Act // Act
LibraryType result = sut.SupportedLibraryType; IReadOnlyList<LibraryType> result = sut.SupportedLibraryTypes;
// Assert // Assert
Assert.Equal(LibraryType.Book, result); Assert.Single(result);
Assert.Equal(LibraryType.Book, result[0]);
} }
[Fact] [Fact]
@@ -442,7 +439,8 @@ public class OpenLibraryBookMetadataProviderTests
private OpenLibraryBookMetadataProvider CreateProvider(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null) private OpenLibraryBookMetadataProvider CreateProvider(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null)
{ {
OpenLibrarySettingsDto runtimeSettings = settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero); OpenLibrarySettingsDto runtimeSettings = settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero);
OpenLibraryHttpClient openLibraryHttpClient = new(new HttpClient(handler), runtimeSettings); OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), runtimeSettings);
return new OpenLibraryBookMetadataProvider(openLibraryHttpClient, runtimeSettings); OpenLibraryHttpClient openLibraryHttpClient = new(new HttpClient(handler), settingsProvider);
return new OpenLibraryBookMetadataProvider(openLibraryHttpClient, settingsProvider);
} }
} }
@@ -2,7 +2,6 @@
using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Metadata; using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.OpenLibrary.Common.DependencyInjection;
using Lumina.Plugins.OpenLibrary.Core; using Lumina.Plugins.OpenLibrary.Core;
using Lumina.Plugins.OpenLibrary.Core.Api; using Lumina.Plugins.OpenLibrary.Core.Api;
using Lumina.Plugins.OpenLibrary.Core.Settings; using Lumina.Plugins.OpenLibrary.Core.Settings;
@@ -10,7 +9,6 @@ using Microsoft.Extensions.DependencyInjection;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion #endregion
namespace Lumina.Plugins.OpenLibrary.UnitTests.Core; namespace Lumina.Plugins.OpenLibrary.UnitTests.Core;
@@ -131,7 +129,7 @@ public class OpenLibraryPluginTests
ServiceProvider serviceProvider = services.BuildServiceProvider(); ServiceProvider serviceProvider = services.BuildServiceProvider();
// Assert // Assert
Assert.NotNull(serviceProvider.GetKeyedService<IRemoteMetadataProvider>(OpenLibraryPlugin.s_pluginId)); Assert.NotNull(serviceProvider.GetKeyedService<IMetadataProvider>(OpenLibraryPlugin.s_pluginId));
Assert.NotNull(serviceProvider.GetService<OpenLibraryHttpClient>()); Assert.NotNull(serviceProvider.GetService<OpenLibraryHttpClient>());
} }
} }