diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs new file mode 100644 index 00000000..d102ba55 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; +using Lumina.Plugins.OpenLibrary.Core; +using Lumina.Plugins.OpenLibrary.Core.Api; +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; + +/// +/// Provides extension methods for registering the Open Library metadata provider services. +/// +internal static class OpenLibraryServices +{ + /// + /// Registers the Open Library book metadata provider and its dependencies, associated with the plugin that provides it. + /// + /// The service collection to register the services into. + /// The unique identifier of the plugin that provides the metadata. + /// Action used to configure the . + /// The service collection, for chaining. + internal static IServiceCollection AddOpenLibraryBookMetadataProvider(this IServiceCollection services, Guid pluginId, Action? settingsCallback = null) + { + ArgumentNullException.ThrowIfNull(services); + + // Build the runtime settings 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); + + IPluginSettingsStore? settingsStore = serviceProvider.GetService(); + if (settingsStore is not null) + { + IReadOnlyDictionary? storedSettings = settingsStore.GetSettingsAsync(pluginId, CancellationToken.None).GetAwaiter().GetResult(); + if (storedSettings is not null) + OpenLibrarySettingsLoader.Apply(openLibrarySettings, storedSettings); + } + + return openLibrarySettings; + }); + + services.AddHttpClient(); + + // Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IRemoteMetadataProvider implementations. + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryAuthorResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryAuthorResponse.cs new file mode 100644 index 00000000..d9c9f1a7 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryAuthorResponse.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an author from the Open Library API. +/// +internal sealed record OpenLibraryAuthorResponse +{ + /// + /// Gets the key of the author. + /// + [JsonPropertyName("key")] + public string? Key { get; init; } + + /// + /// Gets the name of the author. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the personal name of the author. + /// + [JsonPropertyName("personal_name")] + public string? PersonalName { get; init; } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryEditionResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryEditionResponse.cs new file mode 100644 index 00000000..ea5fa21a --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryEditionResponse.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an edition from the Open Library API. +/// +internal sealed record OpenLibraryEditionResponse +{ + /// + /// Gets the key of the edition. + /// + [JsonPropertyName("key")] + public string? Key { get; init; } + + /// + /// Gets the title of the edition. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the subtitle of the edition. + /// + [JsonPropertyName("subtitle")] + public string? Subtitle { get; init; } + + /// + /// Gets the notes of the edition. + /// + [JsonPropertyName("notes")] + public JsonElement Notes { get; init; } + + /// + /// Gets the publication date of the edition. + /// + [JsonPropertyName("publish_date")] + public string? PublishDate { get; init; } + + /// + /// Gets the publishers of the edition. + /// + [JsonPropertyName("publishers")] + public List Publishers { get; init; } = []; + + /// + /// Gets the publication places of the edition. + /// + [JsonPropertyName("publish_places")] + public List PublishPlaces { get; init; } = []; + + /// + /// Gets the number of pages of the edition. + /// + [JsonPropertyName("number_of_pages")] + public int? NumberOfPages { get; init; } + + /// + /// Gets the physical format of the edition. + /// + [JsonPropertyName("physical_format")] + public string? PhysicalFormat { get; init; } + + /// + /// Gets the name of the edition. + /// + [JsonPropertyName("edition_name")] + public string? EditionName { get; init; } + + /// + /// Gets the series the edition belongs to. + /// + [JsonPropertyName("series")] + public List Series { get; init; } = []; + + /// + /// Gets the volume of the edition within its series. + /// + [JsonPropertyName("volume")] + public string? Volume { get; init; } + + /// + /// Gets the ISBN-10 identifiers of the edition. + /// + [JsonPropertyName("isbn_10")] + public List Isbn10 { get; init; } = []; + + /// + /// Gets the ISBN-13 identifiers of the edition. + /// + [JsonPropertyName("isbn_13")] + public List Isbn13 { get; init; } = []; + + /// + /// Gets the LCCN identifiers of the edition. + /// + [JsonPropertyName("lccn")] + public List Lccn { get; init; } = []; + + /// + /// Gets the OCLC numbers of the edition. + /// + [JsonPropertyName("oclc_numbers")] + public List OclcNumbers { get; init; } = []; + + /// + /// Gets the external identifiers of the edition, keyed by identifier name. + /// + [JsonPropertyName("identifiers")] + public JsonElement Identifiers { get; init; } + + /// + /// Gets the source records of the edition. + /// + [JsonPropertyName("source_records")] + public List SourceRecords { get; init; } = []; + + /// + /// Gets the languages of the edition. + /// + [JsonPropertyName("languages")] + public List Languages { get; init; } = []; + + /// + /// Gets the authors of the edition. + /// + [JsonPropertyName("authors")] + public List Authors { get; init; } = []; + + /// + /// Gets the works the edition belongs to. + /// + [JsonPropertyName("works")] + public List Works { get; init; } = []; + + /// + /// Gets the contributions of the edition. + /// + [JsonPropertyName("contributions")] + public List Contributions { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryEditionsResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryEditionsResponse.cs new file mode 100644 index 00000000..7178fffa --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryEditionsResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the editions of a work from the Open Library API. +/// +internal sealed record OpenLibraryEditionsResponse +{ + /// + /// Gets the editions of the work. + /// + [JsonPropertyName("entries")] + public List Entries { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryKeyReferenceResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryKeyReferenceResponse.cs new file mode 100644 index 00000000..fc6a40f8 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryKeyReferenceResponse.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a reference to a resource of the Open Library API by its key. +/// +internal sealed record OpenLibraryKeyReferenceResponse +{ + /// + /// Gets the key of the referenced resource. + /// + [JsonPropertyName("key")] + public string? Key { get; init; } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryRatingSummaryResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryRatingSummaryResponse.cs new file mode 100644 index 00000000..41f3bd70 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryRatingSummaryResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the summary of the ratings of a work from the Open Library API. +/// +internal sealed record OpenLibraryRatingSummaryResponse +{ + /// + /// Gets the average rating of the work. + /// + [JsonPropertyName("average")] + public decimal? Average { get; init; } + + /// + /// Gets the number of ratings of the work. + /// + [JsonPropertyName("count")] + public int? Count { get; init; } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryRatingsResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryRatingsResponse.cs new file mode 100644 index 00000000..76163774 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryRatingsResponse.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the ratings of a work from the Open Library API. +/// +internal sealed record OpenLibraryRatingsResponse +{ + /// + /// Gets the summary of the ratings of the work. + /// + [JsonPropertyName("summary")] + public OpenLibraryRatingSummaryResponse? Summary { get; init; } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibrarySearchDocumentResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibrarySearchDocumentResponse.cs new file mode 100644 index 00000000..ad166095 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibrarySearchDocumentResponse.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a search document from the Open Library API. +/// +internal sealed record OpenLibrarySearchDocumentResponse +{ + /// + /// Gets the key of the search document. + /// + [JsonPropertyName("key")] + public string? Key { get; init; } + + /// + /// Gets the title of the search document. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the author names of the search document. + /// + [JsonPropertyName("author_name")] + public List AuthorNames { get; init; } = []; + + /// + /// Gets the author keys of the search document. + /// + [JsonPropertyName("author_key")] + public List AuthorKeys { get; init; } = []; + + /// + /// Gets the first publication year of the search document. + /// + [JsonPropertyName("first_publish_year")] + public int? FirstPublishYear { get; init; } + + /// + /// Gets the edition keys of the search document. + /// + [JsonPropertyName("edition_key")] + public List EditionKeys { get; init; } = []; + + /// + /// Gets the ISBNs of the search document. + /// + [JsonPropertyName("isbn")] + public List Isbns { get; init; } = []; + + /// + /// Gets the languages of the search document. + /// + [JsonPropertyName("language")] + public List Languages { get; init; } = []; + + /// + /// Gets the publishers of the search document. + /// + [JsonPropertyName("publisher")] + public List Publishers { get; init; } = []; + + /// + /// Gets the subjects of the search document. + /// + [JsonPropertyName("subject")] + public List Subjects { get; init; } = []; + + /// + /// Gets the publication places of the search document. + /// + [JsonPropertyName("publish_place")] + public List PublishPlaces { get; init; } = []; + + /// + /// Gets the median number of pages of the search document. + /// + [JsonPropertyName("number_of_pages_median")] + public int? NumberOfPagesMedian { get; init; } + + /// + /// Gets the average rating of the search document. + /// + [JsonPropertyName("ratings_average")] + public decimal? RatingsAverage { get; init; } + + /// + /// Gets the number of ratings of the search document. + /// + [JsonPropertyName("ratings_count")] + public int? RatingsCount { get; init; } + + /// + /// Gets the Amazon identifiers of the search document. + /// + [JsonPropertyName("id_amazon")] + public List AmazonIds { get; init; } = []; + + /// + /// Gets the Goodreads identifiers of the search document. + /// + [JsonPropertyName("id_goodreads")] + public List GoodreadsIds { get; init; } = []; + + /// + /// Gets the Google identifiers of the search document. + /// + [JsonPropertyName("id_google")] + public List GoogleIds { get; init; } = []; + + /// + /// Gets the LibraryThing identifiers of the search document. + /// + [JsonPropertyName("id_librarything")] + public List LibraryThingIds { get; init; } = []; + + /// + /// Gets the LCCN identifiers of the search document. + /// + [JsonPropertyName("lccn")] + public List Lccn { get; init; } = []; + + /// + /// Gets the OCLC identifiers of the search document. + /// + [JsonPropertyName("oclc")] + public List Oclc { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibrarySearchResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibrarySearchResponse.cs new file mode 100644 index 00000000..0174289a --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibrarySearchResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a search from the Open Library API. +/// +internal sealed record OpenLibrarySearchResponse +{ + /// + /// Gets the documents that match the search. + /// + [JsonPropertyName("docs")] + public List Documents { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponse.cs new file mode 100644 index 00000000..4d0bb561 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an author reference within a work from the Open Library API. +/// +internal sealed record OpenLibraryWorkAuthorResponse +{ + /// + /// Gets the author of the work. + /// + [JsonPropertyName("author")] + public OpenLibraryKeyReferenceResponse? Author { get; init; } + + /// + /// Gets the key of the author reference. + /// + [JsonPropertyName("key")] + public string? Key { get; init; } // Older records can contain a direct key rather than an author wrapper. +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryWorkResponse.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryWorkResponse.cs new file mode 100644 index 00000000..3a1ca9c1 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/Contracts/Responses/OpenLibraryWorkResponse.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a work from the Open Library API. +/// +internal sealed record OpenLibraryWorkResponse +{ + /// + /// Gets the key of the work. + /// + [JsonPropertyName("key")] + public string? Key { get; init; } + + /// + /// Gets the title of the work. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the original title of the work. + /// + [JsonPropertyName("original_title")] + public string? OriginalTitle { get; init; } + + /// + /// Gets the description of the work. + /// + [JsonPropertyName("description")] + public JsonElement Description { get; init; } + + /// + /// Gets the first publication date of the work. + /// + [JsonPropertyName("first_publish_date")] + public string? FirstPublishDate { get; init; } + + /// + /// Gets the subjects of the work. + /// + [JsonPropertyName("subjects")] + public List Subjects { get; init; } = []; + + /// + /// Gets the genres of the work. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the authors of the work. + /// + [JsonPropertyName("authors")] + public List Authors { get; init; } = []; + + /// + /// Gets the original languages of the work. + /// + [JsonPropertyName("original_languages")] + public List OriginalLanguages { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/Models/DTO/Settings/OpenLibrarySettingsDto.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/DTO/Settings/OpenLibrarySettingsDto.cs new file mode 100644 index 00000000..44feda1e --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/Models/DTO/Settings/OpenLibrarySettingsDto.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; + +/// +/// Data transfer object for the settings that configure the Open Library metadata plugin. +/// +internal sealed class OpenLibrarySettingsDto +{ + /// + /// Gets or sets the user agent sent with every request to the Open Library API. + /// + public string UserAgent { get; set; } = "Lumina-OpenLibrary/1.0"; + + /// + /// Gets or sets the contact email sent with every request to the Open Library API. + /// + public string? ContactEmail { get; set; } + + /// + /// Gets or sets the maximum number of results returned by a single search. + /// + public int SearchResultLimit { get; set; } = 10; + + /// + /// Gets or sets the maximum number of editions fetched for a single work. + /// + public int WorkEditionLimit { get; set; } = 50; + + /// + /// Gets or sets the minimum interval between consecutive requests to the Open Library API. + /// + public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.1); +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs new file mode 100644 index 00000000..7749f4a2 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs @@ -0,0 +1,252 @@ +#region ========================================================================= USING ===================================================================================== +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 System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +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.OpenLibrary.Core.Api; + +/// +/// HTTP client that calls the Open Library API and deserializes its JSON responses into typed response models. +/// +internal sealed class OpenLibraryHttpClient +{ + private readonly HttpClient _httpClient; + private readonly OpenLibrarySettingsDto _openLibrarySettings; + private readonly SemaphoreSlim _requestGate = new(1, 1); + private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue; + + private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web) + { + NumberHandling = JsonNumberHandling.AllowReadingFromString + }; + + private const string SEARCH_FIELDS = + "key,title,author_name,author_key,first_publish_year,edition_key,isbn," + + "language,publisher,subject,publish_place,number_of_pages_median," + + "ratings_average,ratings_count,id_amazon,id_goodreads,id_google," + + "id_librarything,lccn,oclc"; + + /// + /// Initializes a new instance of the class. + /// + /// The used to send requests to the Open Library API. + /// The settings that configure the Open Library API requests. + public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsDto openLibrarySettings) + { + _httpClient = httpClient; + _openLibrarySettings = openLibrarySettings; + + _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!; + } + + /// + /// Gets an edition by its ISBN. + /// + /// The ISBN of the edition to get. + /// Cancellation token that can be used to stop the execution. + /// The edition, or when no edition was found for the ISBN. + public Task GetEditionByIsbnAsync(string isbn, CancellationToken cancellationToken) + { + string normalized = OpenLibraryMapper.NormalizeIsbn(isbn); + return GetJsonOrNullAsync($"isbn/{Uri.EscapeDataString(normalized)}.json", cancellationToken); + } + + /// + /// Gets an edition by its Open Library edition identifier. + /// + /// The Open Library edition identifier of the edition to get. + /// Cancellation token that can be used to stop the execution. + /// The edition, or when no edition was found for the identifier. + public Task GetEditionAsync(string editionId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync($"books/{Uri.EscapeDataString(NormalizeOlid(editionId, 'M'))}.json", cancellationToken); + } + + /// + /// Gets a work by its Open Library work identifier. + /// + /// The Open Library work identifier of the work to get. + /// Cancellation token that can be used to stop the execution. + /// The work, or when no work was found for the identifier. + public Task GetWorkAsync(string workId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync($"works/{Uri.EscapeDataString(NormalizeOlid(workId, 'W'))}.json", cancellationToken); + } + + /// + /// Gets an author by its Open Library author identifier. + /// + /// The Open Library author identifier of the author to get. + /// Cancellation token that can be used to stop the execution. + /// The author, or when no author was found for the identifier. + public Task GetAuthorAsync(string authorId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync($"authors/{Uri.EscapeDataString(NormalizeOlid(authorId, 'A'))}.json", cancellationToken); + } + + /// + /// Gets the ratings of a work by its Open Library work identifier. + /// + /// The Open Library work identifier of the work to get the ratings for. + /// Cancellation token that can be used to stop the execution. + /// The ratings, or when no ratings were found for the work. + public Task GetRatingsAsync(string workId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync($"works/{Uri.EscapeDataString(NormalizeOlid(workId, 'W'))}/ratings.json", cancellationToken); + } + + /// + /// Gets a list of editions for a work by its Open Library work identifier. + /// + /// The Open Library work identifier of the work to get the editions for. + /// The maximum number of editions to get. + /// Cancellation token that can be used to stop the execution. + /// The list of editions for the work. + public async Task> GetEditionsAsync(string workId, int limit, CancellationToken cancellationToken) + { + OpenLibraryEditionsResponse? response = await GetJsonOrNullAsync( + $"works/{Uri.EscapeDataString(NormalizeOlid(workId, 'W'))}/editions.json" + + $"?limit={Math.Clamp(limit, 1, 1000).ToString(CultureInfo.InvariantCulture)}", + cancellationToken) + .ConfigureAwait(false); + + return response?.Entries ?? []; + } + + /// + /// Searches Open Library for books matching the lookup. + /// + /// The lookup describing the book to search for. + /// The maximum number of search results to return. + /// Cancellation token that can be used to stop the execution. + /// The list of search results for the lookup. + public async Task> SearchAsync(BookMetadataLookupDto lookup, int limit, CancellationToken cancellationToken) + { + List> parameters = []; + + string? isbn = lookup.Isbn; + string? title = lookup.Title; + string? author = lookup.Author; + string? languageCode = lookup.LanguageCode; + + if (!string.IsNullOrWhiteSpace(isbn)) + parameters.Add(new("isbn", OpenLibraryMapper.NormalizeIsbn(isbn))); + + if (!string.IsNullOrWhiteSpace(title)) + parameters.Add(new("title", title.Trim())); + + if (!string.IsNullOrWhiteSpace(author)) + parameters.Add(new("author", author.Trim())); + + if (!string.IsNullOrWhiteSpace(languageCode)) + parameters.Add(new("language", languageCode.Trim())); + + parameters.Add(new("fields", SEARCH_FIELDS)); + parameters.Add(new("limit", Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture))); + + string query = string.Join("&", parameters.Select(pair => $"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value)}")); + + OpenLibrarySearchResponse? response = await GetJsonOrNullAsync($"search.json?{query}", cancellationToken).ConfigureAwait(false); + + return response?.Documents ?? []; + } + + /// + /// Gets the JSON resource at the given relative URL and deserializes it into . + /// + /// The type to deserialize the JSON response into. + /// The URL of the resource, relative to the base address. + /// Cancellation token that can be used to stop the execution. + /// The deserialized resource, or when the resource was not found. + /// Transient failures and rate limiting are handled by retrying the request up to three times. + private async Task GetJsonOrNullAsync(string relativeUrl, CancellationToken cancellationToken) + { + for (int attempt = 0; attempt < 3; attempt++) + { + using HttpResponseMessage response = await SendAsync(relativeUrl, cancellationToken).ConfigureAwait(false); + + if (response.StatusCode == HttpStatusCode.NotFound) + return default; + + if (response.IsSuccessStatusCode) + { + await using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + return await JsonSerializer.DeserializeAsync(stream, s_serializerOptions, cancellationToken).ConfigureAwait(false); + } + + if (attempt < 2 && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500)) + { + TimeSpan retryDelay = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt)); + await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false); + continue; + } + + response.EnsureSuccessStatusCode(); + } + + return default; + } + + /// + /// Sends a GET request to the Open Library API, throttled to respect the configured minimum request interval. + /// + /// The URL of the resource, relative to the base address. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message for the request. + private async Task SendAsync(string relativeUrl, CancellationToken cancellationToken) + { + await _requestGate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + DateTimeOffset earliestNextRequest = _lastRequestAt + _openLibrarySettings.MinimumRequestInterval; + TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow; + if (delay > TimeSpan.Zero) + await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + + HttpRequestMessage request = new(HttpMethod.Get, relativeUrl); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + _lastRequestAt = DateTimeOffset.UtcNow; + return response; + } + finally + { + _requestGate.Release(); + } + } + + /// + /// Normalizes a raw Open Library identifier into its canonical OLID form. + /// + /// The raw Open Library identifier to normalize. + /// The suffix the OLID must end with, for example M for editions. + /// The canonical OLID. + /// The value is not a valid Open Library identifier. + private static string NormalizeOlid(string value, char expectedSuffix) + { + string id = value.Trim().TrimEnd('/').Split('/').Last().ToUpperInvariant(); + if (id.Length < 4 || !id.StartsWith("OL", StringComparison.Ordinal) || id[^1] != expectedSuffix || !id.AsSpan(2, id.Length - 3).ToString().All(char.IsDigit)) + throw new ArgumentException($"'{value}' is not a valid Open Library {expectedSuffix} identifier.", nameof(value)); + + return id; + } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs new file mode 100644 index 00000000..041f7146 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs @@ -0,0 +1,532 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.Json; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Core.Mapping; + +/// +/// Maps Open Library API responses into the application's book request DTOs. +/// +internal static partial class OpenLibraryMapper +{ + /// + /// Matches a contribution in the form Name (Role). + /// + [GeneratedRegex(@"^(?.+?)\s*\((?[^)]+)\)\s*$")] + private static partial Regex ContributorPattern(); + + /// + /// Matches a volume number in a series or volume string. + /// + [GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?\d+)\b", RegexOptions.IgnoreCase)] + private static partial Regex VolumePattern(); + + /// + /// Matches a four digit year. + /// + [GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")] + private static partial Regex YearPattern(); + + private static readonly HashSet s_genreWords = new(StringComparer.OrdinalIgnoreCase) + { + "adventure", "biography", "children's literature", "comics", "crime", + "drama", "dystopian", "erotica", "essay", "fantasy", "fiction", + "historical fiction", "history", "horror", "humor", "memoir", "mystery", + "nonfiction", "poetry", "romance", "science fiction", "thriller", + "travel", "young adult" + }; + + /// + /// Maps the edition, work, author, rating, and search data into a full book request. + /// + /// The lookup describing the book to map. + /// The edition data, or when no edition was found. + /// The work data, or when no work was found. + /// The authors of the book. + /// The ratings of the book, or when no ratings were found. + /// The search document used as a fallback source of data, or . + /// The mapped book request. + public static AddBookRequest MapDetailed( + BookMetadataLookupDto lookup, + OpenLibraryEditionResponse? edition, + OpenLibraryWorkResponse? work, + IReadOnlyList authors, + OpenLibraryRatingsResponse? ratings, + OpenLibrarySearchDocumentResponse? fallback = null) + { + List subjects = DistinctValues(work?.Subjects ?? fallback?.Subjects ?? []); + List explicitGenres = DistinctValues(work?.Genres ?? []); + List genreNames = explicitGenres.Count > 0 ? explicitGenres : [.. subjects.Where(LooksLikeGenre)]; + + (DateOnly? Date, int? Year) originalRelease = ParseOpenLibraryDate(work?.FirstPublishDate); + int? originalYear = originalRelease.Date?.Year ?? originalRelease.Year ?? fallback?.FirstPublishYear; + (DateOnly? Date, int? Year) editionRelease = ParseOpenLibraryDate(edition?.PublishDate); + + string? workId = ExtractOlid(work?.Key, 'W') ?? ExtractOlid(fallback?.Key, 'W'); + string? editionId = ExtractOlid(edition?.Key, 'M') ?? fallback?.EditionKeys.FirstOrDefault(); + + string? currentLanguageCode = ExtractLanguageCode(edition?.Languages.FirstOrDefault()?.Key) ?? fallback?.Languages.FirstOrDefault(); + string? originalLanguageCode = ExtractLanguageCode(work?.OriginalLanguages.FirstOrDefault()?.Key); + + Dictionary> identifiers = ReadIdentifiers(edition?.Identifiers ?? default); + string? asin = FirstIdentifier(identifiers, "amazon", "asin") ?? FirstSourceIdentifier(edition?.SourceRecords, "amazon") ?? fallback?.AmazonIds.FirstOrDefault(); + string? goodreadsId = FirstIdentifier(identifiers, "goodreads") ?? fallback?.GoodreadsIds.FirstOrDefault(); + string? libraryThingId = FirstIdentifier(identifiers, "librarything") ?? fallback?.LibraryThingIds.FirstOrDefault(); + string? googleBooksId = FirstIdentifier(identifiers, "google", "google_books") ?? FirstSourceIdentifier(edition?.SourceRecords, "google") ?? fallback?.GoogleIds.FirstOrDefault(); + string? barnesAndNobleId = FirstIdentifier(identifiers, "barnesandnoble", "barnes_and_noble", "bn"); + string? appleBooksId = FirstIdentifier(identifiers, "apple", "apple_books", "ibooks"); + + List isbns = MapIsbns(lookup.Isbn, edition, fallback); + List contributors = MapContributors(authors, edition?.Contributions, fallback?.AuthorNames); + List mappedRatings = MapRatings(ratings, fallback); + + string? title = FirstNotEmpty(edition?.Title, work?.Title, fallback?.Title); + string? description = ReadText(work?.Description ?? default) ?? ReadText(edition?.Notes ?? default); + string? releaseCountry = edition?.PublishPlaces.FirstOrDefault() ?? fallback?.PublishPlaces.FirstOrDefault(); + string? releaseVersion = edition?.EditionName; + + return new AddBookRequest( + lookup.LibraryId, + lookup.Path, + new WrittenContentMetadataDto( + title, + work?.OriginalTitle, + description, + new ReleaseInfoDto( + originalRelease.Date, + originalYear, + editionRelease.Date, + editionRelease.Date?.Year ?? editionRelease.Year, + NullIfWhiteSpace(releaseCountry), + NullIfWhiteSpace(releaseVersion)), + genreNames.Select(name => new GenreDto(name)).ToList(), + subjects.Select(name => new TagDto(name)).ToList(), + MapLanguage(currentLanguageCode), + MapLanguage(originalLanguageCode), + edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(), + edition?.NumberOfPages ?? fallback?.NumberOfPagesMedian), + MapFormat(edition?.PhysicalFormat), + NullIfWhiteSpace(edition?.EditionName), + ParseVolumeNumber(edition?.Volume, edition?.Series.FirstOrDefault()), + MapSeries(edition?.Series.FirstOrDefault()), + NullIfWhiteSpace(asin), + NullIfWhiteSpace(goodreadsId), + NullIfWhiteSpace(edition?.Lccn.FirstOrDefault() ?? fallback?.Lccn.FirstOrDefault()), + NullIfWhiteSpace(edition?.OclcNumbers.FirstOrDefault() ?? fallback?.Oclc.FirstOrDefault()), + editionId ?? workId, + NullIfWhiteSpace(libraryThingId), + NullIfWhiteSpace(googleBooksId), + NullIfWhiteSpace(barnesAndNobleId), + NullIfWhiteSpace(appleBooksId), + isbns, + contributors, + mappedRatings); + } + + /// + /// Maps a search document into a book request candidate. + /// + /// The lookup describing the book to map. + /// The search document to map. + /// The mapped book request candidate. + public static AddBookRequest MapSearchCandidate(BookMetadataLookupDto lookup, OpenLibrarySearchDocumentResponse document) + { + return MapDetailed(lookup, null, null, [], null, document); + } + + /// + /// Normalizes an ISBN into its canonical form without separators or whitespace. + /// + /// The ISBN to normalize. + /// The normalized ISBN. + /// The ISBN is empty, white space, or contains invalid characters. + public static string NormalizeIsbn(string isbn) + { + ArgumentException.ThrowIfNullOrWhiteSpace(isbn); + string normalized = new string([.. isbn.Where(character => character is not '-' && !char.IsWhiteSpace(character))]).ToUpperInvariant(); + + if ((normalized.Length != 10 && normalized.Length != 13) || + normalized[..^1].Any(character => !char.IsDigit(character)) || + (!char.IsDigit(normalized[^1]) && !(normalized.Length == 10 && normalized[^1] == 'X'))) + throw new ArgumentException("The ISBN must contain 10 or 13 valid characters.", nameof(isbn)); + + return normalized; + } + + /// + /// Extracts the canonical OLID from an Open Library key, when it matches the expected suffix. + /// + /// The Open Library key to extract the OLID from. + /// The suffix the OLID must end with, for example W for works. + /// The canonical OLID, or when the key does not contain a matching OLID. + public static string? ExtractOlid(string? key, char expectedSuffix) + { + if (string.IsNullOrWhiteSpace(key)) + return null; + + string candidate = key.Trim().TrimEnd('/').Split('/').Last().ToUpperInvariant(); + return candidate.StartsWith("OL", StringComparison.Ordinal) && candidate.EndsWith(expectedSuffix) && candidate.Length > 3 ? candidate : null; + } + + /// + /// Maps a physical format string into a book format enum value. + /// + /// The physical format string to map. + /// The mapped book format, or when the format is not recognized. + public static BookFormat? MapFormat(string? physicalFormat) + { + if (string.IsNullOrWhiteSpace(physicalFormat)) + return null; + + string value = physicalFormat.Trim().ToLowerInvariant(); + if (value.Contains("mass market", StringComparison.Ordinal)) + return BookFormat.MassMarketPaperback; + if (value.Contains("trade paperback", StringComparison.Ordinal)) + return BookFormat.TradePaperback; + if (value.Contains("paperback", StringComparison.Ordinal) || value.Contains("softcover", StringComparison.Ordinal)) + return BookFormat.Paperback; + if (value.Contains("hardcover", StringComparison.Ordinal) || value.Contains("hard cover", StringComparison.Ordinal) || value.Contains("hardback", StringComparison.Ordinal) || value.Contains("clothbound", StringComparison.Ordinal)) + return BookFormat.Hardcover; + if (value.Contains("ebook", StringComparison.Ordinal) || value.Contains("e-book", StringComparison.Ordinal) || value.Contains("electronic", StringComparison.Ordinal)) + return BookFormat.eBook; + if (value.Contains("audiobook", StringComparison.Ordinal) || value.Contains("audio book", StringComparison.Ordinal) || value.Contains("audio cd", StringComparison.Ordinal) || value.Contains("audio cassette", StringComparison.Ordinal)) + return BookFormat.Audiobook; + if (value.Contains("large print", StringComparison.Ordinal)) + return BookFormat.LargePrint; + if (value.Contains("board book", StringComparison.Ordinal)) + return BookFormat.BoardBook; + if (value.Contains("spiral", StringComparison.Ordinal)) + return BookFormat.SpiralBound; + if (value.Contains("library binding", StringComparison.Ordinal)) + return BookFormat.LibraryBinding; + if (value.Contains("leather", StringComparison.Ordinal)) + return BookFormat.LeatherBound; + if (value.Contains("pop-up", StringComparison.Ordinal) || value.Contains("popup", StringComparison.Ordinal)) + return BookFormat.PopupBook; + return null; + } + + /// + /// Maps the ISBNs from the lookup, edition, and search document into ISBN DTOs, de-duplicating normalized values. + /// + /// The ISBN of the lookup. + /// The edition data to read the ISBNs from. + /// The search document to read the ISBNs from. + /// The mapped and de-duplicated ISBN DTOs. + private static List MapIsbns(string? lookupIsbn, OpenLibraryEditionResponse? edition, OpenLibrarySearchDocumentResponse? fallback) + { + List result = []; + HashSet seen = new(StringComparer.OrdinalIgnoreCase); + + void Add(string? raw, IsbnFormat? declaredFormat = null) + { + if (string.IsNullOrWhiteSpace(raw)) + return; + string normalized; + try + { + normalized = NormalizeIsbn(raw); + } + catch (ArgumentException) + { + return; + } + + if (!seen.Add(normalized)) + return; + IsbnFormat format = declaredFormat ?? (normalized.Length == 10 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13); + result.Add(new IsbnDto(normalized, format)); + } + + Add(lookupIsbn); + foreach (string isbn in edition?.Isbn10 ?? []) + Add(isbn, IsbnFormat.Isbn10); + foreach (string isbn in edition?.Isbn13 ?? []) + Add(isbn, IsbnFormat.Isbn13); + foreach (string isbn in fallback?.Isbns ?? []) + Add(isbn); + return result; + } + + /// + /// Maps the authors and contributions into contributor DTOs, de-duplicating identical name and role pairs. + /// + /// The authors of the book. + /// The contribution strings of the edition. + /// The author names from the search document. + /// The mapped contributor DTOs. + private static List MapContributors(IReadOnlyList authors, IReadOnlyList? contributions, IReadOnlyList? fallbackAuthors) + { + List result = []; + HashSet seen = new(StringComparer.OrdinalIgnoreCase); + + void Add(string? displayName, string? legalName, string role, string category) + { + if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}")) + return; + result.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), NullIfWhiteSpace(legalName)), new MediaContributorRoleDto(role, category))); + } + + foreach (OpenLibraryAuthorResponse author in authors) + Add(author.Name, author.PersonalName, "Author", "Writing"); + foreach (string authorName in fallbackAuthors ?? []) + Add(authorName, null, "Author", "Writing"); + + foreach (string contribution in contributions ?? []) + { + Match match = ContributorPattern().Match(contribution); + string name = match.Success ? match.Groups["name"].Value.Trim() : contribution.Trim(); + string role = match.Success ? match.Groups["role"].Value.Trim() : "Contributor"; + Add(name, null, role, ContributorCategory(role)); + } + return result; + } + + /// + /// Maps the ratings into a single Open Library rating DTO when an average or a count is present. + /// + /// The ratings of the work. + /// The search document to read the ratings from. + /// The mapped rating DTOs, or an empty list when no rating data was found. + private static List MapRatings(OpenLibraryRatingsResponse? ratings, OpenLibrarySearchDocumentResponse? fallback) + { + decimal? average = ratings?.Summary?.Average ?? fallback?.RatingsAverage; + int? count = ratings?.Summary?.Count ?? fallback?.RatingsCount; + if (average is null && count is null) + return []; + + return [new BookRatingDto(average, 5m, BookRatingSource.OpenLibrary, count)]; + } + + /// + /// Maps a language code into a language info DTO by matching it against known cultures. + /// + /// The raw language code to map. + /// The mapped language info, or when the code is empty. + private static LanguageInfoDto? MapLanguage(string? rawCode) + { + if (string.IsNullOrWhiteSpace(rawCode)) + return null; + + string code = rawCode.Trim().ToLowerInvariant(); + IEnumerable cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures) + .Concat(CultureInfo.GetCultures(CultureTypes.NeutralCultures)); + + CultureInfo? culture = cultures.FirstOrDefault(candidate => + string.Equals(candidate.TwoLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase) || + string.Equals(candidate.ThreeLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase)); + + return culture is null ? new LanguageInfoDto(code, code, null) : new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName); + } + + /// + /// Maps a series string into a book series DTO. + /// + /// The series string to map. + /// The mapped book series, or when the string is empty. + private static BookSeriesDto? MapSeries(string? series) + { + string? value = NullIfWhiteSpace(series); + return value is null ? null : new BookSeriesDto(value); + } + + /// + /// Parses a volume number from the first candidate that contains one. + /// + /// The strings that may contain a volume number. + /// The parsed volume number, or when no candidate contains one. + private static int? 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)) + return number; + } + return null; + } + + /// + /// Parses an Open Library date string into a date and a year. + /// + /// The date string to parse. + /// The parsed date and year, or values when the string could not be parsed. + private static (DateOnly? Date, int? Year) ParseOpenLibraryDate(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return (null, null); + + DateTimeStyles styles = DateTimeStyles.AllowWhiteSpaces; + string[] formats = + [ + "yyyy-MM-dd", "yyyy-M-d", "MMMM d, yyyy", "MMM d, yyyy", + "d MMMM yyyy", "d MMM yyyy" + ]; + + if (DateOnly.TryParseExact(value.Trim(), formats, CultureInfo.InvariantCulture, styles, out DateOnly exact)) + return (exact, exact.Year); + + Match yearMatch = YearPattern().Match(value); + return yearMatch.Success && int.TryParse(yearMatch.Value, out int year) ? (null, year) : (null, null); + } + + /// + /// Reads the text out of a JSON element that is either a plain string or an object with a value property. + /// + /// The JSON element to read. + /// The text, or when the element does not contain readable text. + private static string? ReadText(JsonElement element) + { + return element.ValueKind switch + { + JsonValueKind.String => NullIfWhiteSpace(element.GetString()), + JsonValueKind.Object when element.TryGetProperty("value", out JsonElement value) => ReadText(value), + _ => null + }; + } + + /// + /// Reads an identifiers object into a dictionary keyed by identifier name. + /// + /// The JSON element to read. + /// The identifier values keyed by identifier name. + private static Dictionary> ReadIdentifiers(JsonElement element) + { + Dictionary> result = new(StringComparer.OrdinalIgnoreCase); + if (element.ValueKind != JsonValueKind.Object) + return result; + + foreach (JsonProperty property in element.EnumerateObject()) + { + IEnumerable values = property.Value.ValueKind switch + { + JsonValueKind.String => [property.Value.GetString()], + JsonValueKind.Array => property.Value.EnumerateArray() + .Where(item => item.ValueKind == JsonValueKind.String) + .Select(item => item.GetString()), + _ => [] + }; + + result[property.Name] = [.. values + .Where(value => !string.IsNullOrWhiteSpace(value)) + .Select(value => value!)]; + } + + return result; + } + + /// + /// Gets the first value of the first identifier key that has values. + /// + /// The identifiers to read from. + /// The identifier keys to try, in order. + /// The first value, or when none of the keys have values. + private static string? FirstIdentifier(IReadOnlyDictionary> identifiers, params string[] keys) + { + foreach (string key in keys) + if (identifiers.TryGetValue(key, out List? values) && values.Count > 0) + return values[0]; + + return null; + } + + /// + /// Gets the identifier value from a source record prefixed with the given source name. + /// + /// The source records to read from. + /// The source name prefix to match. + /// The identifier value, or when no source record matches. + private static string? FirstSourceIdentifier(IReadOnlyList? sourceRecords, string source) + { + string prefix = source + ":"; + string? match = sourceRecords?.FirstOrDefault(value => value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); + return match?[prefix.Length..]; + } + + /// + /// Extracts the language code from an Open Library language key. + /// + /// The language key to extract the code from. + /// The language code, or when the key is empty. + private static string? ExtractLanguageCode(string? key) + { + return string.IsNullOrWhiteSpace(key) ? null : key.Trim().TrimEnd('/').Split('/').Last(); + } + + /// + /// Trims, filters, and de-duplicates the given values, ignoring case. + /// + /// The values to process. + /// The processed values. + private static List DistinctValues(IEnumerable values) + { + return [.. values.Select(value => value.Trim()).Where(value => value.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Determines whether a subject is likely to describe a genre. + /// + /// The subject to check. + /// when the subject is a known genre word or ends in fiction or literature. + private static bool LooksLikeGenre(string subject) + { + return s_genreWords.Contains(subject) || + subject.EndsWith(" fiction", StringComparison.OrdinalIgnoreCase) || + subject.EndsWith(" literature", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Maps a contributor role into a contributor category. + /// + /// The role to categorize. + /// The mapped contributor category. + private static string ContributorCategory(string role) + { + if (role.Contains("illustr", StringComparison.OrdinalIgnoreCase) || + role.Contains("artist", StringComparison.OrdinalIgnoreCase)) + return "Art"; + if (role.Contains("translat", StringComparison.OrdinalIgnoreCase)) + return "Translation"; + if (role.Contains("edit", StringComparison.OrdinalIgnoreCase) || + role.Contains("author", StringComparison.OrdinalIgnoreCase) || + role.Contains("writer", StringComparison.OrdinalIgnoreCase)) + return "Writing"; + if (role.Contains("narrat", StringComparison.OrdinalIgnoreCase)) + return "Performance"; + return "Other"; + } + + /// + /// Gets the first value that is not empty or white space. + /// + /// The values to check, in order. + /// The first non-empty value, or when all values are empty. + private static string? FirstNotEmpty(params string?[] values) + { + return values.Select(NullIfWhiteSpace).FirstOrDefault(value => value is not null); + } + + /// + /// Returns the trimmed value, or when the value is empty or white space. + /// + /// The value to process. + /// The trimmed value, or . + private static string? NullIfWhiteSpace(string? value) + { + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs new file mode 100644 index 00000000..570b837d --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs @@ -0,0 +1,364 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +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 System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Core; + +/// +/// Provides book metadata from the Open Library by resolving lookups into book metadata DTOs. +/// +internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider +{ + private readonly OpenLibraryHttpClient _openLibraryHttpClient; + private readonly OpenLibrarySettingsDto _openLibrarySettings; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "Open Library"; + + /// + /// Gets the media library type this metadata provider supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => true; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP client used to call the Open Library API. + /// The settings that configure the Open Library API requests. + public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsDto openLibrarySettings) + { + _openLibraryHttpClient = openLibraryHttpClient; + _openLibrarySettings = openLibrarySettings; + } + + /// + /// Searches for the metadata of the media item described by . + /// + /// The lookup describing the media item to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of metadata candidates found for the media item. + public async Task> GetSearchResultsAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken) + { + ValidateLookup(bookMetadataLookup); + + if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId)) + { + AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); + return exactBookRequestMatch is null ? [] : [new BookMetadataDto( + exactBookRequestMatch.Metadata?.Title, + exactBookRequestMatch.Metadata?.OriginalTitle, + exactBookRequestMatch.Metadata?.Description, + exactBookRequestMatch.Metadata?.ReleaseInfo, + exactBookRequestMatch.Metadata?.Genres, + exactBookRequestMatch.Metadata?.Tags, + exactBookRequestMatch.Metadata?.Language, + exactBookRequestMatch.Metadata?.OriginalLanguage, + exactBookRequestMatch.Metadata?.Publisher, + exactBookRequestMatch.Metadata?.PageCount, + exactBookRequestMatch.Format, + exactBookRequestMatch.Edition, + exactBookRequestMatch.VolumeNumber, + exactBookRequestMatch.Series, + exactBookRequestMatch.ASIN, + exactBookRequestMatch.GoodreadsId, + exactBookRequestMatch.LCCN, + exactBookRequestMatch.OCLCNumber, + exactBookRequestMatch.OpenLibraryId, + exactBookRequestMatch.LibraryThingId, + exactBookRequestMatch.GoogleBooksId, + exactBookRequestMatch.BarnesAndNobleId, + exactBookRequestMatch.AppleBooksId, + exactBookRequestMatch.ISBNs, + exactBookRequestMatch.Contributors, + exactBookRequestMatch.Ratings, + CoverImageUrl: null + )]; + } + + IReadOnlyList openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, _openLibrarySettings.SearchResultLimit, cancellationToken).ConfigureAwait(false); + + return [.. openLibrarySearchDocuments + .Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title)) + .Select(openLibrarySearchDocument => + { + AddBookRequest addBookRequest = OpenLibraryMapper.MapSearchCandidate(bookMetadataLookup, openLibrarySearchDocument); + return new BookMetadataDto( + addBookRequest.Metadata?.Title, + addBookRequest.Metadata?.OriginalTitle, + addBookRequest.Metadata?.Description, + addBookRequest.Metadata?.ReleaseInfo, + addBookRequest.Metadata?.Genres, + addBookRequest.Metadata?.Tags, + addBookRequest.Metadata?.Language, + addBookRequest.Metadata?.OriginalLanguage, + addBookRequest.Metadata?.Publisher, + addBookRequest.Metadata?.PageCount, + addBookRequest.Format, + addBookRequest.Edition, + addBookRequest.VolumeNumber, + addBookRequest.Series, + addBookRequest.ASIN, + addBookRequest.GoodreadsId, + addBookRequest.LCCN, + addBookRequest.OCLCNumber, + addBookRequest.OpenLibraryId, + addBookRequest.LibraryThingId, + addBookRequest.GoogleBooksId, + addBookRequest.BarnesAndNobleId, + addBookRequest.AppleBooksId, + addBookRequest.ISBNs, + addBookRequest.Contributors, + addBookRequest.Ratings, + CoverImageUrl: null + ); + })]; + } + + /// + /// Gets the metadata of the media item described by . + /// + /// The lookup describing the media item to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the media item, or when no metadata was found. + public async Task GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken) + { + AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); + return exactBookRequestMatch is null ? null : new BookMetadataDto( + exactBookRequestMatch.Metadata?.Title, + exactBookRequestMatch.Metadata?.OriginalTitle, + exactBookRequestMatch.Metadata?.Description, + exactBookRequestMatch.Metadata?.ReleaseInfo, + exactBookRequestMatch.Metadata?.Genres, + exactBookRequestMatch.Metadata?.Tags, + exactBookRequestMatch.Metadata?.Language, + exactBookRequestMatch.Metadata?.OriginalLanguage, + exactBookRequestMatch.Metadata?.Publisher, + exactBookRequestMatch.Metadata?.PageCount, + exactBookRequestMatch.Format, + exactBookRequestMatch.Edition, + exactBookRequestMatch.VolumeNumber, + exactBookRequestMatch.Series, + exactBookRequestMatch.ASIN, + exactBookRequestMatch.GoodreadsId, + exactBookRequestMatch.LCCN, + exactBookRequestMatch.OCLCNumber, + exactBookRequestMatch.OpenLibraryId, + exactBookRequestMatch.LibraryThingId, + exactBookRequestMatch.GoogleBooksId, + exactBookRequestMatch.BarnesAndNobleId, + exactBookRequestMatch.AppleBooksId, + exactBookRequestMatch.ISBNs, + exactBookRequestMatch.Contributors, + exactBookRequestMatch.Ratings, + CoverImageUrl: null + ); + } + + /// + /// Resolves the lookup into a full book request by combining edition, work, author, and rating data from Open Library. + /// + /// The lookup describing the book to resolve. + /// Cancellation token that can be used to stop the execution. + /// The resolved book request, or when no matching book was found. + public async Task GetBookAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken = default) + { + ValidateLookup(bookMetadataLookup); + + OpenLibraryEditionResponse? openLibraryEditionResponse = null; + OpenLibraryWorkResponse? openLibraryWorkResponse = null; + OpenLibrarySearchDocumentResponse? openLibrarySearchDocumentResponse = null; + string? openLibraryId = bookMetadataLookup.OpenLibraryId; + string? isbn = bookMetadataLookup.Isbn; + // if we have an Open Library Id, that's the first thing we should search by + if (!string.IsNullOrWhiteSpace(openLibraryId)) + { + string olid = NormalizeOlid(openLibraryId); + if (olid.EndsWith('M')) + openLibraryEditionResponse = await _openLibraryHttpClient.GetEditionAsync(olid, cancellationToken).ConfigureAwait(false); + else if (olid.EndsWith('W')) + { + // 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); + } + 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)); + + if (openLibraryEditionResponse is null && openLibraryWorkResponse is null) + return null; + } + // no Open Library Id, let's try by ISBN + if (openLibraryEditionResponse is null && !string.IsNullOrWhiteSpace(isbn)) + openLibraryEditionResponse = await _openLibraryHttpClient.GetEditionByIsbnAsync(isbn, cancellationToken).ConfigureAwait(false); + // if we still have no results, let's go nuclear and search by metadata + if (openLibraryEditionResponse is null && openLibraryWorkResponse is null) + { + IReadOnlyList searchResults = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, 1, cancellationToken).ConfigureAwait(false); + if (searchResults.Count == 0 || searchResults[0] is null) + return null; + + string? workId = OpenLibraryMapper.ExtractOlid(searchResults[0].Key, 'W'); + 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); + } + + if (openLibraryEditionResponse is null && searchResults[0].EditionKeys.Count > 0) + openLibraryEditionResponse = await _openLibraryHttpClient.GetEditionAsync(searchResults[0].EditionKeys[0], cancellationToken).ConfigureAwait(false); + } + // if by this time we still have no result, let's forget it... + if (openLibraryEditionResponse is null && openLibraryWorkResponse is null && openLibrarySearchDocumentResponse is null) + return null; + + string? editionWorkId = OpenLibraryMapper.ExtractOlid(openLibraryEditionResponse?.Works.FirstOrDefault()?.Key, 'W'); + if (openLibraryWorkResponse is null && editionWorkId is not null) + openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(editionWorkId, cancellationToken).ConfigureAwait(false); + + List authorIds = [.. (openLibraryWorkResponse?.Authors + .Select(item => OpenLibraryMapper.ExtractOlid(item.Author?.Key ?? item.Key, 'A')) ?? []) + .Concat(openLibraryEditionResponse?.Authors + .Select(item => OpenLibraryMapper.ExtractOlid(item.Key, 'A')) ?? []) + .Where(id => id is not null) + .Select(id => id!) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + + List authors = []; + foreach (string authorId in authorIds) + { + OpenLibraryAuthorResponse? author = await _openLibraryHttpClient.GetAuthorAsync(authorId, cancellationToken).ConfigureAwait(false); + if (author is not null) + authors.Add(author); + } + + string? finalWorkId = OpenLibraryMapper.ExtractOlid(openLibraryWorkResponse?.Key, 'W') ?? editionWorkId; + OpenLibraryRatingsResponse? ratings = finalWorkId is null ? null : await _openLibraryHttpClient.GetRatingsAsync(finalWorkId, cancellationToken).ConfigureAwait(false); + + return OpenLibraryMapper.MapDetailed(bookMetadataLookup, openLibraryEditionResponse, openLibraryWorkResponse, authors, ratings, openLibrarySearchDocumentResponse); + } + + /// + /// Selects the best matching edition from the given editions, favoring matches for the lookup's ISBN and language. + /// + /// The editions to select from. + /// The lookup the selected edition must match. + /// The best matching edition, or when no edition was found. + private static OpenLibraryEditionResponse? SelectEdition(IReadOnlyList openLibraryEditions, BookMetadataLookupDto bookMetadataLookup) + { + string? lookupIsbn = bookMetadataLookup.Isbn; + string? wantedIsbn = string.IsNullOrWhiteSpace(lookupIsbn) ? null : OpenLibraryMapper.NormalizeIsbn(lookupIsbn); + string? wantedLanguage = bookMetadataLookup.LanguageCode?.Trim(); + + return openLibraryEditions + .Select((edition, index) => new + { + Edition = edition, + Index = index, + Score = ScoreEdition(edition, wantedIsbn, wantedLanguage) + }) + .OrderByDescending(item => item.Score) + .ThenBy(item => item.Index) + .Select(item => item.Edition) + .FirstOrDefault(); + } + + /// + /// Scores an edition against the wanted ISBN and language to rank how well it matches the lookup. + /// + /// The edition to score. + /// The normalized ISBN to match, or when the lookup has no ISBN. + /// The language code to match, or when the lookup has no language. + /// The match score of the edition, where a higher score is a better match. + private static int ScoreEdition(OpenLibraryEditionResponse openLibraryEdition, string? wantedIsbn, string? wantedLanguage) + { + int score = 0; + // if we get an ISBN match, that's the most certain identification score + if (wantedIsbn is not null && openLibraryEdition.Isbn10.Concat(openLibraryEdition.Isbn13).Any(value => string.Equals(SafeNormalizeIsbn(value), wantedIsbn, StringComparison.OrdinalIgnoreCase))) + score += 10_000; + + if (!string.IsNullOrWhiteSpace(wantedLanguage) && openLibraryEdition.Languages.Any(language => + string.Equals(language.Key?.Trim().TrimEnd('/').Split('/').Last(), wantedLanguage, StringComparison.OrdinalIgnoreCase))) + score += 1_000; + + if (openLibraryEdition.NumberOfPages is > 0) + score += 100; + if (openLibraryEdition.Isbn10.Count + openLibraryEdition.Isbn13.Count > 0) + score += 50; + if (openLibraryEdition.Publishers.Count > 0) + score += 20; + if (!string.IsNullOrWhiteSpace(openLibraryEdition.PublishDate)) + score += 10; + if (!string.IsNullOrWhiteSpace(openLibraryEdition.EditionName)) + score += 5; + return score; + } + + /// + /// Normalizes an ISBN, returning when the value is not a valid ISBN. + /// + /// The ISBN to normalize. + /// The normalized ISBN, or when the value is not a valid ISBN. + private static string? SafeNormalizeIsbn(string value) + { + try + { + return OpenLibraryMapper.NormalizeIsbn(value); + } + catch (ArgumentException) + { + return null; + } + } + + /// + /// Normalizes a raw Open Library identifier into its canonical OLID form. + /// + /// The raw Open Library identifier to normalize. + /// The canonical OLID. + /// The value is not a valid Open Library identifier. + private static string NormalizeOlid(string raw) + { + string id = raw.Trim().TrimEnd('/').Split('/').Last().ToUpperInvariant(); + if (id.Length < 4 || !id.StartsWith("OL", StringComparison.Ordinal) || (id[^1] is not ('M' or 'W')) || !id.AsSpan(2, id.Length - 3).ToString().All(char.IsDigit)) + throw new ArgumentException("The Open Library ID is invalid.", nameof(raw)); + + return id; + } + + /// + /// Validates that the lookup contains the information required to resolve book metadata. + /// + /// The lookup to validate. + /// The lookup is missing required information. + private static void ValidateLookup(BookMetadataLookupDto bookMetadataLookup) + { + ArgumentNullException.ThrowIfNull(bookMetadataLookup); + if (bookMetadataLookup.LibraryId == Guid.Empty) + throw new ArgumentException("LibraryId is required.", nameof(bookMetadataLookup)); + + ArgumentException.ThrowIfNullOrWhiteSpace(bookMetadataLookup.Path); + + if (string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) && string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId) && string.IsNullOrWhiteSpace(bookMetadataLookup.Title)) + throw new ArgumentException("At least one of Isbn, OpenLibraryId, or Title is required.", nameof(bookMetadataLookup)); + } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryPlugin.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryPlugin.cs new file mode 100644 index 00000000..1fb7f707 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryPlugin.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Contracts.Core.Plugins.Settings; +using Lumina.Plugins.OpenLibrary.Common.DependencyInjection; +using Lumina.Plugins.OpenLibrary.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Core; + +/// +/// Plugin that provides book metadata retrieval from Open Library. +/// +public sealed class OpenLibraryPlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("08b17802-7f9c-4c4b-9d7f-b507bbed3e58"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "Open Library Metadata"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Retrieves book and edition metadata from Open Library."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return + [ + new PluginSettingDescriptor( + Key: OpenLibrarySettingsKeys.CONTACT_EMAIL, + Label: "Contact Email", + Type: PluginSettingType.Text), + new PluginSettingDescriptor( + Key: OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT, + Label: "Search Result Limit", + Type: PluginSettingType.Number, + DefaultValue: "10"), + new PluginSettingDescriptor( + Key: OpenLibrarySettingsKeys.WORK_EDITION_LIMIT, + Label: "Work Edition Limit", + Type: PluginSettingType.Number, + DefaultValue: "50"), + new PluginSettingDescriptor( + Key: OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, + Label: "Minimum Request Interval (seconds)", + Type: PluginSettingType.Number, + DefaultValue: "1.1") + ]; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddOpenLibraryBookMetadataProvider(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsKeys.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsKeys.cs new file mode 100644 index 00000000..c1e83809 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsKeys.cs @@ -0,0 +1,27 @@ +namespace Lumina.Plugins.OpenLibrary.Core.Settings; + +/// +/// Keys of the settings of the Open Library metadata plugin, shared by the settings schema and the settings loader. +/// +internal static class OpenLibrarySettingsKeys +{ + /// + /// The key of the setting defining the contact email sent to the Open Library API. + /// + internal const string CONTACT_EMAIL = "ContactEmail"; + + /// + /// The key of the setting defining the maximum number of results returned by a single search. + /// + internal const string SEARCH_RESULT_LIMIT = "SearchResultLimit"; + + /// + /// The key of the setting defining the maximum number of editions fetched for a single work. + /// + internal const string WORK_EDITION_LIMIT = "WorkEditionLimit"; + + /// + /// The key of the setting defining the minimum interval between consecutive requests to the Open Library API, in seconds. + /// + internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds"; +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsLoader.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsLoader.cs new file mode 100644 index 00000000..772ed05e --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsLoader.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Globalization; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Core.Settings; + +/// +/// Applies the settings persisted by the host onto the runtime settings of the Open Library metadata plugin. +/// +internal static class OpenLibrarySettingsLoader +{ + /// + /// Overlays the persisted onto the provided , keeping the default values of the settings that were not persisted. + /// + /// The runtime settings onto which the persisted settings are applied. + /// The settings persisted by the host, keyed by setting key. + public static void Apply(OpenLibrarySettingsDto settings, IReadOnlyDictionary storedSettings) + { + if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.CONTACT_EMAIL, out string? contactEmail)) + settings.ContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim(); + + if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.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(OpenLibrarySettingsKeys.WORK_EDITION_LIMIT, out string? workEditionLimit) && + int.TryParse(workEditionLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int workEditionLimitValue)) + settings.WorkEditionLimit = Math.Max(1, workEditionLimitValue); + + if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) && + double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue)) + settings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Max(0, minimumRequestIntervalValue)); + } +} diff --git a/plugins/Lumina.Plugins.OpenLibrary/Lumina.Plugins.OpenLibrary.csproj b/plugins/Lumina.Plugins.OpenLibrary/Lumina.Plugins.OpenLibrary.csproj new file mode 100644 index 00000000..a0f2e745 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Lumina.Plugins.OpenLibrary.csproj @@ -0,0 +1,32 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + + + + + + + + + + + + + + false + runtime + + + + + + +