Adds independent metadata and artwork enrichment

Splits the single combined enrichment phase of the media library scan into
independent, modular jobs, so that the metadata and the artwork of a book
are enriched separately and only when their respective triggers fire.

- Adds the MediaContributorRoleCategory enum (Other first, then Author,
  Translator, Illustrator, Publisher and Narrator) and makes the role
  category canonical, so that roles describing the same kind of
  contribution are never treated as distinct.
- Realizes the media contributor bounded context: a MediaContributor is a
  person, unique by display name, without a role. The role moves to the
  per-work participation (BookContributors), so that a single contributor
  can play multiple roles. Contributors are created and linked by the
  metadata enrichment job, and exposed to subsequent jobs.
- Makes the Book aggregate pure: the enrichment tracking state (metadata
  status, providers, timestamps and covers) no longer lives on the domain
  aggregate, but stays in the Books table, managed directly by the jobs.
- Models artwork generically as a BookArtwork child table (type, ordinal,
  content hash, status and provider), so that each piece of artwork is
  tracked independently and a change of one does not require the others to
  be re-fetched.
- Splits the scan DAG into ResultsSave, ProviderConfigurationInvalidation,
  MetadataEnrichment and ArtworkEnrichment jobs. The invalidation job
  fingerprints the provider configuration of a library and resets the
  enrichment state of the affected channel when it changed. The artwork job
  resolves the missing artwork, hashing it to detect identical covers and
  skip re-copying. Content-changed books are reset by the results save job.
- Deletes the book and its stored artwork when the file disappears from the
  library.
- Adds the migration creating the new tables, backfilling the existing
  covers into the artwork table, and adding the configuration fingerprints.
- Localizes the new scan job stages, and fixes the invalidation job wiping
  the library content locations by persisting the fingerprints through the
  change tracker instead of the repository update action.
This commit is contained in:
BinaryAlley committed 2026-08-27 14:41:49 +03:00
1 parent 4ee2976806
commit 565fe68239
98 files changed
+5845 -630

No files matched your search

