diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md
new file mode 100644
index 00000000..ac4ef46c
--- /dev/null
+++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0010.md
@@ -0,0 +1,47 @@
+# Architecture Decision Record (ADR): 0010 - Failure Semantics of the Best-Effort Metadata Enrichment Job
+
+## Status
+**Accepted** (2026-08-09)
+
+## Context
+ADR-0009 established that every media library scan job wraps its execution in a catch-all that marks the job as `Failed` and publishes the `LibraryScanFailedDomainEvent`. That decision applies to the mandatory scan jobs: file system discovery, scan diff, content hashing and scan results save. These jobs are transactional in nature, and a failure in any of them means the file state of the library was not committed.
+
+The metadata enrichment phase runs after the scan results save job, once the file state of the library is committed and the books are materialized. The enrichment phase is best-effort: a book whose metadata could not be retrieved is still browsable with its shell metadata (path and filename-derived title), and a crash mid-enrichment must not roll back the already committed scan results, nor hide the successfully enriched books. This was an explicit product decision: partial enrichment survives a crash, and the scan is not considered failed because a remote metadata provider was unreachable or a provider crashed.
+
+## Decision
+The metadata enrichment job (`MediaLibraryScanMetadataEnrichmentJob`) is a best-effort job with failure semantics that differ from the mandatory jobs of ADR-0009:
+
+- Per-book failures are isolated: a metadata provider that throws, returns unusable metadata, or fails to be applied marks the book as `Failed` (`MetadataStatus.Failed`) and moves to the next book. The other providers are still tried for the same book, and the other books are still processed.
+- Per-provider failures are isolated: a crashing metadata provider does not prevent the other providers from being tried, in their configured order.
+- The scan is considered completed (`LibraryScanFinishedDomainEvent`) after the enrichment phase, even when some books failed to be enriched. The failure is recorded on the books, not on the scan.
+- Only a host-side catastrophic failure of the enrichment job itself (e.g., a storage error) fails the scan, through the existing catch-all of ADR-0009. In that case the file state is already committed, and a re-scan retries the enrichment.
+
+The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`. The event is published by the last job of the directed acyclic job graph: the save job when the library does not permit downloading data from the web (no enrichment phase), or the metadata enrichment job otherwise.
+
+## Consequences
+
+### Positive Outcomes
+| Aspect | Benefit |
+|-----------------------|-----------------------------------------------------------|
+| Partial enrichment | Books successfully enriched before a crash stay browsable and enriched |
+| Provider isolation | A crashing provider does not prevent other providers from being tried |
+| Scan completion | The scan reaches a completed state regardless of enrichment outcome |
+| Retryability | Books with `MetadataStatus.Failed` or `Pending` are re-enriched on the next scan |
+
+### Risks and Tradeoffs
+| Risk | Mitigation Strategy |
+|-------------------------------|-------------------------------------------------------------------|
+| Host failures still fail | Only host-side storage errors fail the scan; re-scan retries enrichment |
+| No per-provider audit trail | Books record the failed status; per-provider error detail is a future refinement |
+
+## Alternatives Considered
+
+### 1. Fail the scan on any enrichment failure
+Keep ADR-0009 semantics for the enrichment job.
+
+**Rejected**: The file state is already committed, and partial enrichment is better than failing a scan that saved the library. Failing the scan would also roll back nothing, while misleading the user about the scan outcome.
+
+### 2. Run enrichment outside the scan lifetime
+Enrich the books asynchronously after the scan, decoupled from the scan progress and cancellation.
+
+**Rejected**: This contradicts the decision that the metadata enrichment phase is part of the scan lifetime, covered by the scan progress reporting and cancellation machinery, so that the scan progress reaches completion only when the metadata is downloaded.
diff --git a/src/Lumina.Application/Common/Infrastructure/Plugins/IPluginManager.cs b/src/Lumina.Application/Common/Infrastructure/Plugins/IPluginManager.cs
new file mode 100644
index 00000000..8ef90497
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Plugins/IPluginManager.cs
@@ -0,0 +1,26 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Plugins;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Plugins;
+
+///
+/// Manager of the plugins loaded by the host application.
+///
+public interface IPluginManager
+{
+ ///
+ /// Gets the plugins that were loaded successfully.
+ ///
+ /// The collection of loaded plugins.
+ IReadOnlyList GetPlugins();
+
+ ///
+ /// Gets the plugin identified by .
+ ///
+ /// The unique identifier of the plugin.
+ /// The plugin, or when no plugin with the provided Id was loaded.
+ IPlugin? GetPlugin(Guid pluginId);
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs
new file mode 100644
index 00000000..0e8fa631
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs
@@ -0,0 +1,137 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Common.ValueObjects.Metadata;
+using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
+using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
+using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+
+///
+/// Extension methods for applying to .
+///
+public static class BookMetadataDtoMapping
+{
+ ///
+ /// Applies the metadata of to , marking its metadata as enriched by the provided .
+ ///
+ /// The domain book to which the metadata is applied.
+ /// The metadata to be applied.
+ /// The name of the metadata provider that enriched the book.
+ /// The date and time when the metadata was enriched.
+ /// An representing either a successful operation, or an error.
+ public static ErrorOr ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc)
+ {
+ if (string.IsNullOrWhiteSpace(metadata.Title))
+ return Domain.SharedKernel.Common.Errors.Errors.Metadata.TitleCannotBeEmpty;
+ if (metadata.ReleaseInfo is null)
+ return Domain.SharedKernel.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull;
+
+ ErrorOr releaseInfoResult = ReleaseInfo.Create(
+ Optional.FromNullable(metadata.ReleaseInfo.OriginalReleaseDate),
+ Optional.FromNullable(metadata.ReleaseInfo.OriginalReleaseYear),
+ Optional.FromNullable(metadata.ReleaseInfo.ReReleaseDate),
+ Optional.FromNullable(metadata.ReleaseInfo.ReReleaseYear),
+ Optional.FromNullable(metadata.ReleaseInfo.ReleaseCountry),
+ Optional.FromNullable(metadata.ReleaseInfo.ReleaseVersion)
+ );
+ if (releaseInfoResult.IsError)
+ return releaseInfoResult.Errors;
+
+ List> domainGenresResult = metadata.Genres is not null
+ ? [.. metadata.Genres.Select(genre => Genre.Create(genre.Name))]
+ : [];
+ List genresErrors = [.. domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors)];
+ if (genresErrors.Count != 0)
+ return genresErrors;
+
+ List> domainTagsResult = metadata.Tags is not null
+ ? [.. metadata.Tags.Select(tag => Tag.Create(tag.Name))]
+ : [];
+ List tagsErrors = [.. domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors)];
+ if (tagsErrors.Count != 0)
+ return tagsErrors;
+
+ Optional languageInfo = Optional.None();
+ if (metadata.Language is not null)
+ {
+ ErrorOr languageInfoResult = LanguageInfo.Create(metadata.Language.LanguageCode, metadata.Language.LanguageName, Optional.FromNullable(metadata.Language.NativeName));
+ if (languageInfoResult.IsError)
+ return languageInfoResult.Errors;
+ languageInfo = languageInfoResult.Value;
+ }
+
+ Optional originalLanguageInfo = Optional.None();
+ if (metadata.OriginalLanguage is not null)
+ {
+ ErrorOr originalLanguageInfoResult = LanguageInfo.Create(metadata.OriginalLanguage.LanguageCode, metadata.OriginalLanguage.LanguageName, Optional.FromNullable(metadata.OriginalLanguage.NativeName));
+ if (originalLanguageInfoResult.IsError)
+ return originalLanguageInfoResult.Errors;
+ originalLanguageInfo = originalLanguageInfoResult.Value;
+ }
+
+ ErrorOr writtenContentMetadataResult = WrittenContentMetadata.Create(
+ metadata.Title,
+ Optional.FromNullable(metadata.OriginalTitle),
+ Optional.FromNullable(metadata.Description),
+ releaseInfoResult.Value,
+ [.. domainGenresResult.Select(genreResult => genreResult.Value)],
+ [.. domainTagsResult.Select(tagResult => tagResult.Value)],
+ languageInfo,
+ originalLanguageInfo,
+ Optional.FromNullable(metadata.Publisher),
+ Optional.FromNullable(metadata.PageCount)
+ );
+ if (writtenContentMetadataResult.IsError)
+ return writtenContentMetadataResult.Errors;
+
+ List> domainIsbnsResult = metadata.Isbns is not null
+ ? [.. metadata.Isbns.Where(isbn => isbn.Value is not null && isbn.Format is not null).Select(isbn => Isbn.Create(isbn.Value, (IsbnFormat)(int)isbn.Format!.Value))]
+ : [];
+ List isbnsErrors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors)];
+ if (isbnsErrors.Count != 0)
+ return isbnsErrors;
+
+ List> domainRatingsResult = metadata.Ratings is not null
+ ? [.. metadata.Ratings.Where(rating => rating.Value is not null && rating.MaxValue is not null).Select(rating => BookRating.Create(
+ rating.Value!.Value,
+ rating.MaxValue!.Value,
+ Optional.FromNullable((BookRatingSource?)(rating.Source is null ? null : (BookRatingSource)(int)rating.Source.Value)),
+ Optional.FromNullable(rating.VoteCount)
+ ))]
+ : [];
+ List ratingsErrors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors)];
+ if (ratingsErrors.Count != 0)
+ return ratingsErrors;
+
+ book.ApplyEnrichedMetadata(
+ writtenContentMetadataResult.Value,
+ Optional.FromNullable(metadata.Format.HasValue ? (BookFormat)(int)metadata.Format.Value : (BookFormat?)null),
+ Optional.FromNullable(metadata.Edition),
+ Optional.FromNullable(metadata.VolumeNumber),
+ Optional.None(),
+ Optional.FromNullable(metadata.ASIN),
+ Optional.FromNullable(metadata.GoodreadsId),
+ Optional.FromNullable(metadata.LCCN),
+ Optional.FromNullable(metadata.OCLCNumber),
+ Optional.FromNullable(metadata.OpenLibraryId),
+ Optional.FromNullable(metadata.LibraryThingId),
+ Optional.FromNullable(metadata.GoogleBooksId),
+ Optional.FromNullable(metadata.BarnesAndNobleId),
+ Optional.FromNullable(metadata.AppleBooksId),
+ [.. domainIsbnsResult.Select(isbnResult => isbnResult.Value)],
+ [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)],
+ providerName,
+ lastUpdateUtc
+ );
+
+ return Result.Success;
+ }
+}
diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj
index ebc70b33..137f8c15 100644
--- a/src/Lumina.Application/Lumina.Application.csproj
+++ b/src/Lumina.Application/Lumina.Application.csproj
@@ -16,6 +16,7 @@
+
diff --git a/src/Lumina.Contracts/DTO/Common/MetadataDto.cs b/src/Lumina.Contracts/DTO/Common/MetadataDto.cs
new file mode 100644
index 00000000..9ad8fe77
--- /dev/null
+++ b/src/Lumina.Contracts/DTO/Common/MetadataDto.cs
@@ -0,0 +1,6 @@
+namespace Lumina.Contracts.DTO.Common;
+
+///
+/// Base type for all metadata returned by a metadata provider.
+///
+public abstract record MetadataDto;
diff --git a/src/Lumina.Contracts/DTO/Common/MetadataLookupDto.cs b/src/Lumina.Contracts/DTO/Common/MetadataLookupDto.cs
new file mode 100644
index 00000000..07023ff2
--- /dev/null
+++ b/src/Lumina.Contracts/DTO/Common/MetadataLookupDto.cs
@@ -0,0 +1,6 @@
+namespace Lumina.Contracts.DTO.Common;
+
+///
+/// Base type for all metadata lookups used to search for media items.
+///
+public abstract record MetadataLookupDto;
diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs
new file mode 100644
index 00000000..24eadae8
--- /dev/null
+++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs
@@ -0,0 +1,41 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+
+///
+/// Data transfer object for the metadata of a book returned by a metadata provider.
+///
+public sealed record BookMetadataDto(
+ string? Title,
+ string? OriginalTitle,
+ string? Description,
+ ReleaseInfoDto? ReleaseInfo,
+ List? Genres,
+ List? Tags,
+ LanguageInfoDto? Language,
+ LanguageInfoDto? OriginalLanguage,
+ string? Publisher,
+ int? PageCount,
+ BookFormat? Format,
+ string? Edition,
+ int? VolumeNumber,
+ BookSeriesDto? Series,
+ string? ASIN,
+ string? GoodreadsId,
+ string? LCCN,
+ string? OCLCNumber,
+ string? OpenLibraryId,
+ string? LibraryThingId,
+ string? GoogleBooksId,
+ string? BarnesAndNobleId,
+ string? AppleBooksId,
+ List? Isbns,
+ List? Contributors,
+ List? Ratings,
+ string? CoverImageUrl
+) : MetadataDto;
diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDto.cs
new file mode 100644
index 00000000..fc931e5b
--- /dev/null
+++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDto.cs
@@ -0,0 +1,28 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+
+///
+/// Data transfer object for a book metadata lookup.
+///
+public sealed record BookMetadataLookupDto(
+ Guid LibraryId,
+ string Path,
+ string? Isbn = null,
+ string? OpenLibraryId = null,
+ string? Title = null,
+ string? Author = null,
+ string? LanguageCode = null
+ //string? Title,
+ //string? OriginalTitle,
+ //int? ReleaseYear,
+ //string? LanguageCode,
+ //IReadOnlyList? Isbns,
+ //string? GoodreadsId,
+ //string? OpenLibraryId,
+ //string? GoogleBooksId
+) : MetadataLookupDto;
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs
deleted file mode 100644
index 638c6827..00000000
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
-using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
-using System.Collections.Generic;
-#endregion
-
-namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
-
-///
-/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph.
-///
-public interface IScanJobRegistry
-{
- ///
- /// Gets the media library scan jobs registered for the provided .
- ///
- /// The name of the hook point at which the media library scan jobs were injected.
- /// The unique identifier of the media library upon which the scan is performed.
- /// The collection of media library scan jobs registered at the provided hook point.
- IEnumerable GetJobsForHook(string hookName, LibraryId libraryId);
-}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs
deleted file mode 100644
index 7dc27477..00000000
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
-
-///
-/// Defines the named junction points of the media library scan job graph where plugin jobs can be injected.
-///
-public static class ScanJobHooks
-{
- ///
- /// The hook that runs after the file system discovery job, and before the scan diff job.
- ///
- public const string AFTER_FILE_SYSTEM_DISCOVERY = "AfterFileSystemDiscovery";
-
- ///
- /// The hook that runs after the scan diff job, and before the scan hash job.
- ///
- public const string AFTER_SCAN_DIFF = "AfterScanDiff";
-
- ///
- /// The hook that runs after the scan hash job, and before any metadata enrichment jobs.
- ///
- public const string BEFORE_METADATA_ENRICHMENT = "BeforeMetadataEnrichment";
-
- ///
- /// The hook that runs after any metadata enrichment jobs, and before the scan results save job.
- ///
- public const string AFTER_METADATA_ENRICHMENT = "AfterMetadataEnrichment";
-
- ///
- /// The hook that runs before the scan results save job, which should always be the last job in the directed acyclic job graph.
- ///
- public const string BEFORE_SCAN_RESULTS_SAVE = "BeforeScanResultsSave";
-}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanMetadataEnrichmentJob.cs
new file mode 100644
index 00000000..23d633f7
--- /dev/null
+++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanMetadataEnrichmentJob.cs
@@ -0,0 +1,8 @@
+namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
+
+///
+/// Interface for the media library scan job for enriching the metadata of the media library items.
+///
+public interface IMediaLibraryScanMetadataEnrichmentJob : IMediaLibraryScanJob
+{
+}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs
index 21a58224..af55a807 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using System.Collections.Generic;
@@ -15,7 +15,7 @@ public interface IMediaTypeScanner
///
/// The media library type that this media library scanner supports.
///
- LibraryType SupportedType { get; }
+ LibraryType SupportedLibraryType { get; }
///
/// Creates the media library scan jobs for the provided media library.
diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IGoodReadsMetadataScrapJob.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IGoodReadsMetadataScrapJob.cs
deleted file mode 100644
index 9dc7196e..00000000
--- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IGoodReadsMetadataScrapJob.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
-
-#endregion
-
-namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
-
-///
-/// Interface for the media library scan job for retrieving written content metadata from GoodReads.
-///
-public interface IGoodReadsMetadataScrapJob : IMediaLibraryScanJob
-{
-}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs
index 5c02cdce..28805417 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs
@@ -1,9 +1,8 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
-using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
#endregion
@@ -15,22 +14,19 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext
internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
{
private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory;
- private readonly IScanJobRegistry _scanJobRegistry;
///
/// The media library type that this media library scanner supports.
///
- public LibraryType SupportedType { get; } = LibraryType.Book;
+ public LibraryType SupportedLibraryType { get; } = LibraryType.Book;
///
/// Initializes a new instance of the class.
///
/// Injected factory for creating media library scan jobs.
- /// Injected registry of the media library scan jobs injected by plugins at the defined hook points.
- public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory, IScanJobRegistry scanJobRegistry)
+ public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory)
{
_mediaScanJobFactory = mediaScanJobFactory;
- _scanJobRegistry = scanJobRegistry;
}
///
@@ -45,51 +41,28 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId);
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob(libraryId);
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob(libraryId);
- IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob(libraryId);
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob(libraryId);
- // establish the hierarchical relationships between jobs, splicing the plugin jobs at the defined hook points
- IMediaLibraryScanJob previousJob = fileSystemDiscoveryJob;
- previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.AFTER_FILE_SYSTEM_DISCOVERY, libraryId);
- previousJob.AddChild(mediaLibraryScanDiffJob);
- mediaLibraryScanDiffJob.AddParent(previousJob);
+ // establish the hierarchical relationships between jobs
+ fileSystemDiscoveryJob.AddChild(mediaLibraryScanDiffJob);
+ mediaLibraryScanDiffJob.AddParent(fileSystemDiscoveryJob);
- previousJob = SpliceJobsAtHook(mediaLibraryScanDiffJob, ScanJobHooks.AFTER_SCAN_DIFF, libraryId);
- previousJob.AddChild(mediaLibraryScanHashJob);
- mediaLibraryScanHashJob.AddParent(previousJob);
+ mediaLibraryScanDiffJob.AddChild(mediaLibraryScanHashJob);
+ mediaLibraryScanHashJob.AddParent(mediaLibraryScanDiffJob);
- previousJob = SpliceJobsAtHook(mediaLibraryScanHashJob, ScanJobHooks.BEFORE_METADATA_ENRICHMENT, libraryId);
+ mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob);
+ mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob);
+
+ // when the library permits downloading data from the web, the metadata enrichment job is the last job in the directed acyclic job graph,
+ // running after the scan results save job, so that the books are materialized before their metadata is enriched
if (downloadMetadataFromWeb)
{
- previousJob.AddChild(goodReadsMetadataScrapJob);
- goodReadsMetadataScrapJob.AddParent(previousJob);
- previousJob = goodReadsMetadataScrapJob;
+ IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId);
+ mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob);
+ mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob);
}
- previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.AFTER_METADATA_ENRICHMENT, libraryId);
- previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.BEFORE_SCAN_RESULTS_SAVE, libraryId);
- previousJob.AddChild(mediaLibraryScanResultsSaveJob);
- mediaLibraryScanResultsSaveJob.AddParent(previousJob);
// return the top level jobs that will be triggered when the scan will be started
yield return fileSystemDiscoveryJob;
}
-
- ///
- /// Splices the plugin jobs registered at the provided after the , and returns the last job of the extended chain.
- ///
- /// The job after which the plugin jobs are spliced.
- /// The name of the hook point at which the plugin jobs are injected.
- /// The unique identifier of the media library upon which the scan is performed.
- /// The last job of the extended chain, which can be used as the parent for the next job.
- private IMediaLibraryScanJob SpliceJobsAtHook(IMediaLibraryScanJob previousJob, string hookName, LibraryId libraryId)
- {
- IMediaLibraryScanJob currentJob = previousJob;
- foreach (IMediaLibraryScanJob pluginJob in _scanJobRegistry.GetJobsForHook(hookName, libraryId))
- {
- currentJob.AddChild(pluginJob);
- pluginJob.AddParent(currentJob);
- currentJob = pluginJob;
- }
- return currentJob;
- }
}
diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
index 078aa845..df81983e 100644
--- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
+++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
@@ -4,11 +4,12 @@ using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
+using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
+using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
-using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
@@ -18,17 +19,21 @@ using Lumina.Infrastructure.Core.Authorization;
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
-using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
+using Lumina.Infrastructure.Core.Plugins;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Time;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
+using System.IO;
using System.Reflection;
#endregion
@@ -44,8 +49,9 @@ public static class InfrastructureLayerServices
/// Extension method for adding the Infrastructure layer services to the DI container.
///
/// The service collection to add the services to.
+ /// The configuration manager used to read the application configuration.
/// The updated .
- public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services)
+ public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services, IConfiguration configuration)
{
// scan the current assembly for validators and add them to the DI container
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton);
@@ -70,16 +76,29 @@ public static class InfrastructureLayerServices
services.AddSingleton();
services.AddSingleton();
services.AddHostedService();
- services.AddSingleton(serviceProvider => new ScanJobRegistry(serviceProvider, new Dictionary>()));
services.AddTransient();
services.AddTransient();
services.AddTransient();
- services.AddTransient();
services.AddTransient();
+ services.AddTransient();
services.AddSingleton();
+
+ // plugins: load the plugin assemblies from the plugins directory, register their services and provide the plugin manager
+ string pluginsDirectorySetting = configuration.GetSection(PluginsSettingsDto.SECTION_NAME)["Directory"] ?? "plugins";
+ string pluginsDirectory = Path.Combine(AppContext.BaseDirectory, pluginsDirectorySetting);
+ PluginLoadResult pluginLoadResult = PluginLoader.LoadPlugins(pluginsDirectory, services);
+ services.AddSingleton(new PluginManager(pluginLoadResult.Plugins));
+ services.AddScoped();
+ services.AddSingleton(serviceProvider => new PluginDetectionSyncJob(
+ serviceProvider.GetRequiredService(),
+ serviceProvider.GetRequiredService(),
+ pluginLoadResult.Errors,
+ serviceProvider.GetRequiredService>()));
+ services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService());
+
return services;
}
}
diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs
index e9e5ce4a..c7a2a772 100644
--- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs
+++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.Infrastructure.Models.Configuration;
-using Lumina.Infrastructure.Common.Models.Configuration;
+using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
+using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Utilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -35,33 +35,38 @@ public static class SharedConfiguration
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
// bind the appsettings sections
- services.AddOptions()
- .Bind(configuration.GetRequiredSection(CommonSettingsModel.SECTION_NAME))
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(CommonSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
- services.AddOptions()
- .Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SECTION_NAME))
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(DatabaseSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
- services.AddOptions()
- .Bind(configuration.GetRequiredSection(MediaSettingsModel.SECTION_NAME))
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(MediaSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
- services.AddOptions()
- .Bind(configuration.GetRequiredSection(JwtSettingsModel.SECTION_NAME))
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(PluginsSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
- services.AddOptions()
- .Bind(configuration.GetRequiredSection(CorsSettingsModel.SECTION_NAME))
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(JwtSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
- services.AddOptions()
- .Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(CorsSettingsDto.SECTION_NAME))
+ .ValidateFluently()
+ .ValidateOnStart();
+
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(EncryptionSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
index fedbfc2a..493f5595 100644
--- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
+++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
@@ -24,5 +24,6 @@ public static partial class Errors
public static Error JwtAudienceCannotBeEmpty => Error.Validation(description: nameof(JwtAudienceCannotBeEmpty));
public static Error CorsOriginsCannotBeEmpty => Error.Validation(description: nameof(CorsOriginsCannotBeEmpty));
public static Error CorsOriginIsInvalid => Error.Validation(description: nameof(CorsOriginIsInvalid));
+ public static Error PluginsDirectoryCannotBeEmpty => Error.Validation(description: nameof(PluginsDirectoryCannotBeEmpty));
}
}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs
new file mode 100644
index 00000000..a134c27d
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs
@@ -0,0 +1,262 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.Entities.Plugins;
+using Lumina.Application.Common.DataAccess.Repositories.Books;
+using Lumina.Application.Common.DataAccess.Repositories.Plugins;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+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.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Mediator;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
+
+///
+/// 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.
+///
+internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanMetadataEnrichmentJob
+{
+ 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 _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ ///
+ /// 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.
+ ///
+ /// Injected logger used to report the issues encountered while enriching the metadata.
+ public MediaLibraryScanMetadataEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger logger)
+ {
+ _serviceScopeFactory = serviceScopeFactory;
+ _logger = logger;
+ }
+
+ ///
+ /// Executes the payload of the media library scan job.
+ ///
+ /// The type of the input parameter representing the data to be processed by this payload.
+ /// The unique identifier of the media library scan job.
+ /// The input data to be processed by this payload.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(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()!;
+ IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!;
+ ILibraryMetadataProviderConfigurationRepository configurationRepository = unitOfWork.GetRepository();
+ IBookRepository bookRepository = unitOfWork.GetRepository();
+
+ 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
+ ErrorOr> getConfigurationsResult = await configurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getConfigurationsResult.IsError)
+ throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
+ List providers = [];
+ foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
+ {
+ List configuredProviders = [.. asyncServiceScope.ServiceProvider
+ .GetKeyedServices(configuration.PluginId)
+ .Where(provider => provider.SupportedLibraryType == LibraryType.Book)];
+ 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);
+ }
+
+ // count the books that need their metadata enriched, for progress reporting purposes
+ ErrorOr getBooksToEnrichCountResult = await bookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getBooksToEnrichCountResult.IsError)
+ throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
+ int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
+
+ // set the initial progress of the scan job
+ ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishJobProgressResult.IsError)
+ 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)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ ErrorOr> getBooksPageResult = await bookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
+ if (getBooksPageResult.IsError)
+ throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
+ IReadOnlyList booksPage = getBooksPageResult.Value;
+ if (booksPage.Count == 0)
+ break;
+
+ foreach (BookEntity bookEntity in booksPage)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ await EnrichBookAsync(bookEntity, providers, 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 PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishJobProgressResult.IsError)
+ throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
+ lastUpdateTime = now;
+ }
+ }
+
+ lastPath = booksPage[^1].Path;
+ }
+
+ 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 publisher.Publish(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);
+ }
+ }
+
+ ///
+ /// Enriches the metadata of the provided , using the provided in their configured order.
+ ///
+ /// The book whose metadata is enriched.
+ /// The metadata providers, in their configured order.
+ /// The repository used to persist the enriched metadata.
+ /// Cancellation token that can be used to stop the execution.
+ private static async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList providers, IBookRepository bookRepository, CancellationToken cancellationToken)
+ {
+ // convert the book to a domain object
+ ErrorOr getBookResult = bookEntity.ToDomainEntity();
+ if (getBookResult.IsError)
+ return;
+ Book book = getBookResult.Value;
+
+ BookMetadataLookupDto lookup = 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
+ OpenLibraryId: bookEntity.OpenLibraryId,
+ Title: bookEntity.Title,
+ Author: null,
+ LanguageCode: bookEntity.LanguageCode
+ );
+
+ // try the metadata providers in order, until one returns usable metadata
+ foreach (IRemoteMetadataProvider provider in providers)
+ {
+ try
+ {
+ MetadataDto? metadataResult = await provider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
+ if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
+ continue;
+
+ ErrorOr applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow);
+ if (applyMetadataResult.IsError)
+ continue;
+
+ ErrorOr updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (updateBookResult.IsError)
+ continue;
+
+ return;
+ }
+ catch (Exception)
+ {
+ // a failing metadata provider must not prevent the other providers from being tried
+ }
+ }
+
+ // no metadata provider returned usable metadata, mark the book as failed to enrich
+ book.MarkMetadataAsFailed();
+ await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Determines whether the provided is usable, meaning it has a title and at least one primary identifier.
+ ///
+ /// The metadata to validate.
+ /// when the metadata is usable, otherwise .
+ private static bool IsUsableMetadata(BookMetadataDto metadata)
+ {
+ 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);
+ }
+
+ ///
+ /// Publishes a job progress update.
+ ///
+ /// The service used to publish the progress update.
+ /// The composite unique identifier of a media library scan.
+ /// The current job progress.
+ /// The total job progress.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
+ {
+ ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata");
+ if (scanJobProgressResult.IsError)
+ return scanJobProgressResult.Errors;
+
+ await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
+ Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
+
+ return Result.Success;
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs
index 675d269d..2f8cc33a 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs
@@ -1,8 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
-using Lumina.Domain.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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;
@@ -10,6 +13,9 @@ using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -86,15 +92,40 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
await publisher.Publish(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
+ // materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata
+ ErrorOr> getPathsResult = await libraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getPathsResult.IsError)
+ throw new InvalidOperationException(getPathsResult.FirstError.Description);
+ IBookRepository bookRepository = unitOfWork.GetRepository();
+ foreach (string path in getPathsResult.Value)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ ErrorOr getExistingBookResult = await bookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false);
+ if (getExistingBookResult.IsError)
+ throw new InvalidOperationException(getExistingBookResult.FirstError.Description);
+ if (getExistingBookResult.Value is not null)
+ continue;
+
+ ErrorOr insertBookResult = await bookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
+ if (insertBookResult.IsError)
+ throw new InvalidOperationException(insertBookResult.FirstError.Description);
+ }
+ await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
- // this job finished, and it's the last in the chain, the scan is completed
Status = LibraryScanJobStatus.Completed;
- await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
- // this should always be the last job in the directed acyclic job graph, so no linked child to call further
+ // 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 publisher.Publish(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);
}
}
@@ -129,4 +160,38 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
return Result.Success;
}
+
+ ///
+ /// Creates a shell book entity for the file stored at in the media library identified by ,
+ /// with a title derived from the file name, and no web metadata yet.
+ ///
+ /// The Id of the media library the book belongs to.
+ /// The file system path of the book.
+ /// The created shell book entity.
+ private static BookEntity CreateShellBookEntity(Guid libraryId, string path)
+ {
+ return new BookEntity
+ {
+ Id = Guid.NewGuid(),
+ LibraryId = libraryId,
+ Path = path,
+ Title = GetTitleFromPath(path),
+ MetadataStatus = MetadataStatus.Pending,
+ CreatedOnUtc = DateTime.UtcNow,
+ CreatedBy = Guid.Empty,
+ UpdatedBy = null
+ };
+ }
+
+ ///
+ /// Derives a book title from the file name of the provided , by removing the extension and replacing separators with spaces.
+ ///
+ /// The file system path of the book.
+ /// The derived title.
+ private static string GetTitleFromPath(string path)
+ {
+ string fileName = Path.GetFileNameWithoutExtension(path);
+ string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim();
+ return title.Length > 0 ? title : fileName;
+ }
}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs
deleted file mode 100644
index 1f77daf0..00000000
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
-using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
-using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
-using Microsoft.Extensions.DependencyInjection;
-using System;
-using System.Collections.Generic;
-#endregion
-
-namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs;
-
-///
-/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph.
-///
-internal sealed class ScanJobRegistry : IScanJobRegistry
-{
- private readonly IServiceProvider _serviceProvider;
- private readonly IReadOnlyDictionary> _jobsByHook;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The service provider, used to resolve the registered plugin jobs.
- /// The media library scan job types registered for each hook point, provided by the composition root of the plugin system.
- public ScanJobRegistry(IServiceProvider serviceProvider, IReadOnlyDictionary> jobsByHook)
- {
- _serviceProvider = serviceProvider;
- _jobsByHook = jobsByHook;
- }
-
- ///
- /// Gets the media library scan jobs registered for the provided .
- ///
- /// The name of the hook point at which the media library scan jobs were injected.
- /// The unique identifier of the media library upon which the scan is performed.
- /// The collection of media library scan jobs registered at the provided hook point.
- public IEnumerable GetJobsForHook(string hookName, LibraryId libraryId)
- {
- // no plugin jobs are registered for this hook point, unless the plugin system provides them
- if (!_jobsByHook.TryGetValue(hookName, out IReadOnlyList? jobTypes))
- yield break;
-
- foreach (Type jobType in jobTypes)
- {
- IMediaLibraryScanJob pluginJob = (IMediaLibraryScanJob)_serviceProvider.GetRequiredService(jobType);
- pluginJob.LibraryId = libraryId;
- yield return pluginJob;
- }
- }
-}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs
deleted file mode 100644
index f0e2c15d..00000000
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs
+++ /dev/null
@@ -1,162 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
-using Lumina.Application.Common.DataAccess.UoW;
-using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
-using Lumina.Domain.Common.Enums.MediaLibrary;
-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.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
-using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
-using Mediator;
-using Microsoft.Extensions.DependencyInjection;
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
-
-///
-/// Media library scan job for retrieving written content metadata from GoodReads.
-///
-internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob
-{
- private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of media library items that are enriched in a single batch, keeping the peak memory bounded regardless of the library size
- private readonly IServiceScopeFactory _serviceScopeFactory;
-
- ///
- /// Initializes a new instance of the class.
- ///
- ///
- /// 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.
- ///
- public GoodReadsMetadataScrapJob(IServiceScopeFactory serviceScopeFactory)
- {
- _serviceScopeFactory = serviceScopeFactory;
- }
-
- ///
- /// Executes the payload of the media library scan job.
- ///
- /// The type of the input parameter representing the data to be processed by this payload.
- /// The unique identifier of the media library scan job.
- /// The input data to be processed by this payload.
- /// Cancellation token that can be used to stop the execution.
- public override async Task ExecuteAsync(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()!;
- IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!;
- ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository();
-
- MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
-
- // count the media library items that need their metadata enriched, which are the items that were new or changed in this scan
- ErrorOr getItemsToEnrichCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
- if (getItemsToEnrichCountResult.IsError)
- throw new InvalidOperationException(getItemsToEnrichCountResult.FirstError.Description);
- int totalItemsToEnrich = getItemsToEnrichCountResult.Value;
-
- // set the initial progress of the scan job
- ErrorOr publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
- if (publishJobProgressResult.IsError)
- throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
-
- DateTime lastUpdateTime = DateTime.UtcNow;
- int minUpdateIntervalMs = 100;
- int processedItemsCount = 0;
- string? lastPath = null;
-
- // process the media library items that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
- while (true)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- ErrorOr> getItemsToEnrichPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
- if (getItemsToEnrichPageResult.IsError)
- throw new InvalidOperationException(getItemsToEnrichPageResult.FirstError.Description);
- IReadOnlyList itemsToEnrichPage = getItemsToEnrichPageResult.Value;
- if (itemsToEnrichPage.Count == 0)
- break;
-
- // TODO: retrieve the metadata of each media library item from GoodReads, and store it, once the real scraping is implemented
- foreach (HashedFileSystemFile item in itemsToEnrichPage)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- // 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 PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedItemsCount), totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
- if (publishJobProgressResult.IsError)
- throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
- lastUpdateTime = now;
- }
- }
-
- lastPath = itemsToEnrichPage[^1].Path;
- }
-
- // this job finished, increment the number of processed jobs progress
- await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
- Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
- Status = LibraryScanJobStatus.Completed;
-
- // 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);
- }
- }
-
- ///
- /// Publishes a job progress update.
- ///
- /// The service used to publish the progress update.
- /// The composite unique identifier of a media library scan.
- /// The current job progress.
- /// The total job progress.
- /// Cancellation token that can be used to stop the execution.
- /// An representing either a successful operation, or an error.
- private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
- {
- ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "GoodReadsMetadataDownload");
- if (scanJobProgressResult.IsError)
- return scanJobProgressResult.Errors;
-
- await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
- Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
-
- return Result.Success;
- }
-}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs
index bc994143..ea1bf1c7 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs
@@ -4,7 +4,7 @@ using ErrorOr;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Contracts.Responses.MediaLibrary.Management;
-using Lumina.Domain.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Microsoft.AspNetCore.SignalR;
@@ -79,7 +79,8 @@ public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibrarySca
if (!progressResult.IsError)
{
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
- await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync("libraryScanFinishedEvent", progress, cancellationToken).ConfigureAwait(false);
+ await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync(
+ "libraryScanFinishedEvent", progress with { Status = LibraryScanJobStatus.Completed.ToString() }, cancellationToken).ConfigureAwait(false);
}
}
diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs
new file mode 100644
index 00000000..25f0ab67
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs
@@ -0,0 +1,76 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Application.Common.DataAccess.Entities.Plugins;
+using Lumina.Application.Common.DataAccess.Repositories.Plugins;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Plugins;
+using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.Core.Plugins;
+
+///
+/// Background job that persists the detection of the loaded plugins into the storage medium at startup.
+///
+internal sealed class PluginDetectionSyncJob : BackgroundService
+{
+ private readonly IServiceScopeFactory _serviceScopeFactory;
+ private readonly IPluginManager _pluginManager;
+ private readonly IReadOnlyList _loadErrors;
+ private readonly ILogger _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected factory for creating scopes in which services are requested.
+ /// Injected manager of the plugins loaded by the host application.
+ /// The errors that occurred while loading the plugins.
+ /// Injected logger used for logging.
+ public PluginDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IPluginManager pluginManager, IReadOnlyList loadErrors, ILogger logger)
+ {
+ _serviceScopeFactory = serviceScopeFactory;
+ _pluginManager = pluginManager;
+ _loadErrors = loadErrors;
+ _logger = logger;
+ }
+
+ ///
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ foreach (string loadError in _loadErrors)
+ _logger.LogWarning("Plugin load failure: {LoadError}", loadError);
+
+ await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
+ IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService();
+ IPluginRepository pluginRepository = unitOfWork.GetRepository();
+
+ foreach (IPlugin plugin in _pluginManager.GetPlugins())
+ {
+ PluginEntity pluginEntity = new()
+ {
+ Id = plugin.Id,
+ Name = plugin.Name,
+ Author = plugin.Author,
+ Version = plugin.Version.ToString(),
+ Description = plugin.Description,
+ LoadStatus = PluginLoadStatus.Loaded,
+ CreatedOnUtc = DateTime.UtcNow,
+ CreatedBy = default,
+ UpdatedBy = default
+ };
+ ErrorOr upsertResult = await pluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
+ if (upsertResult.IsError)
+ _logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
+ }
+
+ await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginLoadContext.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginLoadContext.cs
new file mode 100644
index 00000000..5097a35b
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/Plugins/PluginLoadContext.cs
@@ -0,0 +1,48 @@
+#region ========================================================================= USING =====================================================================================
+using System.IO;
+using System.Reflection;
+using System.Runtime.Loader;
+#endregion
+
+namespace Lumina.Infrastructure.Core.Plugins;
+
+///
+/// Assembly load context of a single plugin, resolving the shared host assemblies from the default context and the plugin local dependencies from the plugin directory.
+///
+internal sealed class PluginLoadContext : AssemblyLoadContext
+{
+ private readonly string _pluginDirectory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The directory where the plugin assemblies and their dependencies are located.
+ /// The name of the load context.
+ public PluginLoadContext(string pluginDirectory, string name) : base(name, isCollectible: true)
+ {
+ _pluginDirectory = pluginDirectory;
+ }
+
+ ///
+ protected override Assembly? Load(AssemblyName assemblyName)
+ {
+ if (assemblyName.Name is null)
+ return null;
+
+ // try to resolve the assembly from the default context first, so that the plugin shares the host and framework assemblies
+ try
+ {
+ return AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName);
+ }
+ catch (FileNotFoundException)
+ {
+ }
+
+ // fall back to resolving the assembly from the plugin directory
+ string dependencyPath = Path.Combine(_pluginDirectory, assemblyName.Name + ".dll");
+ if (File.Exists(dependencyPath))
+ return LoadFromAssemblyPath(dependencyPath);
+
+ return null;
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs
new file mode 100644
index 00000000..446c772e
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+#endregion
+
+namespace Lumina.Infrastructure.Core.Plugins;
+
+///
+/// Result of loading the plugins from the plugins directory.
+///
+/// The plugins that were loaded successfully.
+/// The errors that occurred while loading the plugins.
+internal sealed record PluginLoadResult(IReadOnlyList Plugins, IReadOnlyList Errors);
+
+///
+/// Loads the plugins from the plugins directory, discovers their descriptors and registers their services.
+///
+internal static class PluginLoader
+{
+ ///
+ /// Loads the plugins from the , discovers their descriptors and registers their services.
+ ///
+ /// The directory where the plugin assemblies are located.
+ /// The service collection to which the plugin services are added.
+ /// The result of loading the plugins.
+ public static PluginLoadResult LoadPlugins(string pluginsDirectory, IServiceCollection services)
+ {
+ List plugins = [];
+ List errors = [];
+
+ if (!Directory.Exists(pluginsDirectory))
+ return new PluginLoadResult(plugins, errors);
+
+ foreach (string assemblyPath in Directory.EnumerateFiles(pluginsDirectory, "*.dll"))
+ {
+ // a failing plugin must not prevent the other plugins from loading, so each assembly is isolated in its own load context
+ PluginLoadContext loadContext = new(pluginsDirectory, Path.GetFileNameWithoutExtension(assemblyPath));
+ try
+ {
+ Assembly assembly = loadContext.LoadFromAssemblyPath(assemblyPath);
+ foreach (Type type in assembly.GetTypes())
+ {
+ if (type.IsClass && !type.IsAbstract && typeof(IPlugin).IsAssignableFrom(type))
+ {
+ IPlugin plugin = (IPlugin)Activator.CreateInstance(type)!;
+ if (plugin is IPluginServiceRegistrator serviceRegistrator)
+ serviceRegistrator.RegisterServices(services);
+ plugins.Add(plugin);
+ break; // only one plugin descriptor per assembly
+ }
+ }
+ }
+ catch (Exception exception)
+ {
+ errors.Add($"Failed to load plugin assembly '{Path.GetFileName(assemblyPath)}': {exception.Message}");
+ }
+ }
+
+ return new PluginLoadResult(plugins, errors);
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginManager.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginManager.cs
new file mode 100644
index 00000000..07a84af2
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/Plugins/PluginManager.cs
@@ -0,0 +1,38 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Plugins;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+#endregion
+
+namespace Lumina.Infrastructure.Core.Plugins;
+
+///
+/// Manager of the plugins loaded by the host application.
+///
+internal sealed class PluginManager : IPluginManager
+{
+ private readonly IReadOnlyDictionary _pluginsById;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The plugins that were loaded successfully.
+ public PluginManager(IEnumerable plugins)
+ {
+ _pluginsById = plugins.ToDictionary(plugin => plugin.Id);
+ }
+
+ ///
+ public IReadOnlyList GetPlugins()
+ {
+ return [.. _pluginsById.Values];
+ }
+
+ ///
+ public IPlugin? GetPlugin(Guid pluginId)
+ {
+ return _pluginsById.GetValueOrDefault(pluginId);
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs
new file mode 100644
index 00000000..d0ef241b
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs
@@ -0,0 +1,49 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using Lumina.Application.Common.DataAccess.Entities.Plugins;
+using Lumina.Application.Common.DataAccess.Repositories.Plugins;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Mapping.Plugins;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.Core.Plugins;
+
+///
+/// Reads the settings persisted by the host for a plugin.
+///
+internal sealed class PluginSettingsStore : IPluginSettingsStore
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ILogger _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected logger used to report the failures to read the plugin settings.
+ public PluginSettingsStore(IUnitOfWork unitOfWork, ILogger logger)
+ {
+ _unitOfWork = unitOfWork;
+ _logger = logger;
+ }
+
+ ///
+ public async Task?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken)
+ {
+ IPluginRepository pluginRepository = _unitOfWork.GetRepository();
+ ErrorOr getPluginResult = await pluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
+ if (getPluginResult.IsError)
+ {
+ _logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description);
+ return null;
+ }
+
+ return getPluginResult.Value?.ToSettings();
+ }
+}
diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj
index 38e5433f..33aec118 100644
--- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj
+++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj
@@ -44,5 +44,6 @@
+
diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json
index 8343e8e2..af9eda89 100644
--- a/src/Lumina.Infrastructure/appsettings.shared.json
+++ b/src/Lumina.Infrastructure/appsettings.shared.json
@@ -3,6 +3,9 @@
"RootDirectory": "media",
"LibrariesDirectory": "libraries"
},
+ "PluginsSettings": {
+ "Directory": "plugins"
+ },
"CommonSettings": {
"Theme": "LuminaDark"
},
diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs
index 3e3482bb..9f663160 100644
--- a/src/Lumina.Presentation.Api/Program.cs
+++ b/src/Lumina.Presentation.Api/Program.cs
@@ -47,7 +47,7 @@ public class Program
builder.Services.AddPresentationApiLayerServices(builder.Configuration);
builder.Services.AddApplicationLayerServices();
- builder.Services.AddInfrastructureLayerServices();
+ builder.Services.AddInfrastructureLayerServices(builder.Configuration);
builder.Services.AddDataAccessLayerServices();
builder.Services.AddDomainLayerServices();
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx
index 167b3211..fd3f500c 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx
@@ -186,8 +186,8 @@
Filmreihe
-
- Metadaten werden von GoodReads heruntergeladen...
+
+ Metadaten werden angereichert...
Berechne die Datei-Hashes...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx
index a04e2a83..b5b3f263 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx
@@ -186,8 +186,8 @@
Film Series
-
- Downloading metadata from GoodReads...
+
+ Enriching metadata...
Hashing file contents...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx
index ca26806a..18ea70c2 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx
@@ -186,8 +186,8 @@
Saga Cinematográfica
-
- Descargando metadatos de GoodReads...
+
+ Enriqueciendo metadatos...
Calculando los hashes de los archivos...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx
index 217d4007..3ca27a25 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx
@@ -186,8 +186,8 @@
Saga Cinématographique
-
- Téléchargement des métadonnées depuis GoodReads...
+
+ Enrichissement des métadonnées...
Calcul des hachages des fichiers...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx
index f44f35d0..9387d8eb 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx
@@ -186,8 +186,8 @@
Saga Cinematografica
-
- Scaricamento dei metadati da GoodReads...
+
+ Arricchimento dei metadati...
Calcolo degli hash dei file...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx
index 525c1e48..a88d1ea1 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx
@@ -186,8 +186,8 @@
映画シリーズ
-
- GoodReadsからメタデータをダウンロード中...
+
+ メタデータを補完しています...
ファイルのハッシュを計算中...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx
index a04e2a83..b5b3f263 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx
@@ -186,8 +186,8 @@
Film Series
-
- Downloading metadata from GoodReads...
+
+ Enriching metadata...
Hashing file contents...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx
index 17941f34..b1735455 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx
@@ -186,8 +186,8 @@
Serie de Filme
-
- Se descarcă metadate de pe GoodReads...
+
+ Se îmbogățesc metadatele...
Se calculează hash-urile fișierelor...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx
index c6fde0d8..98adbae1 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx
@@ -186,8 +186,8 @@
Киносерия
-
- Загрузка метаданных из GoodReads...
+
+ Обогащение метаданных...
Вычисление хешей файлов...
diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx
index b19516a5..fa8f6f81 100644
--- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx
+++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx
@@ -186,8 +186,8 @@
电影系列
-
- 正在从GoodReads下载元数据...
+
+ 正在丰富元数据...
正在计算文件哈希...
diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml
index 4247df20..7b4d6646 100644
--- a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml
+++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml
@@ -171,7 +171,7 @@
DiscoveringFiles: '@_localizer["DiscoveringFiles"]',
ComparingFileHashes: '@_localizer["ComparingFileHashes"]',
HashingFileContents: '@_localizer["HashingFileContents"]',
- GoodReadsMetadataDownload: '@_localizer["GoodReadsMetadataDownload"]',
+ EnrichingMetadata: '@_localizer["EnrichingMetadata"]',
SavingScanData: '@_localizer["SavingScanData"]'
};
const jsLocalizedLibraryTypes = {
diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Fakes/FakeBookMetadataProvider.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Fakes/FakeBookMetadataProvider.cs
new file mode 100644
index 00000000..264bcdb7
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Fakes/FakeBookMetadataProvider.cs
@@ -0,0 +1,127 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.Contracts.Core.Plugins.Settings;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.Contracts.UnitTests.Fakes;
+
+///
+/// A fake book metadata provider used to exercise the plugin contracts from outside.
+///
+public sealed class FakeBookMetadataProvider : IPlugin, IPluginServiceRegistrator, IRemoteMetadataProvider
+{
+ ///
+ public Guid Id { get; } = Guid.Parse("11111111-1111-1111-1111-111111111111");
+
+ ///
+ public string Name { get; } = "Fake Book Metadata Provider";
+
+ ///
+ public string Author { get; } = "Lumina";
+
+ ///
+ public Version Version { get; } = new(1, 0, 0);
+
+ ///
+ public string Description { get; } = "A fake metadata provider used to exercise the plugin contracts.";
+
+ ///
+ public LibraryType SupportedLibraryType { get; } = LibraryType.Book;
+
+ ///
+ public bool RequiresWebAccess { get; } = true;
+
+ ///
+ public IReadOnlyList GetSettingsSchema()
+ {
+ return
+ [
+ new PluginSettingDescriptor(
+ Key: "preferredLanguage",
+ Label: "Preferred Language",
+ Type: PluginSettingType.Text,
+ DefaultValue: "en"
+ ),
+ new PluginSettingDescriptor(
+ Key: "selectionStrategy",
+ Label: "Selection Strategy",
+ Type: PluginSettingType.Select,
+ DefaultValue: "first",
+ AllowedValues: ["first", "best"]
+ )
+ ];
+ }
+
+ ///
+ public void RegisterServices(IServiceCollection services)
+ {
+ }
+
+ ///
+ public Task> GetSearchResultsAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ return Task.FromResult>(
+ [
+ CreateMetadata("The Fellowship of the Ring", "3")
+ ]
+ );
+ }
+
+ ///
+ public Task GetMetadataAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ if (lookup.Title is null)
+ return Task.FromResult(null);
+ return Task.FromResult(CreateMetadata(lookup.Title, "3"));
+ }
+
+ private static BookMetadataDto CreateMetadata(string title, string goodreadsId)
+ {
+ return new BookMetadataDto(
+ Title: title,
+ OriginalTitle: title,
+ Description: "A test description.",
+ ReleaseInfo: new ReleaseInfoDto(
+ OriginalReleaseDate: new DateOnly(1954, 7, 29),
+ OriginalReleaseYear: 1954,
+ ReReleaseDate: null,
+ ReReleaseYear: null,
+ ReleaseCountry: "uk",
+ ReleaseVersion: null
+ ),
+ Genres: [new GenreDto("fantasy")],
+ Tags: [new TagDto("epic fantasy")],
+ Language: new LanguageInfoDto("en", "English", "English"),
+ OriginalLanguage: null,
+ Publisher: "Houghton Mifflin",
+ PageCount: 398,
+ Format: BookFormat.Paperback,
+ Edition: null,
+ VolumeNumber: 1,
+ Series: null,
+ ASIN: null,
+ GoodreadsId: goodreadsId,
+ LCCN: null,
+ OCLCNumber: null,
+ OpenLibraryId: null,
+ LibraryThingId: null,
+ GoogleBooksId: null,
+ BarnesAndNobleId: null,
+ AppleBooksId: null,
+ Isbns: null,
+ Contributors: null,
+ Ratings: null,
+ CoverImageUrl: null
+ );
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj
new file mode 100644
index 00000000..711d201a
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj
@@ -0,0 +1,39 @@
+
+
+
+ net10.0
+ disable
+ enable
+
+ false
+ true
+
+
+
+
+ <_Parameter1>DisableTestParallelization = true
+ <_Parameter1_IsLiteral>true
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Metadata/RemoteMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Metadata/RemoteMetadataProviderTests.cs
new file mode 100644
index 00000000..2c94544a
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Metadata/RemoteMetadataProviderTests.cs
@@ -0,0 +1,72 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.Contracts.UnitTests.Fakes;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.Contracts.UnitTests.Metadata;
+
+///
+/// Contains unit tests for the contracts.
+///
+public class RemoteMetadataProviderTests
+{
+ private readonly IRemoteMetadataProvider _provider = new FakeBookMetadataProvider();
+
+ [Fact]
+ public async Task GetMetadataAsync_WhenCalledThroughNonGenericInterface_ShouldReturnTypedMetadata()
+ {
+ // Arrange
+ MetadataLookupDto lookup = new BookMetadataLookupDto(
+ LibraryId: Guid.NewGuid(),
+ Path: "/books/the-fellowship-of-the-ring.epub",
+ Title: "The Fellowship of the Ring");
+
+ // Act
+ MetadataDto? result = await _provider.GetMetadataAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.NotNull(result);
+ BookMetadataDto bookMetadata = Assert.IsType(result);
+ Assert.Equal("The Fellowship of the Ring", bookMetadata.Title);
+ Assert.Equal("3", bookMetadata.GoodreadsId);
+ }
+
+ [Fact]
+ public async Task GetMetadataAsync_WhenNoMetadataFound_ShouldReturnNull()
+ {
+ // Arrange
+ MetadataLookupDto lookup = new BookMetadataLookupDto(
+ LibraryId: Guid.NewGuid(),
+ Path: "/books/unknown.epub");
+
+ // Act
+ MetadataDto? result = await _provider.GetMetadataAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Null(result);
+ }
+
+ [Fact]
+ public async Task GetSearchResultsAsync_WhenCalledThroughNonGenericInterface_ShouldReturnTypedResults()
+ {
+ // Arrange
+ MetadataLookupDto lookup = new BookMetadataLookupDto(
+ LibraryId: Guid.NewGuid(),
+ Path: "/books/the-fellowship-of-the-ring.epub",
+ Title: "The Fellowship of the Ring");
+
+ // Act
+ IReadOnlyList result = await _provider.GetSearchResultsAsync(lookup, CancellationToken.None);
+
+ // Assert
+ Assert.Single(result);
+ BookMetadataDto bookMetadata = Assert.IsType(result[0]);
+ Assert.Equal("The Fellowship of the Ring", bookMetadata.Title);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Plugins/PluginTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Plugins/PluginTests.cs
new file mode 100644
index 00000000..ed6f0901
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Plugins/PluginTests.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.Contracts.Core.Plugins.Settings;
+using Lumina.Plugins.Contracts.UnitTests.Fakes;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Plugins.Contracts.UnitTests.Plugins;
+
+///
+/// Contains unit tests for the contract.
+///
+public class PluginTests
+{
+ private readonly IPlugin _plugin = new FakeBookMetadataProvider();
+
+ [Fact]
+ public void GetSettingsSchema_WhenCalled_ShouldReturnDeclaredSettings()
+ {
+ // Act
+ IReadOnlyList schema = _plugin.GetSettingsSchema();
+
+ // Assert
+ Assert.Equal(2, schema.Count);
+ Assert.Equal("preferredLanguage", schema[0].Key);
+ Assert.Equal(PluginSettingType.Text, schema[0].Type);
+ Assert.Equal("en", schema[0].DefaultValue);
+ Assert.Equal("selectionStrategy", schema[1].Key);
+ Assert.Equal(PluginSettingType.Select, schema[1].Type);
+ Assert.Contains("first", schema[1].AllowedValues!);
+ }
+}