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

@@ -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>