#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 Lumina.Plugins.OpenLibrary.Core.Settings;
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 : IMetadataProvider
{
private readonly OpenLibraryHttpClient _openLibraryHttpClient;
private readonly OpenLibrarySettingsProvider _settingsProvider;
///
/// Gets the display name of the metadata provider.
///
public string Name => "Open Library";
///
/// Gets the media library types this metadata provider supports.
///
public IReadOnlyList SupportedLibraryTypes => [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 provider of the settings that configure the Open Library API requests.
public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsProvider settingsProvider)
{
_openLibraryHttpClient = openLibraryHttpClient;
_settingsProvider = settingsProvider;
}
///
/// 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);
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId))
{
BookMetadataDto? exactBookMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
return exactBookMatch is null ? [] : [exactBookMatch];
}
IReadOnlyList openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
return [.. openLibrarySearchDocuments
.Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title))
.Select(openLibrarySearchDocument => OpenLibraryMapper.MapSearchCandidate(bookMetadataLookup, openLibrarySearchDocument))];
}
///
/// 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)
{
return await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
}
///
/// Resolves the lookup into full book metadata 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 metadata, or when no matching book was found.
public async Task GetBookAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken = default)
{
ValidateLookup(bookMetadataLookup);
OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
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, settings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
}
else
throw new ArgumentException("A book Open Library ID must be a work ID ending in W or an edition ID ending in M.", nameof(bookMetadataLookup));
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, settings.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));
}
}