#region ========================================================================= USING ===================================================================================== using Nemera.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Nemera.Plugins.OpenLibrary.Common.Models.Contracts.Responses; using Nemera.Plugins.OpenLibrary.Common.Models.DTO.Settings; using Nemera.Plugins.OpenLibrary.Core.Mapping; using Nemera.Plugins.OpenLibrary.Core.Settings; 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 Nemera.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 OpenLibrarySettingsProvider _settingsProvider; 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,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 provider of the settings that configure the Open Library API requests. public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsProvider settingsProvider) { _httpClient = httpClient; _settingsProvider = settingsProvider; _httpClient.BaseAddress ??= new("https://openlibrary.org/"); } /// /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set. /// /// The settings that configure the Open Library API requests. 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!; } /// /// 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) { OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); EnsureRequestHeaders(settings); await _requestGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { DateTimeOffset earliestNextRequest = _lastRequestAt + settings.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; } }