@@ -99,7 +99,9 @@ public static class InfrastructureLayerServices
services.AddTransient<IMediaLibraryScanDiffJob, MediaLibraryScanDiffJob>();
services.AddTransient<IMediaLibraryScanHashJob, MediaLibraryScanHashJob>();
services.AddTransient<IMediaLibraryScanResultsSaveJob, MediaLibraryScanResultsSaveJob>();
services.AddTransient<IMediaLibraryScanProviderConfigurationInvalidationJob, MediaLibraryScanProviderConfigurationInvalidationJob>();
services.AddTransient<IMediaLibraryScanMetadataEnrichmentJob, MediaLibraryScanMetadataEnrichmentJob>();
services.AddTransient<IMediaLibraryScanArtworkEnrichmentJob, MediaLibraryScanArtworkEnrichmentJob>();
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
@@ -0,0 +1,412 @@
#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.UoW;
using Lumina.Application.Common.Infrastructure.Security;
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;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Media library scan job for resolving the artwork of the media library items, using the artwork providers configured for the media library.
/// The artwork is tracked per book, per type and ordinal, so that a change of one artwork does not require the others to be re-fetched.
/// </summary>
internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob
{
private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<MediaLibraryScanArtworkEnrichmentJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanArtworkEnrichmentJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">
/// Injected factory for creating scopes in which services are requested.
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
/// </param>
/// <param name="logger">Injected logger used to report the issues encountered while resolving the artwork.</param>
public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger<MediaLibraryScanArtworkEnrichmentJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <summary>
/// Executes the payload of the media library scan job.
/// </summary>
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
/// <param name="id">The unique identifier of the media library scan job.</param>
/// <param name="input">The input data to be processed by this payload.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// 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 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 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);
}
}
}
// when no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely
if (artworkProviders.Count > 0)
{
IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService<IBookArtworkService>();
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(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;
// process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size
string? lastPath = null;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
Result<IReadOnlyList<BookEntity>> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(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;
// load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
throw new InvalidOperationException(getAuthorsResult.FirstError.Description);
foreach (BookEntity bookEntity in booksPage)
{
cancellationToken.ThrowIfCancellationRequested();
await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, 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 artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", LibraryId.Value);
}
Status = LibraryScanJobStatus.Completed;
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
if (Children.Count == 0)
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
catch (Exception exception)
{
Status = LibraryScanJobStatus.Failed;
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Resolves the cover artwork of the provided <paramref name="bookEntity"/> from the <paramref name="artworkProviders"/>, in their configured order,
/// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book.
/// </summary>
/// <param name="bookEntity">The book whose artwork is resolved.</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="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="authorsDisplayNamesByBookId">The display names of the authors of the books of the current page, keyed by the Id of the book.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary<Guid, string?> authorsDisplayNamesByBookId, CancellationToken cancellationToken)
{
// when no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped
if (bookArtworkService is null || artworkProviders.Count == 0)
return;
ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false);
if (resolvedArtwork is null)
{
// no artwork provider returned usable artwork, mark the cover artwork of the book as failed to resolve
BookArtworkEntity? coverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
if (coverArtwork is null)
{
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
}
else
{
coverArtwork.Status = ArtworkStatus.Failed;
coverArtwork.UpdatedOnUtc = DateTime.UtcNow;
coverArtwork.UpdatedBy = Guid.NewGuid();
}
return;
}
BookArtworkEntity? existingCoverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
// when the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one
// is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it.
ulong contentHash = 0;
bool shouldStoreArtwork = true;
if (!string.IsNullOrWhiteSpace(resolvedArtwork.Artwork.LocalPath))
{
contentHash = fileHashService.ComputeFileHash(resolvedArtwork.Artwork.LocalPath);
shouldStoreArtwork = existingCoverArtwork is null || contentHash != existingCoverArtwork.ContentHash;
}
if (shouldStoreArtwork)
{
string authorName = authorsDisplayNamesByBookId.TryGetValue(bookEntity.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
Result<string> saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false);
if (saveArtworkResult.IsFailure)
{
// a failing artwork storage must not prevent the book from being tracked as failed to resolve
if (existingCoverArtwork is null)
{
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
}
else
{
existingCoverArtwork.Status = ArtworkStatus.Failed;
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedBy = Guid.NewGuid();
}
return;
}
// for remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one
if (contentHash == 0)
{
string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\'));
contentHash = fileHashService.ComputeFileHash(storedArtworkPath);
}
if (existingCoverArtwork is null)
{
bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow));
}
else
{
existingCoverArtwork.FileName = saveArtworkResult.Value;
existingCoverArtwork.ContentHash = contentHash;
existingCoverArtwork.Status = ArtworkStatus.Enriched;
existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedBy = Guid.NewGuid();
}
}
else
{
// the resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched
existingCoverArtwork!.Status = ArtworkStatus.Enriched;
existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
existingCoverArtwork.UpdatedBy = Guid.NewGuid();
}
}
/// <summary>
/// Resolves the artwork of the <paramref name="bookEntity"/> from the <paramref name="artworkProviders"/>, in their configured order,
/// returning the artwork of the first provider that returns it.
/// </summary>
/// <param name="bookEntity">The book whose artwork is resolved.</param>
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The resolved artwork and the provider that supplied it, or <see langword="null"/> when no provider returned usable artwork.</returns>
private static async Task<ResolvedArtwork?> ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, CancellationToken cancellationToken)
{
BookMetadataLookupDto artworkLookup = 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,
OpenLibraryId: bookEntity.OpenLibraryId,
Title: bookEntity.Title,
Author: null,
LanguageCode: bookEntity.LanguageCode
);
foreach (IArtworkProvider provider in artworkProviders)
{
ArtworkDto? artwork = null;
try
{
artwork = await provider.GetArtworkAsync(artworkLookup, 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;
return new ResolvedArtwork(artwork, provider.Name);
}
return null;
}
/// <summary>
/// Creates a cover artwork entity for the book identified by <paramref name="bookId"/>.
/// </summary>
/// <param name="bookId">The Id of the book the artwork belongs to.</param>
/// <param name="status">The status of the artwork enrichment.</param>
/// <param name="fileName">The relative file name of the stored artwork, if the artwork has been resolved.</param>
/// <param name="contentHash">The content hash of the stored artwork.</param>
/// <param name="provider">The name of the plugin that resolved the artwork, if applicable.</param>
/// <param name="lastUpdateUtc">The date and time when the artwork was resolved, if applicable.</param>
/// <returns>The created cover artwork entity.</returns>
private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc)
{
return new BookArtworkEntity
{
Id = Guid.NewGuid(),
BookId = bookId,
ArtworkType = ArtworkType.Cover,
Ordinal = 0,
FileName = fileName,
ContentHash = contentHash,
Status = status,
Provider = provider,
LastUpdateUtc = lastUpdateUtc,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
};
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork");
if (scanJobProgressResult.IsFailure)
return scanJobProgressResult.Errors;
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
}
/// <summary>
/// The artwork resolved for a book, along with the provider that supplied it.
/// </summary>
/// <param name="Artwork">The resolved artwork of the book.</param>
/// <param name="ProviderName">The name of the provider that supplied the artwork.</param>
private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName);
}
@@ -1,13 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
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.Repositories.MediaContributors;
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.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
@@ -15,6 +17,8 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
@@ -30,7 +34,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
/// <summary>
/// Media library scan job for enriching the metadata of the media library items, using the metadata providers configured for the media library.
/// This should always be the last job in the directed acyclic job graph.
/// The enriched metadata is applied to the books, and the media contributors discovered while enriching the metadata are linked to them.
/// </summary>
internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanMetadataEnrichmentJob
{
@@ -77,23 +81,18 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// 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;
// load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment
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.");
_logger.LogWarning("Failed to read the media library, 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,
@@ -124,34 +123,6 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
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
string? lastPath = null;
// 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)
{
@@ -169,7 +140,12 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
int minUpdateIntervalMs = 100;
int processedBooksCount = 0;
// the contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only
// created once even when the same person is discovered for many books of the same page
Dictionary<string, MediaContributorEntity> contributorsByNormalizedName = [];
// process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
string? lastPath = null;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -185,7 +161,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
{
cancellationToken.ThrowIfCancellationRequested();
await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, artworkProviders, bookArtworkService, libraryName, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false);
await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.BookRepository, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false);
// check if enough time has passed since last update
DateTime now = DateTime.UtcNow;
@@ -202,6 +178,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
// 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();
contributorsByNormalizedName.Clear();
lastPath = booksPage[^1].Path;
}
@@ -211,13 +188,10 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value);
}
// 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;
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
if (Children.Count == 0)
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob child in Children)
@@ -238,22 +212,18 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
}
/// <summary>
/// Enriches the metadata and the artwork of the provided <paramref name="bookEntity"/>, using the provided metadata and artwork providers in their configured order.
/// Enriches the metadata of the provided <paramref name="bookEntity"/>, using the provided metadata providers in their configured order,
/// linking the media contributors discovered while enriching to the book.
/// </summary>
/// <param name="bookEntity">The book whose metadata and artwork are enriched.</param>
/// <param name="bookEntity">The book whose metadata is 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="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, IBookRepository bookRepository, CancellationToken cancellationToken)
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, 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)
@@ -270,26 +240,79 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
LanguageCode: bookEntity.LanguageCode
);
BookMetadataDto? appliedMetadata = shouldAggregateMetadataWhenMissing
ResolvedMetadata? resolvedMetadata = shouldAggregateMetadataWhenMissing
? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false)
: await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false);
if (appliedMetadata is null)
if (resolvedMetadata 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);
// no metadata provider returned usable metadata, mark the book as failed to enrich, keeping its previous metadata
bookEntity.MetadataStatus = MetadataStatus.Failed;
bookEntity.UpdatedOnUtc = DateTime.UtcNow;
bookEntity.UpdatedBy = Guid.NewGuid();
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);
// apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns
book.ApplyMetadata(resolvedMetadata.Metadata);
bookEntity.ApplyMetadataToEntity(book);
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);
// link the media contributors discovered while enriching to the book, finding or creating a single contributor per person
List<BookContributorEntity> linkedContributors = [];
foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? [])
{
if (contributor.Name?.DisplayName is null)
continue;
MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false);
string roleName = contributor.Role?.Name ?? "Contributor";
MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other;
linkedContributors.Add(new BookContributorEntity
{
Id = Guid.NewGuid(),
BookId = bookEntity.Id,
MediaContributorId = contributorEntity.Id,
RoleName = roleName,
RoleCategory = roleCategory,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
});
}
bookEntity.BookContributors.Clear();
bookEntity.BookContributors.AddRange(linkedContributors);
book.UpdateContributors([.. linkedContributors.Select(linkedContributor => Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects.MediaContributorId.Create(linkedContributor.MediaContributorId))]);
// mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern
bookEntity.MetadataStatus = MetadataStatus.Enriched;
bookEntity.MetadataProvider = resolvedMetadata.ProviderName;
bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow;
}
/// <summary>
/// Finds the media contributor with the name of the provided <paramref name="contributor"/>, or creates it, caching it by its normalized display name
/// so that a contributor is only created once even when the same person is discovered for many books of the same page.
/// </summary>
/// <param name="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
/// <param name="contributor">The contributor to find or create.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The found or created media contributor.</returns>
private async Task<MediaContributorEntity> FindOrCreateContributorAsync(IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, MediaContributorDto contributor, CancellationToken cancellationToken)
{
string displayName = contributor.Name!.DisplayName!;
string normalizedDisplayName = displayName.ToLowerInvariant();
if (contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? cachedContributor))
return cachedContributor;
Result<MediaContributorEntity> getContributorResult = await mediaContributorRepository.FindOrCreateByDisplayNameAsync(displayName, null, cancellationToken).ConfigureAwait(false);
if (getContributorResult.IsFailure)
throw new InvalidOperationException(getContributorResult.FirstError.Description);
contributorsByNormalizedName[normalizedDisplayName] = getContributorResult.Value;
return getContributorResult.Value;
}
/// <summary>
@@ -299,8 +322,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
/// <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)
/// <returns>The applied metadata and the provider that supplied it, or <see langword="null"/> when no provider returned usable metadata.</returns>
private static async Task<ResolvedMetadata?> TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
{
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
@@ -310,10 +333,10 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
continue;
Result<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata, metadataProvider.Name, DateTime.UtcNow);
Result<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata);
if (applyMetadataResult.IsFailure)
continue;
return bookMetadata;
return new ResolvedMetadata(bookMetadata, metadataProvider.Name);
}
catch (Exception)
{
@@ -330,8 +353,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
/// <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)
/// <returns>The applied aggregated metadata and the providers that contributed to it, or <see langword="null"/> when no provider returned usable metadata.</returns>
private static async Task<ResolvedMetadata?> AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
{
BookMetadataDto? mergedMetadata = null;
List<string> contributingProviders = [];
@@ -358,52 +381,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
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>
/// 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="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 (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;
}
Result<Success> applyMetadataResult = book.ApplyMetadata(mergedMetadata);
return applyMetadataResult.IsFailure ? null : new ResolvedMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)));
}
/// <summary>
@@ -455,4 +434,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
return Result.Success;
}
/// <summary>
/// The metadata resolved for a book, along with the providers that supplied it.
/// </summary>
/// <param name="Metadata">The resolved metadata of the book.</param>
/// <param name="ProviderName">The name of the provider, or the providers, that supplied the metadata.</param>
private sealed record ResolvedMetadata(BookMetadataDto Metadata, string ProviderName);
}
@@ -0,0 +1,183 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Media library scan job for invalidating the enrichment state of the books whose metadata or artwork provider configuration
/// changed since the last scan, so that they are re-enriched by the enrichment jobs that follow.
/// </summary>
internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : MediaLibraryScanJob, IMediaLibraryScanProviderConfigurationInvalidationJob
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<MediaLibraryScanProviderConfigurationInvalidationJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanProviderConfigurationInvalidationJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">
/// Injected factory for creating scopes in which services are requested.
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
/// </param>
/// <param name="logger">Injected logger used to report the issues encountered while invalidating the enrichment state.</param>
public MediaLibraryScanProviderConfigurationInvalidationJob(IServiceScopeFactory serviceScopeFactory, ILogger<MediaLibraryScanProviderConfigurationInvalidationJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <summary>
/// Executes the payload of the media library scan job.
/// </summary>
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
/// <param name="id">The unique identifier of the media library scan job.</param>
/// <param name="input">The input data to be processed by this payload.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// set the initial progress of the scan job, it's a 1 step job - invalidating the stale enrichment state
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
// load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints
// are compared against the current provider configuration to detect whether it changed since the last scan
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
LibraryEntity library = getLibraryResult.Value;
// load the provider configurations of the media library, whose fingerprint is compared against the stored one
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getMetadataConfigurationsResult.IsFailure)
throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description);
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getArtworkConfigurationsResult.IsFailure)
throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description);
// 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 provider configuration fingerprint will not include the metadata aggregation setting.");
else
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
}
// compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
// changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration
// was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored.
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb);
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, library.CanDownloadMetadataFromWeb);
if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint)
{
Result<Updated> resetMetadataResult = await unitOfWork.BookRepository.ResetMetadataStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (resetMetadataResult.IsFailure)
throw new InvalidOperationException(resetMetadataResult.FirstError.Description);
}
if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint)
{
Result<Updated> resetArtworkResult = await unitOfWork.BookRepository.ResetArtworkStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (resetArtworkResult.IsFailure)
throw new InvalidOperationException(resetArtworkResult.FirstError.Description);
}
// store the current fingerprints, so that the next scan can detect whether the provider configuration changed again.
// the library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository
// update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
library.UpdatedOnUtc = DateTime.UtcNow;
library.UpdatedBy = Guid.NewGuid();
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
Status = LibraryScanJobStatus.Completed;
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
if (Children.Count == 0)
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
catch (Exception exception)
{
Status = LibraryScanJobStatus.Failed;
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "InvalidatingStaleEnrichment");
if (scanJobProgressResult.IsFailure)
return scanJobProgressResult.Errors;
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
}
}
@@ -80,11 +80,24 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
if (getDeletedPathsResult.IsFailure)
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
// get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched
Result<IReadOnlyList<string>> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getChangedPathsResult.IsFailure)
throw new InvalidOperationException(getChangedPathsResult.FirstError.Description);
// apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan
Result<Updated> applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
if (applySnapshotSwapResult.IsFailure)
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
// reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow
if (getChangedPathsResult.Value.Count > 0)
{
Result<Updated> resetEnrichmentStateResult = await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
if (resetEnrichmentStateResult.IsFailure)
throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description);
}
// raise a deletion event for every media library scan snapshot item that is no longer present on disk
foreach (string deletedPath in getDeletedPathsResult.Value)
{
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO.Hashing;
using System.Linq;
using System.Text;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Computes the fingerprint of the provider configuration of a media library, used to detect whether the configuration
/// changed since the last scan, and thus whether the books of the library need their metadata or artwork re-enriched.
/// Any change to the configuration, like adding, removing, reordering, enabling, or disabling a provider, changes the fingerprint.
/// </summary>
internal static class ProviderConfigurationFingerprint
{
/// <summary>
/// Computes the fingerprint of the metadata provider configuration of a media library.
/// </summary>
/// <param name="configurations">The metadata provider configurations of the media library.</param>
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the books is aggregated from multiple providers, when fields are missing.</param>
/// <param name="canDownloadMetadataFromWeb">Whether the media library permits downloading data from the web.</param>
/// <returns>The fingerprint of the metadata provider configuration.</returns>
public static string ComputeMetadataFingerprint(IReadOnlyList<LibraryMetadataProviderConfigurationEntity> configurations, bool shouldAggregateMetadataWhenMissing, bool canDownloadMetadataFromWeb)
{
StringBuilder canonicalRepresentation = new();
foreach (LibraryMetadataProviderConfigurationEntity configuration in configurations.OrderBy(configuration => configuration.Rank))
canonicalRepresentation.Append($"{configuration.PluginId:D}|{configuration.IsEnabled}|{configuration.Rank};");
canonicalRepresentation.Append($"aggregate:{shouldAggregateMetadataWhenMissing};web:{canDownloadMetadataFromWeb};");
return ComputeFingerprint(canonicalRepresentation.ToString());
}
/// <summary>
/// Computes the fingerprint of the artwork provider configuration of a media library.
/// </summary>
/// <param name="configurations">The artwork provider configurations of the media library.</param>
/// <param name="canDownloadMetadataFromWeb">Whether the media library permits downloading data from the web.</param>
/// <returns>The fingerprint of the artwork provider configuration.</returns>
public static string ComputeArtworkFingerprint(IReadOnlyList<LibraryArtworkProviderConfigurationEntity> configurations, bool canDownloadMetadataFromWeb)
{
StringBuilder canonicalRepresentation = new();
foreach (LibraryArtworkProviderConfigurationEntity configuration in configurations.OrderBy(configuration => configuration.Rank))
canonicalRepresentation.Append($"{configuration.PluginId:D}|{configuration.IsEnabled}|{configuration.Rank};");
canonicalRepresentation.Append($"web:{canDownloadMetadataFromWeb};");
return ComputeFingerprint(canonicalRepresentation.ToString());
}
/// <summary>
/// Computes the fingerprint of the provided canonical representation, by hashing it.
/// </summary>
/// <param name="canonicalRepresentation">The canonical representation of the configuration.</param>
/// <returns>The fingerprint of the canonical representation.</returns>
private static string ComputeFingerprint(string canonicalRepresentation)
{
byte[] bytes = Encoding.UTF8.GetBytes(canonicalRepresentation);
ulong hash = XxHash64.HashToUInt64(bytes);
return hash.ToString("X16", CultureInfo.InvariantCulture);
}
}
@@ -69,6 +69,21 @@ internal class FileHashService : IFileHashService
return outputFiles;
}
/// <summary>
/// Computes the content hash of the file stored at <paramref name="filePath"/>, by sampling chunks from it.
/// </summary>
/// <param name="filePath">The path of the file to hash.</param>
/// <returns>The content hash of the file.</returns>
public ulong ComputeFileHash(string filePath)
{
long fileSize = new FileInfo(filePath).Length;
if (fileSize == 0)
return s_emptyFileHash; // precomputed constant: XxHash64 hash of zero-length input
ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, fileSize);
return ComputeFileHash(filePath, fileSize, bufferSize);
}
/// <summary>
/// Computes content hash using memory-mapped sampling.
/// </summary>