Adds book reading support with EPUB and PDF reader plugins

This commit is contained in:
BinaryAlley committed 2026-09-02 04:45:11 -07:00
1 parent 275fd83ff2
commit f7ccdf3d1c
271 files changed
+11501 -361

No files matched your search

@@ -6,12 +6,14 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
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.Reading;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
@@ -29,7 +31,8 @@ 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.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Themes;
@@ -49,20 +52,20 @@ using System.Reflection;
namespace Lumina.Infrastructure.Common.DependencyInjection;
/// <summary>
/// Contains all services of the Infrastructure layer.
/// Utility class for registering the services of the Infrastructure layer into the Dependency Injection container.
/// </summary>
[ExcludeFromCodeCoverage]
public static class InfrastructureLayerServices
{
/// <summary>
/// Extension method for adding the Infrastructure layer services to the DI container.
/// Registers the services of the Infrastucture layer into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="configuration">The configuration manager used to read the application configuration.</param>
/// <param name="configuration">The configuration used to read the application configuration.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services, IConfiguration configuration)
{
// scan the current assembly for validators and add them to the DI container
// Scan the current assembly for validators and add them to the DI container.
IEnumerable<Type> concreteTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition);
@@ -84,13 +87,13 @@ public static class InfrastructureLayerServices
services.AddScoped<IDomainEventsQueue, DomainEventsQueue>();
services.AddScoped<IDomainEventPublisher, DomainEventPublisher>();
// authorization
// Authorization.
services.AddScoped<IOver18Policy, Over18Policy>();
services.AddScoped<ILibraryOwnershipPolicy, LibraryOwnershipPolicy>();
services.AddScoped<IAuthorizationPolicyFactory, AuthorizationPolicyFactory>();
services.AddScoped<IAuthorizationService, AuthorizationService>();
// media library scanning
// Media library scanning.
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
@@ -106,15 +109,21 @@ public static class InfrastructureLayerServices
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
// book artwork: stores the artwork of the books into the internal media directory
// Book artwork: stores the artwork of the books into the internal media directory.
services.AddHttpClient();
services.AddScoped<IBookArtworkService, BookArtworkService>();
// plugins: load the plugin assemblies from the plugins directory, register their services and provide the plugin manager
// Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents;
// the enablement cache lets the reading service skip the per-request database read of the reader configurations.
services.AddSingleton<IBookReaderEnablementCache, BookReaderEnablementCache>();
services.AddSingleton<IBookReaderRegistry, BookReaderRegistry>();
services.AddSingleton<IBookReadingService, BookReadingService>();
// 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);
PluginLoadResultDto pluginLoadResult = PluginLoader.LoadPlugins(pluginsDirectory, services);
services.AddSingleton<IPluginManager>(new PluginManager(pluginLoadResult.Plugins));
services.AddSingleton<IPluginManager>(new PluginManager(pluginLoadResult.Plugins, pluginLoadResult.LoadContexts));
services.AddScoped<IPluginSettingsStore, PluginSettingsStore>();
services.AddScoped<IPluginInstaller, PluginInstaller>();
services.AddScoped<IMediaLibraryProviderConfigurationStore, MediaLibraryProviderConfigurationStore>();
@@ -125,7 +134,7 @@ public static class InfrastructureLayerServices
serviceProvider.GetRequiredService<ILogger<PluginDetectionSyncJob>>()));
services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<PluginDetectionSyncJob>());
// themes: the theme service stores and serves theme packs, and the detection job seeds the bundled themes at startup
// Themes: the theme service stores and serves theme packs, and the detection job seeds the bundled themes at startup.
services.AddSingleton<IThemeService, ThemeService>();
services.AddHostedService<ThemeDetectionSyncJob>();
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using System.Collections.Generic;
#endregion
@@ -9,8 +10,14 @@ namespace Lumina.Infrastructure.Common.Models.DTO.Plugins;
/// Data transfer object for the result of loading the plugins from the plugins directory.
/// </summary>
/// <param name="Plugins">The plugins that were loaded successfully.</param>
/// <param name="LoadContexts">
/// The load contexts of the successfully loaded plugins. The contexts are kept referenced here for the lifetime of the host, because a collectible
/// load context is only kept alive by a direct reference to the context object itself, and the garbage collector would otherwise unload the plugin assemblies mid-request,
/// when a lazily resolved dependency is first used.
/// </param>
/// <param name="Errors">The errors that occurred while loading the plugins.</param>
internal sealed record PluginLoadResultDto(
IReadOnlyList<IPlugin> Plugins,
IReadOnlyList<IPlugin> Plugins,
IReadOnlyList<PluginLoadContext> LoadContexts,
IReadOnlyList<PluginLoadErrorDto> Errors
);
@@ -4,7 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Events;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -18,7 +18,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
/// <summary>
/// Stores the artwork of a book into the internal media directory, under a per-book directory, and returns its relative path.
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Reading;
using System;
using System.Collections.Concurrent;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// In-memory cache of whether the book reader of a plugin is enabled for a media library. The entries are invalidated when the
/// enablement is changed by the user, or when the configurations of a plugin or a library are removed.
/// </summary>
internal sealed class BookReaderEnablementCache : IBookReaderEnablementCache
{
private readonly ConcurrentDictionary<(Guid LibraryId, Guid PluginId), bool> _enablements = [];
/// <inheritdoc/>
public bool? Get(Guid libraryId, Guid pluginId)
{
return _enablements.TryGetValue((libraryId, pluginId), out bool isEnabled) ? isEnabled : null;
}
/// <inheritdoc/>
public void Set(Guid libraryId, Guid pluginId, bool isEnabled)
{
_enablements[(libraryId, pluginId)] = isEnabled;
}
/// <inheritdoc/>
public void Invalidate(Guid libraryId, Guid pluginId)
{
_enablements.TryRemove((libraryId, pluginId), out _);
}
/// <inheritdoc/>
public void InvalidateLibrary(Guid libraryId)
{
foreach ((Guid cachedLibraryId, Guid cachedPluginId) in _enablements.Keys)
if (cachedLibraryId == libraryId)
_enablements.TryRemove((cachedLibraryId, cachedPluginId), out _);
}
/// <inheritdoc/>
public void InvalidatePlugin(Guid pluginId)
{
foreach ((Guid cachedLibraryId, Guid cachedPluginId) in _enablements.Keys)
if (cachedPluginId == pluginId)
_enablements.TryRemove((cachedLibraryId, cachedPluginId), out _);
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Reading;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Registry of the book readers provided by the loaded plugins.
/// </summary>
internal sealed class BookReaderRegistry : IBookReaderRegistry
{
private readonly IPluginManager _pluginManager;
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="BookReaderRegistry"/> class.
/// </summary>
/// <param name="pluginManager">Injected manager of the plugins loaded by the host application.</param>
/// <param name="serviceProvider">Injected provider used to resolve the book readers registered by the plugins.</param>
public BookReaderRegistry(IPluginManager pluginManager, IServiceProvider serviceProvider)
{
_pluginManager = pluginManager;
_serviceProvider = serviceProvider;
}
/// <summary>
/// Gets the file extensions supported by the book readers of each loaded plugin, keyed by the Id of the plugin.
/// </summary>
/// <returns>The supported extensions of the book readers, keyed by the Id of the plugin providing them.</returns>
public IReadOnlyDictionary<Guid, IReadOnlyList<string>> GetSupportedExtensionsByPluginId()
{
Dictionary<Guid, IReadOnlyList<string>> extensionsByPluginId = [];
// The extensions are read live from the loaded book readers, rather than persisted, so that a plugin update that
// changes its supported formats is reflected immediately and the stored configurations never go stale.
foreach (IPlugin plugin in _pluginManager.GetPlugins())
{
List<string> extensions = [.. _serviceProvider.GetKeyedServices<IBookReader>(plugin.Id)
.SelectMany(reader => reader.SupportedExtensions)
.Where(extension => !string.IsNullOrWhiteSpace(extension))
.OrderBy(extension => extension, StringComparer.OrdinalIgnoreCase)
.Distinct(StringComparer.OrdinalIgnoreCase)];
if (extensions.Count > 0)
extensionsByPluginId[plugin.Id] = extensions;
}
return extensionsByPluginId;
}
}
@@ -0,0 +1,558 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Reading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Service for reading books using the book reader plugins configured for their media library. The contents of a book are
/// extracted into a temporary directory on first access and served from there, and the extraction is wiped at startup.
/// </summary>
/// <remarks>
/// The reading flow, for every request: resolve the reader plugin supporting the format of the book, check that the reader
/// is enabled for the book's library, reuse the already extracted book when its file has not changed on disk, and only then
/// serve the requested part (manifest, section, or resource). The section content is always sanitized by the host, and the
/// section and resource file paths coming from the plugins are contained-checked before they are read. The text and the image
/// extraction of the same book use separate working directories, and each extraction is serialized per rendering preference,
/// so that users reading the same book with different preferences never overwrite each other's extracted files.
/// </remarks>
internal sealed class BookReadingService : IBookReadingService
{
private readonly ConcurrentDictionary<ReadingCacheKey, BookExtractionEntry> _extractions = [];
private readonly ConcurrentDictionary<ReadingCacheKey, SemaphoreSlim> _bookExtractionLocks = [];
private readonly IServiceProvider _serviceProvider;
private readonly IPluginManager _pluginManager;
private readonly IBookReaderEnablementCache _enablementCache;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<BookReadingService> _logger;
// The plugin set is fixed for the lifetime of the host, so the mapping from a format to the plugin that reads it is built once on
// its first use, instead of being recomputed - and each plugin's keyed services resolved - on every section or resource request.
private IReadOnlyDictionary<ReaderKey, Guid>? _pluginIdsByReaderKey;
private readonly object _readerMapSync = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookReadingService"/> class.
/// </summary>
/// <param name="serviceProvider">Injected provider used to resolve the book readers registered by the plugins.</param>
/// <param name="pluginManager">Injected manager of the plugins loaded by the host application.</param>
/// <param name="enablementCache">Injected cache of whether the book reader of a plugin is enabled for a media library.</param>
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which the book reader configurations are requested.</param>
/// <param name="logger">Injected logger used to report the failures to open the books.</param>
public BookReadingService(IServiceProvider serviceProvider, IPluginManager pluginManager, IBookReaderEnablementCache enablementCache, IServiceScopeFactory serviceScopeFactory, ILogger<BookReadingService> logger)
{
_serviceProvider = serviceProvider;
_pluginManager = pluginManager;
_enablementCache = enablementCache;
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <summary>
/// Gets the reading manifest of the book stored at <paramref name="path"/>.
/// </summary>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="libraryType">The type of the media library the book belongs to.</param>
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the reading manifest of the book, or an error.</returns>
public async Task<Result<ReadingManifestResponse>> GetManifestAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, bool shouldRenderPdfAsImages, CancellationToken cancellationToken)
{
Result<BookExtractionEntry> extractionResult = await GetExtractionAsync(bookId, libraryId, path, libraryType, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
return extractionResult.IsSuccess ? extractionResult.Value.Document.ToResponse() : extractionResult.Errors;
}
/// <summary>
/// Gets the content of the reading section identified by <paramref name="locationRef"/> of the book stored at <paramref name="path"/>.
/// </summary>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="libraryType">The type of the media library the book belongs to.</param>
/// <param name="locationRef">The opaque location reference of the reading section.</param>
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
/// <param name="shouldPreserveStyles">Whether the styles of the section content are preserved when it is sanitized, or stripped.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the content of the reading section, or an error.</returns>
public async Task<Result<ReadingSectionDto>> GetSectionAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string locationRef, bool shouldRenderPdfAsImages, bool shouldPreserveStyles, CancellationToken cancellationToken)
{
Result<BookExtractionEntry> extractionResult = await GetExtractionAsync(bookId, libraryId, path, libraryType, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
if (extractionResult.IsFailure)
return extractionResult.Errors;
BookExtractionEntry extraction = extractionResult.Value;
if (!extraction.SectionsByLocationRef.TryGetValue(locationRef, out ReadingSpineItemDto? spineItem))
return Errors.Reading.SectionNotFound;
string workingDirectory = GetWorkingDirectory(bookId, shouldRenderPdfAsImages);
// The section file path comes from the reader plugin, so it is resolved against the working directory and the resolved path is verified to stay inside it,
// so that a malicious plugin cannot point the reader at arbitrary files.
Result<string> sectionFilePathResult = ResolveContainedPath(workingDirectory, spineItem.RelativeSectionFilePath);
if (sectionFilePathResult.IsFailure || !File.Exists(sectionFilePathResult.Value))
return Errors.Reading.SectionNotFound;
string content = await File.ReadAllTextAsync(sectionFilePathResult.Value, cancellationToken).ConfigureAwait(false);
// The section content is always sanitized by the host, regardless of what the reader plugin produced, so that no plugin can ever serve active content to the client;
// whether the inert style attributes survive is the per-user choice that decides if a book keeps its original look.
return new ReadingSectionDto(spineItem.LocationRef, spineItem.Title, ReadingContentSanitizer.Sanitize(content, shouldPreserveStyles));
}
/// <summary>
/// Gets the resource identified by <paramref name="resourceKey"/> of the book stored at <paramref name="path"/>.
/// </summary>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="libraryType">The type of the media library the book belongs to.</param>
/// <param name="resourceKey">The opaque resource key of the resource.</param>
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the resource, or an error.</returns>
public async Task<Result<ReadingResourceDataDto>> GetResourceAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string resourceKey, bool shouldRenderPdfAsImages, CancellationToken cancellationToken)
{
// The reader is resolved and its enablement verified before anything is served, so that disabling a reader immediately cuts access
// even to the resources that are already extracted and cached on disk, and to the pages a PDF rendered for an earlier request.
Result<BookExtractionEntry> extractionResult = await GetExtractionAsync(bookId, libraryId, path, libraryType, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
if (extractionResult.IsFailure)
return extractionResult.Errors;
BookExtractionEntry extraction = extractionResult.Value;
if (!extraction.Document.Resources.TryGetValue(resourceKey, out ReadingResourceInfoDto? resource))
return Errors.Reading.ResourceNotFound;
string workingDirectory = GetWorkingDirectory(bookId, shouldRenderPdfAsImages);
// The resource file path comes from the reader plugin, so it is contained-checked the same way the section files are.
Result<string> resourceFilePathResult = ResolveContainedPath(workingDirectory, resource.RelativeFilePath);
if (resourceFilePathResult.IsFailure)
return Errors.Reading.ResourceNotFound;
string resourceFilePath = resourceFilePathResult.Value;
// A resource that was already produced (for example an EPUB resource extracted when the book was opened, or a PDF page
// rendered by an earlier request) is served from disk; otherwise the reader produces it on demand, and the produced file is
// cached to disk, so that a resource is only ever produced once, and a large book is not rendered up front.
if (!File.Exists(resourceFilePath))
{
// A resource is produced by at most one request at a time: two requests that miss the same resource (for example two
// readers turning to the same not-yet-rendered page of a PDF) would otherwise both render it, and one of them could read
// the resource file while the other was still writing it.
SemaphoreSlim productionLock = extraction.ResourceProductionLocks.GetOrAdd(resourceFilePath, _ => new SemaphoreSlim(initialCount: 1, maxCount: 1));
await productionLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Another request may have produced the resource while this one was waiting for the lock.
if (File.Exists(resourceFilePath))
{
byte[] existingData = await File.ReadAllBytesAsync(resourceFilePath, cancellationToken).ConfigureAwait(false);
return new ReadingResourceDataDto(existingData, resource.MimeType);
}
Result<(Guid pluginId, IBookReader reader)> resolveResult = ResolveReader(path, libraryType);
if (resolveResult.IsFailure)
return resolveResult.Errors;
// A failing reader must not escape as an unhandled exception, so the production is wrapped the same way the extraction is;
// a corrupt book or renderer failure becomes a reading error the client can show, instead of a raw server error.
byte[] producedData;
try
{
producedData = await resolveResult.Value.reader.GetResourceAsync(path, workingDirectory, resourceKey, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception exception)
{
_logger.LogError(exception, "Failed to produce the resource '{ResourceKey}' of the book '{BookId}'.", resourceKey, bookId);
return Error.Failure(code: "Reading.ResourceProductionFailed", description: "The resource of the book could not be produced.");
}
// The produced bytes are written to a temporary file that is then moved over the resource file, so that a request that
// observes the resource file on disk only ever reads a fully written resource, never one that is still being written.
Directory.CreateDirectory(Path.GetDirectoryName(resourceFilePath)!);
string temporaryFilePath = $"{resourceFilePath}.{Guid.NewGuid():N}.tmp";
try
{
await File.WriteAllBytesAsync(temporaryFilePath, producedData, cancellationToken).ConfigureAwait(false);
File.Move(temporaryFilePath, resourceFilePath, overwrite: true);
}
catch
{
if (File.Exists(temporaryFilePath))
File.Delete(temporaryFilePath);
throw;
}
return new ReadingResourceDataDto(producedData, resource.MimeType);
}
finally
{
productionLock.Release();
}
}
byte[] data = await File.ReadAllBytesAsync(resourceFilePath, cancellationToken).ConfigureAwait(false);
return new ReadingResourceDataDto(data, resource.MimeType);
}
/// <summary>
/// Checks whether the book stored at <paramref name="path"/> can be opened for reading, resolving the book reader configured for
/// its media library and verifying that the reader is enabled, without extracting the book.
/// </summary>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="libraryType">The type of the media library the book belongs to.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the reading availability of the book, or an error.</returns>
public async Task<Result<ReadingAvailabilityResponse>> GetAvailabilityAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, CancellationToken cancellationToken)
{
// The same two checks that gate the actual reading are performed here, so that the availability the user is told about is
// exactly the availability the reader would experience, but the book is not extracted just to answer the question.
Result<(Guid pluginId, IBookReader reader)> resolveResult = ResolveReader(path, libraryType);
if (resolveResult.IsFailure)
return new ReadingAvailabilityResponse(bookId, libraryId, IsAvailable: false, ErrorCode: resolveResult.FirstError.Description);
Result<bool> isEnabledResult = await IsReaderEnabledAsync(libraryId, resolveResult.Value.pluginId, cancellationToken).ConfigureAwait(false);
if (isEnabledResult.IsFailure)
return new ReadingAvailabilityResponse(bookId, libraryId, IsAvailable: false, ErrorCode: isEnabledResult.FirstError.Description);
return new ReadingAvailabilityResponse(bookId, libraryId, IsAvailable: true, ErrorCode: null);
}
/// <summary>
/// Gets the extracted reading document of the book stored at <paramref name="path"/>, resolving the book reader configured
/// for its media library, extracting the book into the temporary directory when it is not already extracted, and enforcing
/// the enablement of the reader before anything is served.
/// </summary>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="libraryType">The type of the media library the book belongs to.</param>
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the extracted document of the book with its section lookup, or an error.</returns>
private async Task<Result<BookExtractionEntry>> GetExtractionAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, bool shouldRenderPdfAsImages, CancellationToken cancellationToken)
{
// The plugin supporting the book format is resolved first, so that a book whose format has no plugin at all gets a distinct error from a book whose plugin
// is simply disabled for the library.
Result<(Guid pluginId, IBookReader reader)> resolveResult = ResolveReader(path, libraryType);
if (resolveResult.IsFailure)
return resolveResult.Errors;
// The per-library enablement is enforced before anything is served, and never derived from the extraction cache, so disabling
// a reader immediately cuts access for that library, even to already extracted content; the check itself is cached, since it is
// read on every request and only changes through an explicit toggle.
Result<bool> isEnabledResult = await IsReaderEnabledAsync(libraryId, resolveResult.Value.pluginId, cancellationToken).ConfigureAwait(false);
if (isEnabledResult.IsFailure)
return isEnabledResult.Errors;
// The extraction is keyed by both the book and the rendering preference, so that the same book can be extracted both as
// text and as page images for different users without them evicting each other.
ReadingCacheKey cacheKey = new(bookId, shouldRenderPdfAsImages);
// Reuse the already extracted document while the book file on disk still matches the extraction, so that reading a book does not re-parse it on every section
// or resource request; a book modified in place is re-extracted.
if (_extractions.TryGetValue(cacheKey, out BookExtractionEntry? extraction) && !HasFileChanged(extraction, path))
return extraction;
// A book is extracted by at most one request at a time, and each rendering preference of a book has its own working directory, so
// concurrent extractions are serialized per book and rendering preference; a request that arrives while the book is being extracted
// for its preference waits for that extraction to finish and reuses its result, instead of starting a second extraction over the
// same directory. The extraction itself runs with a host lifetime token rather than the token of the first request, so that a single
// disconnected client cannot abort the extraction of a book that other users are waiting for.
SemaphoreSlim extractionLock = _bookExtractionLocks.GetOrAdd(cacheKey, _ => new SemaphoreSlim(initialCount: 1, maxCount: 1));
await extractionLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Another request may have extracted the book while this one was waiting for the lock.
if (_extractions.TryGetValue(cacheKey, out BookExtractionEntry? existingExtraction) && !HasFileChanged(existingExtraction, path))
return existingExtraction;
Result<ReadingDocumentDto> extractResult = await ExtractAsync(resolveResult.Value.reader, bookId, path, shouldRenderPdfAsImages, CancellationToken.None).ConfigureAwait(false);
if (extractResult.IsFailure)
return extractResult.Errors;
ReadingDocumentDto document = extractResult.Value;
BookExtractionEntry newExtraction = new(document, BuildSectionLookup(document), GetFileFingerprint(path));
_extractions[cacheKey] = newExtraction;
return newExtraction;
}
finally
{
extractionLock.Release();
}
}
/// <summary>
/// Extracts the book stored at <paramref name="path"/> into its temporary directory using the provided <paramref name="reader"/>.
/// </summary>
/// <param name="reader">The book reader used to extract the book.</param>
/// <param name="bookId">The Id of the book.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the reading document of the book, or an error.</returns>
private async Task<Result<ReadingDocumentDto>> ExtractAsync(IBookReader reader, Guid bookId, string path, bool shouldRenderPdfAsImages, CancellationToken cancellationToken)
{
string workingDirectory = GetWorkingDirectory(bookId, shouldRenderPdfAsImages);
try
{
// A re-extraction replaces the previous contents of the directory, so that a book modified in place is re-extracted from scratch.
if (Directory.Exists(workingDirectory))
Directory.Delete(workingDirectory, recursive: true);
Directory.CreateDirectory(workingDirectory);
return await reader.OpenAsync(path, workingDirectory, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (IOException exception) when (exception is FileNotFoundException or DirectoryNotFoundException)
{
return Errors.Reading.BookFileNotFound;
}
catch (Exception exception)
{
_logger.LogError(exception, "Failed to open the book '{BookId}' for reading.", bookId);
return Error.Failure(code: "Reading.ExtractionFailed", description: "The book could not be opened for reading.");
}
}
/// <summary>
/// Resolves the book reader supporting the extension and the library type of the book stored at <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path of the book.</param>
/// <param name="libraryType">The type of the media library the book belongs to.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the Id of the plugin and the resolved book reader, or an error.</returns>
private Result<(Guid pluginId, IBookReader reader)> ResolveReader(string path, LibraryType libraryType)
{
// The extension is matched case-insensitively against the extensions the readers declare, like the per-request scan it replaces.
string extension = Path.GetExtension(path).ToLowerInvariant();
ReaderKey readerKey = new(extension, libraryType);
IReadOnlyDictionary<ReaderKey, Guid> pluginIdsByReaderKey = GetPluginIdsByReaderKey();
if (!pluginIdsByReaderKey.TryGetValue(readerKey, out Guid pluginId))
return Errors.Reading.NoReaderAvailable;
IBookReader? reader = _serviceProvider.GetKeyedServices<IBookReader>(pluginId)
.FirstOrDefault(candidate => candidate.SupportedLibraryTypes.Contains(libraryType)
&& candidate.SupportedExtensions.Any(supportedExtension => string.Equals(supportedExtension, extension, StringComparison.OrdinalIgnoreCase)));
return reader is not null ? (pluginId, reader) : Errors.Reading.NoReaderAvailable;
}
/// <summary>
/// Gets the mapping from a format to the Id of the plugin that reads it, built once from the plugins loaded by the host.
/// </summary>
/// <returns>The Id of the plugin reading each format, keyed by the format.</returns>
private IReadOnlyDictionary<ReaderKey, Guid> GetPluginIdsByReaderKey()
{
IReadOnlyDictionary<ReaderKey, Guid>? pluginIdsByReaderKey = _pluginIdsByReaderKey;
if (pluginIdsByReaderKey is not null)
return pluginIdsByReaderKey;
lock (_readerMapSync)
{
pluginIdsByReaderKey = _pluginIdsByReaderKey;
if (pluginIdsByReaderKey is not null)
return pluginIdsByReaderKey;
// The readers are iterated in the same stable order the per-request scan used - plugins alphabetically by name, then their
// readers - and the first reader that declares a format is the one that reads it, so a format is handled by exactly one reader.
Dictionary<ReaderKey, Guid> discoveredPluginIdsByReaderKey = [];
foreach (IPlugin plugin in _pluginManager.GetPlugins().OrderBy(plugin => plugin.Name, StringComparer.OrdinalIgnoreCase))
{
foreach (IBookReader candidateReader in _serviceProvider.GetKeyedServices<IBookReader>(plugin.Id))
{
foreach (LibraryType supportedLibraryType in candidateReader.SupportedLibraryTypes)
{
foreach (string supportedExtension in candidateReader.SupportedExtensions)
{
string normalizedExtension = supportedExtension.Trim().ToLowerInvariant();
if (normalizedExtension.Length == 0)
continue;
discoveredPluginIdsByReaderKey.TryAdd(new ReaderKey(normalizedExtension, supportedLibraryType), plugin.Id);
}
}
}
}
_pluginIdsByReaderKey = discoveredPluginIdsByReaderKey;
return discoveredPluginIdsByReaderKey;
}
}
/// <summary>
/// Determines whether the book reader of the plugin identified by <paramref name="pluginId"/> is enabled for the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book reader configuration is read.</param>
/// <param name="pluginId">The Id of the plugin providing the book reader.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either whether the book reader is enabled, or an error.</returns>
private async Task<Result<bool>> IsReaderEnabledAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken)
{
// The enablement is cached, because it is consulted on every request and only changes when the user toggles a reader; the toggle
// invalidates the cache, so a disabled reader is never served content for longer than the toggle operation takes.
bool? cachedIsEnabled = _enablementCache.Get(libraryId, pluginId);
if (cachedIsEnabled is not null)
return cachedIsEnabled.Value ? true : Errors.Reading.ReaderDisabled;
// The service is a singleton so that the extraction cache is shared across requests, and the unit of work is scoped, so a fresh scope is created for this single
// configuration read instead of capturing a scoped dependency into a singleton.
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<LibraryBookReaderConfigurationEntity?> getConfigurationResult = await unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, cancellationToken).ConfigureAwait(false);
if (getConfigurationResult.IsFailure)
return getConfigurationResult.Errors;
// A missing configuration row (for example when the library was created before the reader was installed) is treated as disabled, so that no reader is ever used without an explicit enablement.
bool isEnabled = getConfigurationResult.Value is not null && getConfigurationResult.Value.IsEnabled;
_enablementCache.Set(libraryId, pluginId, isEnabled);
return isEnabled ? true : Errors.Reading.ReaderDisabled;
}
/// <summary>
/// Determines whether the file stored at <paramref name="path"/> changed since it was extracted.
/// </summary>
/// <param name="extraction">The stored extraction of the book.</param>
/// <param name="path">The file system path of the book.</param>
/// <returns><see langword="true"/> when the file changed since it was extracted, <see langword="false"/> otherwise.</returns>
private static bool HasFileChanged(BookExtractionEntry extraction, string path)
{
// Comparing the size and the last write time against the values captured at extraction time is a cheap staleness check that does not re-read the book file,
// so that an in-place modification of the book is detected without the cost of hashing the whole file on every request.
BookFileFingerprint currentFingerprint = GetFileFingerprint(path);
return currentFingerprint.FileSize != extraction.Fingerprint.FileSize || currentFingerprint.LastWriteTimeUtc != extraction.Fingerprint.LastWriteTimeUtc;
}
/// <summary>
/// Gets the size and the last write time of the file stored at <paramref name="path"/>, in a single file system probe.
/// </summary>
/// <param name="path">The file system path of the file.</param>
/// <returns>The fingerprint of the file, or the fingerprint of a missing file when it cannot be probed.</returns>
private static BookFileFingerprint GetFileFingerprint(string path)
{
try
{
// A missing file is reported with a size of -1 and a minimum last write time, which never match a stored extraction
// fingerprint, so that a deleted book is re-extracted (and fails) instead of being served from the cache.
FileInfo fileInfo = new(path);
return fileInfo.Exists ? new BookFileFingerprint(fileInfo.Length, fileInfo.LastWriteTimeUtc) : BookFileFingerprint.Missing;
}
catch (IOException)
{
return BookFileFingerprint.Missing;
}
catch (UnauthorizedAccessException)
{
return BookFileFingerprint.Missing;
}
}
/// <summary>
/// Builds the lookup of the reading sections of a book, keyed by their location reference, so that a section is found without
/// scanning the whole spine on every request.
/// </summary>
/// <param name="document">The reading document of the book.</param>
/// <returns>The reading sections of the book, keyed by their location reference.</returns>
private static IReadOnlyDictionary<string, ReadingSpineItemDto> BuildSectionLookup(ReadingDocumentDto document)
{
Dictionary<string, ReadingSpineItemDto> sectionsByLocationRef = [];
foreach (ReadingSpineItemDto spineItem in document.Spine)
sectionsByLocationRef.TryAdd(spineItem.LocationRef, spineItem);
return sectionsByLocationRef;
}
/// <summary>
/// Gets the temporary directory into which the book identified by <paramref name="bookId"/> is extracted for the rendering
/// preference identified by <paramref name="shouldRenderPdfAsImages"/>.
/// </summary>
/// <param name="bookId">The Id of the book.</param>
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
/// <returns>The absolute path of the temporary directory of the book for the rendering preference.</returns>
private static string GetWorkingDirectory(Guid bookId, bool shouldRenderPdfAsImages)
{
// The directory of a book combines its Id with the rendering preference used to extract it, so that the text and the image
// extraction of the same book live in separate directories and a re-extraction of one preference never deletes the files of
// the other; the whole cache is wiped at startup, so no further bookkeeping is needed to keep it from growing across restarts.
return Path.Combine(ReadingCachePaths.GetRootDirectory(), bookId.ToString("N"), shouldRenderPdfAsImages ? "images" : "text");
}
/// <summary>
/// Resolves a package-relative path against a package root, rejecting paths that escape the root.
/// </summary>
/// <param name="root">The absolute path of the package root.</param>
/// <param name="relativePath">The package-relative path to resolve.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the absolute path, or an error.</returns>
private static Result<string> ResolveContainedPath(string root, string relativePath)
{
string rootPath = Path.GetFullPath(root);
string candidate = Path.GetFullPath(Path.Combine(rootPath, relativePath));
string rootWithSeparator = rootPath.EndsWith(Path.DirectorySeparatorChar) ? rootPath : rootPath + Path.DirectorySeparatorChar;
StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
// A relative path that walks up past the root (for example with "..") is rejected, so that the reader can never serve a file outside the temporary extraction directory of the book.
if (!candidate.StartsWith(rootWithSeparator, comparison))
return Errors.Reading.ResourceNotFound;
return candidate;
}
/// <summary>
/// The extracted document of a book, along with the lookup of its sections and the file fingerprint captured at extraction time.
/// </summary>
/// <param name="Document">The reading document of the book.</param>
/// <param name="SectionsByLocationRef">The reading sections of the book, keyed by their location reference.</param>
/// <param name="Fingerprint">The size and last write time of the book file at extraction time.</param>
private sealed record BookExtractionEntry(ReadingDocumentDto Document, IReadOnlyDictionary<string, ReadingSpineItemDto> SectionsByLocationRef, BookFileFingerprint Fingerprint)
{
/// <summary>
/// The on-demand productions of the resources of the book, serialized per resource file, so that two requests that miss the
/// same resource (for example two readers turning to the same not-yet-rendered page of a PDF) do not both produce it, and a
/// request never reads a resource while another request is writing it.
/// </summary>
public ConcurrentDictionary<string, SemaphoreSlim> ResourceProductionLocks { get; } = [];
}
/// <summary>
/// The fingerprint of a book file, used to detect whether the file changed since it was extracted.
/// </summary>
/// <param name="FileSize">The size of the file, or -1 when the file does not exist.</param>
/// <param name="LastWriteTimeUtc">The last write time of the file, or <see cref="DateTime.MinValue"/> when the file does not exist.</param>
private readonly record struct BookFileFingerprint(long FileSize, DateTime LastWriteTimeUtc)
{
/// <summary>
/// The fingerprint of a file that does not exist or cannot be probed.
/// </summary>
public static BookFileFingerprint Missing { get; } = new(-1, DateTime.MinValue);
}
/// <summary>
/// The key of the extraction cache of a book, combining the Id of the book with the rendering preference used to extract it,
/// so that the same book can be extracted both as text and as page images for different users without them evicting each other.
/// </summary>
/// <param name="BookId">The Id of the book.</param>
/// <param name="ShouldRenderPdfAsImages">Whether the book, when it is a PDF, was rendered as page images instead of extracting its text layer.</param>
private sealed record ReadingCacheKey(Guid BookId, bool ShouldRenderPdfAsImages);
/// <summary>
/// The format of a book, combining its file extension with the type of its media library.
/// </summary>
/// <param name="Extension">The lower-case file extension of the format, with its leading dot.</param>
/// <param name="LibraryType">The type of the media library the format is read for.</param>
private sealed record ReaderKey(string Extension, LibraryType LibraryType);
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.IO;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Provides the location of the temporary directory into which the reading plugins extract the contents of the books.
/// </summary>
public static class ReadingCachePaths
{
/// <summary>
/// The name of the temporary directory into which the reading plugins extract the contents of the books.
/// </summary>
public const string DIRECTORY_NAME = "reading-cache";
/// <summary>
/// Gets the absolute path of the temporary directory into which the reading plugins extract the contents of the books.
/// </summary>
/// <returns>The absolute path of the reading cache directory.</returns>
public static string GetRootDirectory()
{
return Path.Combine(AppContext.BaseDirectory, DIRECTORY_NAME);
}
}
@@ -0,0 +1,77 @@
#region ========================================================================= USING =====================================================================================
using Ganss.Xss;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Sanitizes the HTML content of the reading sections extracted from the books, stripping every active content and keeping only the inert markup a reader can render.
/// The sanitization is generic and is always applied by the host, regardless of what the reader plugin produced.
/// </summary>
public static class ReadingContentSanitizer
{
public const string RESOURCE_ATTRIBUTE = "data-lumina-resource";
// The sanitizer that preserves the style attribute, used for the users who want the books to keep their original look, and the
// sanitizer that strips it, used for the users who prefer a book to never be able to load resources through its styles.
// The two are configured once at startup, because the allowlist of a sanitizer must not be mutated while it is shared between requests.
private static readonly HtmlSanitizer s_sanitizerWithStyles = CreateSanitizer(shouldPreserveStyles: true);
private static readonly HtmlSanitizer s_sanitizerWithoutStyles = CreateSanitizer(shouldPreserveStyles: false);
/// <summary>
/// Sanitizes the provided <paramref name="html"/>, returning the safe HTML content ready to be rendered by the client.
/// </summary>
/// <param name="html">The HTML content to sanitize.</param>
/// <param name="shouldPreserveStyles">Whether the style attributes of the content are preserved, or stripped.</param>
/// <returns>The sanitized HTML content.</returns>
public static string Sanitize(string html, bool shouldPreserveStyles)
{
if (string.IsNullOrWhiteSpace(html))
return string.Empty;
HtmlSanitizer sanitizer = shouldPreserveStyles ? s_sanitizerWithStyles : s_sanitizerWithoutStyles;
return sanitizer.Sanitize(html);
}
/// <summary>
/// Creates the sanitizer configured with the tags, attributes, and schemes a reading section may use.
/// </summary>
/// <param name="shouldPreserveStyles">Whether the style attribute is included in the allowlist of the sanitizer, or not.</param>
/// <returns>The configured sanitizer.</returns>
private static HtmlSanitizer CreateSanitizer(bool shouldPreserveStyles)
{
// The sanitizer uses an explicit allowlist of the inert markup a book may use, so that anything else - scripts, iframes, objects, forms, SVG, event handlers, and external references
// is stripped by default, instead of having to enumerate every active construct to remove.
HtmlSanitizer sanitizer = new();
sanitizer.AllowedTags.Clear();
sanitizer.AllowedTags.UnionWith(
[
"p", "div", "span", "section", "article", "header", "footer", "aside", "nav", "main",
"h1", "h2", "h3", "h4", "h5", "h6",
"a", "img", "picture", "source",
"ul", "ol", "li", "dl", "dt", "dd",
"table", "thead", "tbody", "tfoot", "tr", "td", "th", "caption", "colgroup", "col",
"blockquote", "pre", "code", "br", "hr",
"strong", "em", "b", "i", "u", "s", "sub", "sup", "small", "mark", "ins", "del",
"figure", "figcaption", "q", "cite", "abbr", "ruby", "rt", "rp", "bdi", "bdo", "wbr",
"kbd", "samp", "var", "time", "summary", "details"
]);
sanitizer.AllowedAttributes.Clear();
sanitizer.AllowedAttributes.UnionWith(
[
"class", "id", "title", "lang", "dir", "align", "valign", "width", "height",
"colspan", "rowspan", "scope", "href", "src", "alt", "data-lumina-resource"
]);
// The style attribute is what keeps the original look of a book (fonts, colors, alignment), but its CSS can also reference
// resources from external servers, which those servers could observe; whether it survives sanitization is a per-user choice.
if (shouldPreserveStyles)
sanitizer.AllowedAttributes.Add("style");
// Only the safe web schemes are allowed, so that a reference to javascript or a custom scheme is stripped; the data-lumina-resource attribute carries an opaque key instead of a URL, so it needs no scheme.
sanitizer.AllowedSchemes.Clear();
sanitizer.AllowedSchemes.UnionWith(["http", "https", "mailto", "tel"]);
sanitizer.UriAttributes.Clear();
sanitizer.UriAttributes.UnionWith(["href", "src"]);
return sanitizer;
}
}
@@ -2,10 +2,12 @@
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Reading;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
@@ -17,13 +19,22 @@ using System.Threading.Tasks;
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Store of the metadata and artwork provider configurations of the media libraries.
/// Store of the metadata, artwork and book reader configurations of the media libraries.
/// </summary>
/// <remarks>
/// The configurations decide, per media library, which loaded plugins may serve metadata or artwork, which book reader opens the
/// books of the library, and whether each of them is currently enabled. They are persisted as rows instead of being derived from
/// the loaded plugins on the fly, because the user can enable or disable a provider per library, and because the set of loaded
/// plugins can change between restarts. This class is the single place that maintains them, and the only one that knows the
/// difference between "ensure" (only add what is missing) and "reconcile" (make the persisted configurations match the loaded
/// plugins exactly).
/// </remarks>
internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProviderConfigurationStore
{
private readonly IUnitOfWork _unitOfWork;
private readonly IPluginManager _pluginManager;
private readonly IServiceProvider _serviceProvider;
private readonly IBookReaderEnablementCache _enablementCache;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryProviderConfigurationStore"/> class.
@@ -31,69 +42,161 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="pluginManager">Injected manager of the plugins loaded by the host application.</param>
/// <param name="serviceProvider">Injected provider used to resolve the providers registered by the plugins.</param>
public MediaLibraryProviderConfigurationStore(IUnitOfWork unitOfWork, IPluginManager pluginManager, IServiceProvider serviceProvider)
/// <param name="enablementCache">Injected cache of whether the book reader of a plugin is enabled for a media library.</param>
public MediaLibraryProviderConfigurationStore(IUnitOfWork unitOfWork, IPluginManager pluginManager, IServiceProvider serviceProvider, IBookReaderEnablementCache enablementCache)
{
_unitOfWork = unitOfWork;
_pluginManager = pluginManager;
_serviceProvider = serviceProvider;
_enablementCache = enablementCache;
}
/// <inheritdoc/>
/// <summary>
/// Gets the metadata provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the configurations, or an error.</returns>
public async Task<Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>> GetConfigurationsAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
/// <summary>
/// Adds a disabled provider configuration for every loaded plugin that supports the provided library type and has no configuration yet for the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose provider configurations are ensured.</param>
/// <param name="libraryType">The type of the media library, used to determine the plugins whose providers apply.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> EnsureProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken)
{
// "Ensure" is idempotent: it adds a configuration for every plugin that supports the library type and has none yet, but never removes any.
// It is called when a library is created or when plugins are (re)loaded, so every applicable provider is present and can be enabled from the UI.
(IReadOnlyList<Guid> metadataProviderPluginIds, IReadOnlyList<Guid> artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType);
Result<Success> ensureMetadataResult = await EnsureMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false);
if (ensureMetadataResult.IsFailure)
return ensureMetadataResult;
return await EnsureArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false);
Result<Success> ensureArtworkResult = await EnsureArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false);
if (ensureArtworkResult.IsFailure)
return ensureArtworkResult;
return await EnsureBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
/// <summary>
/// Replaces the provider configurations of the media library identified by <paramref name="libraryId"/> so that they match the plugins supporting the provided library type.
/// </summary>
/// <param name="libraryId">The Id of the media library whose provider configurations are reconciled.</param>
/// <param name="libraryType">The type of the media library, used to determine the plugins whose providers apply.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken)
{
// "Reconcile" makes the persisted configurations match the loaded plugins exactly: configurations of plugins that no longer support
// the library type are removed, configurations for newly supported plugins are added, and the rest are kept. It is called when a
// plugin is uninstalled or when the type of a library changes.
(IReadOnlyList<Guid> metadataProviderPluginIds, IReadOnlyList<Guid> artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType);
Result<Success> reconcileMetadataResult = await ReconcileMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false);
if (reconcileMetadataResult.IsFailure)
return reconcileMetadataResult;
return await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<Result<Deleted>> RemoveProviderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
{
Result<Deleted> removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (removeMetadataResult.IsFailure)
return removeMetadataResult;
return await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task<Result<Deleted>> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken)
{
Result<Deleted> removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
if (removeMetadataResult.IsFailure)
return removeMetadataResult;
return await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
Result<Success> reconcileArtworkResult = await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false);
if (reconcileArtworkResult.IsFailure)
return reconcileArtworkResult;
return await ReconcileBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the Ids of the loaded plugins that provide metadata or artwork for the provided library type,
/// ordered alphabetically by plugin name so that the assigned ranks are stable.
/// Deletes all the provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> RemoveProviderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
{
// The configurations would otherwise keep referencing a library that no longer exists, so they are all deleted with it.
Result<Deleted> removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (removeMetadataResult.IsFailure)
return removeMetadataResult;
Result<Deleted> removeArtworkResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (removeArtworkResult.IsFailure)
return removeArtworkResult;
Result<Deleted> removeBookReadersResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (removeBookReadersResult.IsFailure)
return removeBookReadersResult;
// The reader enablements of the deleted library are no longer valid, so the reading service must not serve its books from the cache.
_enablementCache.InvalidateLibrary(libraryId);
return removeBookReadersResult;
}
/// <summary>
/// Deletes all the provider configurations referencing the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose provider configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken)
{
// An uninstalled plugin can no longer serve any provider, so the configurations referencing it are deleted.
Result<Deleted> removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
if (removeMetadataResult.IsFailure)
return removeMetadataResult;
Result<Deleted> removeArtworkResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
if (removeArtworkResult.IsFailure)
return removeArtworkResult;
Result<Deleted> removeBookReadersResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
if (removeBookReadersResult.IsFailure)
return removeBookReadersResult;
// The reader enablements of the removed plugin are no longer valid, so the reading service must not serve its books from the cache.
_enablementCache.InvalidatePlugin(pluginId);
return removeBookReadersResult;
}
/// <summary>
/// Deletes all the book reader configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book reader configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
{
Result<Deleted> removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (removeResult.IsFailure)
return removeResult;
// The reader enablements of the deleted library are no longer valid, so the reading service must not serve its books from the cache.
_enablementCache.InvalidateLibrary(libraryId);
return removeResult;
}
/// <summary>
/// Deletes all the book reader configurations referencing the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose book reader configurations are deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken)
{
Result<Deleted> removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
if (removeResult.IsFailure)
return removeResult;
// The reader enablements of the removed plugin are no longer valid, so the reading service must not serve its books from the cache.
_enablementCache.InvalidatePlugin(pluginId);
return removeResult;
}
/// <summary>
/// Gets the Ids of the loaded plugins that provide metadata or artwork for the provided library type, ordered alphabetically by plugin name so that the assigned ranks are stable.
/// </summary>
/// <param name="libraryType">The type of the media library the providers must support.</param>
/// <returns>The Ids of the plugins providing metadata, and the Ids of the plugins providing artwork.</returns>
private (IReadOnlyList<Guid> metadataProviderPluginIds, IReadOnlyList<Guid> artworkProviderPluginIds) GetSupportedProviderPluginIds(LibraryType libraryType)
{
// The plugins are ordered alphabetically by name so the resulting ranks are stable across restarts, and each plugin is tracked in
// the metadata or artwork list independently, since it can support either, both, or neither.
List<Guid> metadataProviderPluginIds = [];
List<Guid> artworkProviderPluginIds = [];
foreach (IPlugin plugin in _pluginManager.GetPlugins().OrderBy(plugin => plugin.Name))
{
// The providers are resolved as keyed services under the Id of their plugin, and the plugin supports the library type when at least one of its providers declares that type.
if (_serviceProvider.GetKeyedServices<IMetadataProvider>(plugin.Id).Any(provider => provider.SupportedLibraryTypes.Contains(libraryType)))
metadataProviderPluginIds.Add(plugin.Id);
if (_serviceProvider.GetKeyedServices<IArtworkProvider>(plugin.Id).Any(provider => provider.SupportedLibraryTypes.Contains(libraryType)))
@@ -102,6 +205,111 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
return (metadataProviderPluginIds, artworkProviderPluginIds);
}
/// <summary>
/// Gets the Ids of the loaded plugins that provide a book reader for the provided library type, ordered alphabetically by plugin name so that the assigned order is stable.
/// </summary>
/// <param name="libraryType">The type of the media library the book readers must support.</param>
/// <returns>The Ids of the plugins providing a book reader for the library type.</returns>
private IReadOnlyList<Guid> GetSupportedBookReaderPluginIds(LibraryType libraryType)
{
// Book readers have no rank: a book is opened by exactly one reader matched by its file extension, not by priority, so the alphabetical order is only used to keep the display order stable.
List<Guid> bookReaderPluginIds = [];
foreach (IPlugin plugin in _pluginManager.GetPlugins().OrderBy(plugin => plugin.Name))
// A reader that declares no file extension can never be asked to open a file, so it is not worth configuring.
if (_serviceProvider.GetKeyedServices<IBookReader>(plugin.Id).Any(reader => reader.SupportedLibraryTypes.Contains(libraryType) && reader.SupportedExtensions.Count > 0))
bookReaderPluginIds.Add(plugin.Id);
return bookReaderPluginIds;
}
/// <summary>
/// Replaces the book reader configurations of the media library identified by <paramref name="libraryId"/> so that they match the plugins supporting the provided library type.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book reader configurations are reconciled.</param>
/// <param name="libraryType">The type of the media library, used to determine the plugins whose book readers apply.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken)
{
// First, the configurations of readers that no longer apply are deleted, then a disabled configuration is added for every reader
// that applies, but is not configured yet; the configurations of readers that still apply are kept untouched.
IReadOnlyList<Guid> bookReaderPluginIds = GetSupportedBookReaderPluginIds(libraryType);
Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> supportedPluginIds = [.. bookReaderPluginIds];
List<Guid> stalePluginIds = [.. getConfigurationsResult.Value
.Select(configuration => configuration.PluginId)
.Where(pluginId => !supportedPluginIds.Contains(pluginId))];
if (stalePluginIds.Count > 0)
{
Result<Deleted> removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false);
if (removeResult.IsFailure)
return Result<Success>.Failure(removeResult.Errors);
}
HashSet<Guid> configuredPluginIds = [.. getConfigurationsResult.Value.Select(configuration => configuration.PluginId)];
foreach (Guid pluginId in bookReaderPluginIds)
{
if (configuredPluginIds.Contains(pluginId))
continue;
// A newly discovered reader starts disabled so it never silently takes over reading the books of the library, and the audit
// columns are left at their defaults because the persistence layer stamps them when the row is saved.
LibraryBookReaderConfigurationEntity configuration = new()
{
Id = Guid.NewGuid(),
LibraryId = libraryId,
PluginId = pluginId,
IsEnabled = false,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
};
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return Result<Success>.Failure(upsertResult.Errors);
}
return Result.Success;
}
/// <summary>
/// Adds a disabled book reader configuration for every loaded plugin that supports the provided library type and has no configuration yet, for the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book reader configurations are ensured.</param>
/// <param name="libraryType">The type of the media library, used to determine the plugins whose book readers apply.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken)
{
// Unlike reconcile, ensure never deletes: it only adds a disabled configuration for the readers that are not configured yet.
IReadOnlyList<Guid> bookReaderPluginIds = GetSupportedBookReaderPluginIds(libraryType);
if (bookReaderPluginIds.Count == 0)
return Result.Success;
Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> configuredPluginIds = [.. getConfigurationsResult.Value.Select(configuration => configuration.PluginId)];
foreach (Guid pluginId in bookReaderPluginIds)
{
if (configuredPluginIds.Contains(pluginId))
continue;
// A newly discovered reader starts disabled so it never silently takes over reading the books of the library, and the audit
// columns are left at their defaults because the persistence layer stamps them when the row is saved.
LibraryBookReaderConfigurationEntity configuration = new()
{
Id = Guid.NewGuid(),
LibraryId = libraryId,
PluginId = pluginId,
IsEnabled = false,
CreatedOnUtc = default,
CreatedBy = default,
UpdatedBy = default
};
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
return Result<Success>.Failure(upsertResult.Errors);
}
return Result.Success;
}
/// <summary>
/// Removes the metadata provider configurations of the plugins that no longer support the library type, and adds a disabled
/// configuration for every plugin that supports it and has none yet, keeping the configurations of the plugins that still apply.
@@ -115,23 +323,27 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> supportedPluginIds = metadataProviderPluginIds.ToHashSet();
List<Guid> stalePluginIds = getConfigurationsResult.Value
HashSet<Guid> supportedPluginIds = [.. metadataProviderPluginIds];
List<Guid> stalePluginIds = [.. getConfigurationsResult.Value
.Select(configuration => configuration.PluginId)
.Where(pluginId => !supportedPluginIds.Contains(pluginId))
.ToList();
.Where(pluginId => !supportedPluginIds.Contains(pluginId))];
if (stalePluginIds.Count > 0)
{
// The stale configurations are deleted first, so the next free rank is computed on the configurations that remain.
Result<Deleted> removeResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false);
if (removeResult.IsFailure)
return Result<Success>.Failure(removeResult.Errors);
}
HashSet<Guid> configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet();
HashSet<Guid> configuredPluginIds = [.. getConfigurationsResult.Value.Select(configuration => configuration.PluginId)];
// The metadata providers of a library are ordered by an explicit 1-based rank that decides which provider is consulted first when
// enriching a book; new providers are appended after the current highest rank so the priority of the existing ones is preserved.
int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1;
foreach (Guid pluginId in metadataProviderPluginIds)
{
if (configuredPluginIds.Contains(pluginId))
continue;
// A newly discovered provider starts disabled, so it never silently starts enriching the library until the user enables it, and
// the audit columns are left at their defaults because the persistence layer stamps them when the row is saved.
LibraryMetadataProviderConfigurationEntity configuration = new()
{
Id = Guid.NewGuid(),
@@ -164,23 +376,27 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> supportedPluginIds = artworkProviderPluginIds.ToHashSet();
List<Guid> stalePluginIds = getConfigurationsResult.Value
HashSet<Guid> supportedPluginIds = [.. artworkProviderPluginIds];
List<Guid> stalePluginIds = [.. getConfigurationsResult.Value
.Select(configuration => configuration.PluginId)
.Where(pluginId => !supportedPluginIds.Contains(pluginId))
.ToList();
.Where(pluginId => !supportedPluginIds.Contains(pluginId))];
if (stalePluginIds.Count > 0)
{
// The stale configurations are deleted first, so the next free rank is computed on the configurations that remain.
Result<Deleted> removeResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false);
if (removeResult.IsFailure)
return Result<Success>.Failure(removeResult.Errors);
}
HashSet<Guid> configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet();
HashSet<Guid> configuredPluginIds = [.. getConfigurationsResult.Value.Select(configuration => configuration.PluginId)];
// Same rank logic as the metadata providers: artwork providers are ordered by an explicit 1-based rank that decides which
// provider is consulted first, and new providers are appended after the current highest rank.
int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1;
foreach (Guid pluginId in artworkProviderPluginIds)
{
if (configuredPluginIds.Contains(pluginId))
continue;
// A newly discovered provider starts disabled, so it never silently starts fetching artwork until the user enables it, and the
// audit columns are left at their defaults because the persistence layer stamps them when the row is saved.
LibraryArtworkProviderConfigurationEntity configuration = new()
{
Id = Guid.NewGuid(),
@@ -214,12 +430,15 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet();
HashSet<Guid> configuredPluginIds = [.. getConfigurationsResult.Value.Select(configuration => configuration.PluginId)];
// New providers are appended after the current highest rank, and only added when missing: unlike reconcile, ensure never deletes.
int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1;
foreach (Guid pluginId in metadataProviderPluginIds)
{
if (configuredPluginIds.Contains(pluginId))
continue;
// A newly discovered provider starts disabled, so it never silently starts enriching the library until the user enables it, and
// the audit columns are left at their defaults because the persistence layer stamps them when the row is saved.
LibraryMetadataProviderConfigurationEntity configuration = new()
{
Id = Guid.NewGuid(),
@@ -253,12 +472,15 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
return Result<Success>.Failure(getConfigurationsResult.Errors);
HashSet<Guid> configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet();
HashSet<Guid> configuredPluginIds = [.. getConfigurationsResult.Value.Select(configuration => configuration.PluginId)];
// New providers are appended after the current highest rank, and only added when missing: unlike reconcile, ensure never deletes.
int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1;
foreach (Guid pluginId in artworkProviderPluginIds)
{
if (configuredPluginIds.Contains(pluginId))
continue;
// A newly discovered provider starts disabled, so it never silently starts fetching artwork until the user enables it, and the
// audit columns are left at their defaults because the persistence layer stamps them when the row is saved.
LibraryArtworkProviderConfigurationEntity configuration = new()
{
Id = Guid.NewGuid(),
@@ -1,10 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
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.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Infrastructure.Common.Models.DTO.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
@@ -60,7 +59,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
// the Ids of the plugin rows that are currently detected, either loaded successfully or failed to load
// The Ids of the plugin rows that are currently detected, either loaded successfully or failed to load.
HashSet<Guid> detectedPluginIds = [];
foreach (IPlugin plugin in _pluginManager.GetPlugins())
@@ -85,8 +84,8 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
foreach (PluginLoadErrorDto loadError in _loadErrors)
{
// a failing plugin cannot report its own Id, so it is identified by a stable Id derived from its assembly file name,
// which keeps the same row across restarts and avoids creating a new row every time the application starts
// A failing plugin cannot report its own Id, so it is identified by a stable Id derived from its assembly file name,
// which keeps the same row across restarts and avoids creating a new row every time the application starts.
Guid failedPluginId = DerivePluginId(loadError.AssemblyName);
detectedPluginIds.Add(failedPluginId);
PluginEntity pluginEntity = new()
@@ -107,8 +106,8 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", loadError.AssemblyName, upsertResult.FirstError.Description);
}
// remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status,
// and delete the provider configurations of the removed plugins, since their configuration only makes sense while the plugin is installed
// Remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status,
// and delete the provider configurations of the removed plugins, since their configuration only makes sense while the plugin is installed.
IMediaLibraryProviderConfigurationStore providerConfigurationStore = asyncServiceScope.ServiceProvider.GetRequiredService<IMediaLibraryProviderConfigurationStore>();
Result<IEnumerable<PluginEntity>> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(stoppingToken).ConfigureAwait(false);
if (getPluginsResult.IsFailure)
@@ -128,7 +127,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
}
}
// seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type
// Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type.
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(stoppingToken).ConfigureAwait(false);
if (getLibrariesResult.IsFailure)
_logger.LogError("Failed to get the media libraries while seeding the provider configurations.");
@@ -139,6 +138,9 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
Result<Success> ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false);
if (ensureResult.IsFailure)
_logger.LogError("Failed to seed the provider configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureResult.FirstError.Description);
Result<Success> ensureBookReadersResult = await providerConfigurationStore.EnsureBookReaderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false);
if (ensureBookReadersResult.IsFailure)
_logger.LogError("Failed to seed the book reader configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureBookReadersResult.FirstError.Description);
}
}
@@ -146,8 +148,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
}
/// <summary>
/// Derives a stable unique identifier for a plugin from the file name of its assembly, so that a plugin that fails to load
/// is always identified by the same row across application restarts.
/// Derives a stable unique identifier for a plugin from the file name of its assembly, so that a plugin that fails to load is always identified by the same row across application restarts.
/// </summary>
/// <param name="assemblyName">The file name of the plugin assembly, without its extension.</param>
/// <returns>The derived plugin identifier.</returns>
@@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
#endregion
@@ -24,36 +25,83 @@ internal static class PluginLoader
public static PluginLoadResultDto LoadPlugins(string pluginsDirectory, IServiceCollection services)
{
List<IPlugin> plugins = [];
List<PluginLoadContext> loadContexts = [];
List<PluginLoadErrorDto> errors = [];
if (!Directory.Exists(pluginsDirectory))
return new PluginLoadResultDto(plugins, errors);
return new PluginLoadResultDto(plugins, loadContexts, 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
// 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())
// The plugins directory also holds the managed dependencies of the plugins (like PdfPig.dll or SkiaSharp.dll next to the PDF plugin), which are not
// plugin assemblies and must not be reflected over here. Only an assembly that references the plugin contracts can implement IPlugin, so the
// dependency assemblies are filtered out before their types are ever loaded, which would otherwise surface spurious failures (for example a
// ReflectionTypeLoadException on platform type forwarders) that the catch blocks below would report as broken plugins.
if (assembly.GetReferencedAssemblies().Any(assemblyReference => assemblyReference.Name == "Lumina.Plugins.Contracts"))
{
if (type.IsClass && !type.IsAbstract && typeof(IPlugin).IsAssignableFrom(type))
foreach (Type type in assembly.GetTypes())
{
IPlugin plugin = (IPlugin)Activator.CreateInstance(type)!;
if (plugin is IPluginServiceRegistrator serviceRegistrator)
serviceRegistrator.RegisterServices(services);
plugins.Add(plugin);
break; // only one plugin descriptor per assembly
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);
// A collectible load context is only kept alive by a direct reference to the context object itself, so the context of a loaded plugin is held for the lifetime
// of the host, keeping the plugin assemblies (and any lazily resolved dependency, like a book reader library) from being unloaded by the garbage collector.
loadContexts.Add(loadContext);
break; // Only one plugin descriptor per assembly.
}
}
}
}
catch (BadImageFormatException)
{
// A native library is a valid PE image, but it cannot be loaded as a managed assembly, so it is thrown out by LoadFromAssemblyPath before it can ever reach the
// plugin contracts reference check, and it is skipped silently. A file that is not a valid PE image at all is a genuinely broken plugin, and is recorded.
// The managed dependencies of the plugins are valid managed assemblies, so they are not rejected here: they are instead filtered out by the plugin contracts
// reference check above, before any reflection happens, and therefore never surface an error for being a non-plugin file.
if (!IsPeImage(assemblyPath))
errors.Add(new PluginLoadErrorDto(Path.GetFileNameWithoutExtension(assemblyPath), $"Failed to load plugin assembly '{Path.GetFileName(assemblyPath)}': The file is not a valid .NET assembly."));
}
catch (Exception exception)
{
errors.Add(new PluginLoadErrorDto(Path.GetFileNameWithoutExtension(assemblyPath), $"Failed to load plugin assembly '{Path.GetFileName(assemblyPath)}': {exception.Message}"));
}
}
return new PluginLoadResultDto(plugins, errors);
return new PluginLoadResultDto(plugins, loadContexts, errors);
}
/// <summary>
/// Determines whether the file at <paramref name="path"/> is a PE image (either a managed assembly or a native library),
/// by checking its DOS signature.
/// </summary>
/// <param name="path">The path of the file to check.</param>
/// <returns><see langword="true"/> when the file starts with the DOS signature of a PE image, <see langword="false"/> otherwise.</returns>
private static bool IsPeImage(string path)
{
try
{
using FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read);
Span<byte> signature = stackalloc byte[2];
if (fileStream.Read(signature) < signature.Length)
return false;
// The DOS signature "MZ" is the header every PE image starts with, whether it is a managed assembly or a native library.
return signature[0] == (byte)'M' && signature[1] == (byte)'Z';
}
catch (IOException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
}
@@ -14,14 +14,19 @@ namespace Lumina.Infrastructure.Core.Plugins;
internal sealed class PluginManager : IPluginManager
{
private readonly IReadOnlyDictionary<Guid, IPlugin> _pluginsById;
// The load contexts of the loaded plugins are held for the lifetime of the host, because a collectible load context is only kept alive by a direct reference to the
// context object itself, and the garbage collector would otherwise unload the plugin assemblies mid-request, when a lazily resolved dependency is first used.
private readonly IReadOnlyList<PluginLoadContext> _loadContexts;
/// <summary>
/// Initializes a new instance of the <see cref="PluginManager"/> class.
/// </summary>
/// <param name="plugins">The plugins that were loaded successfully.</param>
public PluginManager(IEnumerable<IPlugin> plugins)
/// <param name="loadContexts">The load contexts of the loaded plugins, kept referenced for the lifetime of the host.</param>
public PluginManager(IEnumerable<IPlugin> plugins, IReadOnlyList<PluginLoadContext> loadContexts)
{
_pluginsById = plugins.ToDictionary(plugin => plugin.Id);
_loadContexts = loadContexts;
}
/// <summary>
@@ -16,6 +16,7 @@
<ItemGroup>
<PackageReference Include="DebounceThrottle" />
<PackageReference Include="HtmlSanitizer" />
<PackageReference Include="Konscious.Security.Cryptography.Argon2" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Core" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" />