Merge branch 'feature/add-metadata-aggregation' into feature/add-artwork-provider-and-metadata-aggregation

This commit is contained in:
BinaryAlley committed 2026-08-24 22:53:57 -07:00
commit b47588cf83
168 files changed
+3503 -1062

No files matched your search

@@ -14,6 +14,7 @@ public static partial class Errors
public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty));
public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty));
public static Error MediaLibrariesDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaLibrariesDirectoryCannotBeEmpty));
public static Error MediaBooksDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaBooksDirectoryCannotBeEmpty));
public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty));
public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String));
public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty));
@@ -23,5 +23,9 @@ public class MediaSettingsDtoValidator : AbstractValidator<MediaSettingsDto>
RuleFor(settings => settings.LibrariesDirectory)
.NotEmpty()
.WithError(Errors.Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty);
RuleFor(settings => settings.BooksDirectory)
.NotEmpty()
.WithError(Errors.Errors.Configuration.MediaBooksDirectoryCannotBeEmpty);
}
}
@@ -1,9 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Events;
@@ -77,71 +80,140 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// get the metadata providers configured for the media library, in their configured order, that support the media library type
// load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
// whether the providers that require access to the web are used during the enrichment
string libraryName = string.Empty;
bool canDownloadMetadataFromWeb = false;
if (unitOfWork.LibraryRepository is not null)
{
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
_logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used.");
else
{
libraryName = getLibraryResult.Value.Title;
canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
}
}
// get the metadata providers configured for the media library, in their configured order, that support the media library type,
// skipping the providers that require access to the web when the media library does not permit downloading data from the web
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
List<IRemoteMetadataProvider> providers = [];
List<IMetadataProvider> providers = [];
foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
{
List<IRemoteMetadataProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
.GetKeyedServices<IRemoteMetadataProvider>(configuration.PluginId)
.Where(provider => provider.SupportedLibraryType == LibraryType.Book)];
List<IMetadataProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
.GetKeyedServices<IMetadataProvider>(configuration.PluginId)
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
providers.AddRange(configuredProviders);
}
// read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing
bool shouldAggregateMetadataWhenMissing = false;
if (unitOfWork.UserSettingsRepository is not null)
{
Result<UserSettingsEntity?> getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false);
if (getUserSettingsResult.IsFailure)
_logger.LogWarning("Failed to read the user settings, the metadata will not be aggregated across providers.");
else
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
}
// get the artwork providers configured for the media library, in their configured order, that support the media library type.
// the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the metadata enrichment from proceeding
List<IArtworkProvider> artworkProviders = [];
if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
{
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getArtworkConfigurationsResult.IsFailure)
_logger.LogWarning("Failed to read the artwork provider configurations.");
else
{
foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
{
List<IArtworkProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
.GetKeyedServices<IArtworkProvider>(configuration.PluginId)
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
artworkProviders.AddRange(configuredProviders);
}
}
}
IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService<IBookArtworkService>();
// count the books that need their metadata enriched, for progress reporting purposes
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getBooksToEnrichCountResult.IsFailure)
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
// set the initial progress of the scan job
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
DateTime lastUpdateTime = DateTime.UtcNow;
int minUpdateIntervalMs = 100;
int processedBooksCount = 0;
string? lastPath = null;
// process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
while (true)
// when no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely
if (providers.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getBooksToEnrichCountResult.IsFailure)
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
Result<IReadOnlyList<BookEntity>> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
if (getBooksPageResult.IsFailure)
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
IReadOnlyList<BookEntity> booksPage = getBooksPageResult.Value;
if (booksPage.Count == 0)
break;
// set the initial progress of the scan job
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
foreach (BookEntity bookEntity in booksPage)
DateTime lastUpdateTime = DateTime.UtcNow;
int minUpdateIntervalMs = 100;
int processedBooksCount = 0;
// process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
await EnrichBookAsync(bookEntity, providers, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false);
Result<IReadOnlyList<BookEntity>> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
if (getBooksPageResult.IsFailure)
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
IReadOnlyList<BookEntity> booksPage = getBooksPageResult.Value;
if (booksPage.Count == 0)
break;
// check if enough time has passed since last update
DateTime now = DateTime.UtcNow;
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
foreach (BookEntity bookEntity in booksPage)
{
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastUpdateTime = now;
}
}
cancellationToken.ThrowIfCancellationRequested();
lastPath = booksPage[^1].Path;
await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, artworkProviders, bookArtworkService, libraryName, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false);
// check if enough time has passed since last update
DateTime now = DateTime.UtcNow;
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastUpdateTime = now;
}
}
// persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
unitOfWork.ClearTrackedEntities();
lastPath = booksPage[^1].Path;
}
}
else
{
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value);
}
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// persist the changes when no page was processed, so that the scan still saves even when there are no books to enrich
if (lastPath is null)
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// this job finished, and it's the last in the chain, the scan is completed
Status = LibraryScanJobStatus.Completed;
@@ -166,21 +238,29 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
/// <summary>
/// Enriches the metadata of the provided <paramref name="bookEntity"/>, using the provided <paramref name="providers"/> in their configured order.
/// Enriches the metadata and the artwork of the provided <paramref name="bookEntity"/>, using the provided metadata and artwork providers in their configured order.
/// </summary>
/// <param name="bookEntity">The book whose metadata is enriched.</param>
/// <param name="providers">The metadata providers, in their configured order.</param>
/// <param name="bookRepository">The repository used to persist the enriched metadata.</param>
/// <param name="bookEntity">The book whose metadata and artwork are enriched.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not.</param>
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
/// <param name="bookArtworkService">The service used to store the artwork of the book.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="bookRepository">The repository used to persist the enriched book.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private static async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IRemoteMetadataProvider> providers, IBookRepository bookRepository, CancellationToken cancellationToken)
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, IBookRepository bookRepository, CancellationToken cancellationToken)
{
// when no metadata provider is available, the book must not be marked as failed to enrich, so the enrichment is skipped
if (metadataProviders.Count == 0)
return;
// convert the book to a domain object
Result<Book> getBookResult = bookEntity.ToDomainEntity();
if (getBookResult.IsFailure)
return;
Book book = getBookResult.Value;
BookMetadataLookupDto lookup = new(
BookMetadataLookupDto bookMetadataLookup = new(
LibraryId: bookEntity.LibraryId,
Path: bookEntity.Path,
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: this should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results
@@ -190,24 +270,84 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
LanguageCode: bookEntity.LanguageCode
);
// try the metadata providers in order, until one returns usable metadata
foreach (IRemoteMetadataProvider provider in providers)
BookMetadataDto? appliedMetadata = shouldAggregateMetadataWhenMissing
? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false)
: await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false);
if (appliedMetadata is null)
{
// no metadata provider returned usable metadata, mark the book as failed to enrich
book.MarkMetadataAsFailed();
Result<Updated> markFailedResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (markFailedResult.IsFailure)
_logger.LogWarning("Failed to persist the failed enrichment state of the book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path);
return;
}
// resolve the artwork of the book from the artwork providers, in their configured order
await EnrichBookArtworkAsync(book, appliedMetadata, artworkProviders, bookArtworkService, libraryName, cancellationToken).ConfigureAwait(false);
Result<Updated> updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateBookResult.IsFailure)
_logger.LogWarning("Failed to persist the enriched book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path);
}
/// <summary>
/// Tries the <paramref name="metadataProviders"/> in order, applying the metadata of the first one that returns usable metadata.
/// </summary>
/// <param name="book">The book onto which the metadata is applied.</param>
/// <param name="bookMetadataLookup">The lookup describing the book.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied metadata, or <see langword="null"/> when no provider returned usable metadata.</returns>
private static async Task<BookMetadataDto?> TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
{
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
try
{
MetadataDto? metadataResult = await provider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
continue;
Result<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow);
Result<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata, metadataProvider.Name, DateTime.UtcNow);
if (applyMetadataResult.IsFailure)
continue;
return bookMetadata;
}
catch (Exception)
{
// a failing metadata provider must not prevent the other providers from being tried
}
}
return null;
}
Result<Updated> updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateBookResult.IsFailure)
/// <summary>
/// Aggregates the metadata of the <paramref name="book"/> from all the <paramref name="metadataProviders"/>, in their configured order, filling the fields that the earlier providers lack with the values of the later ones.
/// </summary>
/// <param name="book">The book onto which the aggregated metadata is applied.</param>
/// <param name="bookMetadataLookup">The lookup describing the book.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied aggregated metadata, or <see langword="null"/> when no provider returned usable metadata.</returns>
private static async Task<BookMetadataDto?> AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
{
BookMetadataDto? mergedMetadata = null;
List<string> contributingProviders = [];
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
try
{
MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
continue;
return;
mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata);
contributingProviders.Add(metadataProvider.Name);
// the identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely
bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata);
}
catch (Exception)
{
@@ -215,25 +355,84 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
}
// no metadata provider returned usable metadata, mark the book as failed to enrich
book.MarkMetadataAsFailed();
await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (mergedMetadata is null)
return null;
Result<Success> applyMetadataResult = book.ApplyMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)), DateTime.UtcNow);
return applyMetadataResult.IsFailure ? null : mergedMetadata;
}
/// <summary>
/// Determines whether the provided <paramref name="metadata"/> is usable, meaning it has a title and at least one primary identifier.
/// Resolves the artwork of the <paramref name="book"/> from the <paramref name="artworkProviders"/>, in their configured order, storing the artwork of the first provider that returns it.
/// </summary>
/// <param name="metadata">The metadata to validate.</param>
/// <returns><see langword="true"/> when the metadata is usable, otherwise <see langword="false"/>.</returns>
private static bool IsUsableMetadata(BookMetadataDto metadata)
/// <param name="book">The book whose artwork is enriched.</param>
/// <param name="appliedMetadata">The metadata applied to the book, used to build the directory of the book artwork.</param>
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
/// <param name="bookArtworkService">The service used to store the artwork of the book.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private static async Task EnrichBookArtworkAsync(Book book, BookMetadataDto appliedMetadata, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(metadata.Title))
return false;
return !string.IsNullOrWhiteSpace(metadata.GoodreadsId)
|| !string.IsNullOrWhiteSpace(metadata.OpenLibraryId)
|| !string.IsNullOrWhiteSpace(metadata.GoogleBooksId)
|| !string.IsNullOrWhiteSpace(metadata.ASIN)
|| (metadata.Isbns is not null && metadata.Isbns.Count > 0);
if (bookArtworkService is null || artworkProviders.Count == 0)
return;
foreach (IArtworkProvider provider in artworkProviders)
{
ArtworkDto? artwork = null;
try
{
artwork = await provider.GetArtworkAsync(new BookMetadataLookupDto(LibraryId: book.LibraryId.Value, Path: book.Path), cancellationToken).ConfigureAwait(false);
}
catch (Exception)
{
// a failing artwork provider must not prevent the other providers from being tried
}
if (artwork is null)
continue;
// a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract
if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess)
continue;
string authorName = appliedMetadata.Contributors?.FirstOrDefault(contributor => contributor.Name?.DisplayName is not null)?.Name?.DisplayName ?? string.Empty;
string bookTitle = appliedMetadata.Title ?? book.Metadata.Title;
Result<string> saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(book.LibraryId.Value, book.Id.Value, libraryName, authorName, bookTitle, artwork, cancellationToken).ConfigureAwait(false);
if (saveArtworkResult.IsFailure)
continue;
book.SetBookCoverImagePath(saveArtworkResult.Value);
return;
}
}
/// <summary>
/// Enriches the <paramref name="bookMetadataLookup"/> with the identifiers and the title discovered by the already queried metadata providers.
/// </summary>
/// <param name="bookMetadataLookup">The lookup to enrich.</param>
/// <param name="bookMetadata">The metadata discovered by the already queried metadata providers.</param>
/// <returns>The enriched lookup.</returns>
private static BookMetadataLookupDto EnrichLookup(BookMetadataLookupDto bookMetadataLookup, BookMetadataDto bookMetadata)
{
string? isbn = bookMetadataLookup.Isbn ?? bookMetadata.Isbns?.FirstOrDefault()?.Value;
string? openLibraryId = bookMetadataLookup.OpenLibraryId ?? bookMetadata.OpenLibraryId;
string? title = bookMetadataLookup.Title ?? bookMetadata.Title;
return bookMetadataLookup with
{
Isbn = isbn,
OpenLibraryId = openLibraryId,
Title = title
};
}
/// <summary>
/// Determines whether the provided <paramref name="bookMetadata"/> is usable, meaning it has a title.
/// </summary>
/// <param name="bookMetadata">The metadata to validate.</param>
/// <returns><see langword="true"/> when the metadata is usable, otherwise <see langword="false"/>.</returns>
private static bool IsUsableMetadata(BookMetadataDto bookMetadata)
{
return !string.IsNullOrWhiteSpace(bookMetadata.Title);
}
/// <summary>
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Merges the book metadata returned by multiple metadata providers into a single book metadata, giving priority to the first provider that provides a value for each field.
/// </summary>
internal static class MetadataAggregator
{
/// <summary>
/// Merges <paramref name="first"/> with <paramref name="second"/>, keeping the first non-empty value of each scalar field, and the union of the collection fields.
/// </summary>
/// <param name="first">The first metadata to merge, whose values have priority.</param>
/// <param name="second">The second metadata to merge, filling the fields that the first metadata lacks.</param>
/// <returns>The merged metadata.</returns>
public static BookMetadataDto Merge(BookMetadataDto first, BookMetadataDto second)
{
return new BookMetadataDto(
FirstOrDefaultReference(first.Title, second.Title),
FirstOrDefaultReference(first.OriginalTitle, second.OriginalTitle),
FirstOrDefaultReference(first.Description, second.Description),
MergeReleaseInfo(first.ReleaseInfo, second.ReleaseInfo),
Union(first.Genres, second.Genres, genre => genre.Name),
Union(first.Tags, second.Tags, tag => tag.Name),
FirstOrDefaultReference(first.Language, second.Language),
FirstOrDefaultReference(first.OriginalLanguage, second.OriginalLanguage),
FirstOrDefaultReference(first.Publisher, second.Publisher),
FirstOrDefaultValue(first.PageCount, second.PageCount),
FirstOrDefaultValue(first.Format, second.Format),
FirstOrDefaultReference(first.Edition, second.Edition),
FirstOrDefaultValue(first.VolumeNumber, second.VolumeNumber),
FirstOrDefaultReference(first.Series, second.Series),
FirstOrDefaultReference(first.ASIN, second.ASIN),
FirstOrDefaultReference(first.GoodreadsId, second.GoodreadsId),
FirstOrDefaultReference(first.LCCN, second.LCCN),
FirstOrDefaultReference(first.OCLCNumber, second.OCLCNumber),
FirstOrDefaultReference(first.OpenLibraryId, second.OpenLibraryId),
FirstOrDefaultReference(first.LibraryThingId, second.LibraryThingId),
FirstOrDefaultReference(first.GoogleBooksId, second.GoogleBooksId),
FirstOrDefaultReference(first.BarnesAndNobleId, second.BarnesAndNobleId),
FirstOrDefaultReference(first.AppleBooksId, second.AppleBooksId),
Union(first.Isbns, second.Isbns, isbn => isbn.Value),
Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role?.Name}"),
Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()),
FirstOrDefaultReference(first.CoverImagePath, second.CoverImagePath));
}
/// <summary>
/// Merges the release information of the two metadata, keeping the first non-null value of each field.
/// </summary>
/// <param name="first">The first release information, whose values have priority.</param>
/// <param name="second">The second release information, filling the fields that the first one lacks.</param>
/// <returns>The merged release information, or <see langword="null"/> when both are <see langword="null"/>.</returns>
private static ReleaseInfoDto? MergeReleaseInfo(ReleaseInfoDto? first, ReleaseInfoDto? second)
{
if (first is null && second is null)
return null;
return new ReleaseInfoDto(
FirstOrDefaultValue(first?.OriginalReleaseDate, second?.OriginalReleaseDate),
FirstOrDefaultValue(first?.OriginalReleaseYear, second?.OriginalReleaseYear),
FirstOrDefaultValue(first?.ReReleaseDate, second?.ReReleaseDate),
FirstOrDefaultValue(first?.ReReleaseYear, second?.ReReleaseYear),
FirstOrDefaultReference(first?.ReleaseCountry, second?.ReleaseCountry),
FirstOrDefaultReference(first?.ReleaseVersion, second?.ReleaseVersion));
}
/// <summary>
/// Gets the first non-null value of the two reference values.
/// </summary>
/// <typeparam name="T">The type of the reference values.</typeparam>
/// <param name="first">The value with priority.</param>
/// <param name="second">The fallback value.</param>
/// <returns>The first non-null value, or <see langword="null"/> when both are <see langword="null"/>.</returns>
private static T? FirstOrDefaultReference<T>(T? first, T? second)
where T : class
{
return first ?? second;
}
/// <summary>
/// Gets the first non-null value of the two nullable value types.
/// </summary>
/// <typeparam name="T">The underlying type of the nullable values.</typeparam>
/// <param name="first">The value with priority.</param>
/// <param name="second">The fallback value.</param>
/// <returns>The first non-null value, or <see langword="null"/> when both are <see langword="null"/>.</returns>
private static T? FirstOrDefaultValue<T>(T? first, T? second)
where T : struct
{
return first ?? second;
}
/// <summary>
/// Returns the union of the two collections, de-duplicated by the <paramref name="keySelector"/> key, keeping the items of the first collection on key conflicts.
/// </summary>
/// <typeparam name="T">The type of the collection items.</typeparam>
/// <param name="first">The first collection, whose items have priority.</param>
/// <param name="second">The second collection.</param>
/// <param name="keySelector">The function used to extract the de-duplication key of an item.</param>
/// <returns>The union of the two collections, or <see langword="null"/> when both are <see langword="null"/>.</returns>
private static List<T>? Union<T>(List<T>? first, List<T>? second, Func<T, string?> keySelector)
where T : class
{
if (first is null && second is null)
return null;
Dictionary<string, T> seen = new(StringComparer.OrdinalIgnoreCase);
List<T> result = [];
void AddRange(List<T>? items)
{
foreach (T item in items ?? [])
if (seen.TryAdd(keySelector(item) ?? string.Empty, item))
result.Add(item);
}
AddRange(first);
AddRange(second);
return result;
}
}
@@ -1,7 +1,8 @@
{
"MediaSettings": {
"RootDirectory": "media",
"LibrariesDirectory": "libraries"
"LibrariesDirectory": "libraries",
"BooksDirectory": "books"
},
"PluginsSettings": {
"Directory": "plugins"