mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 12:01:10 +00:00
Adds book reading support with EPUB and PDF reader plugins
This commit is contained in:
1 parent
275fd83ff2
commit
f7ccdf3d1c
271 files changed
+11501
-361
No files matched your search
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for the configuration of a book reader of a media library.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
|
||||
public class LibraryBookReaderConfigurationEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the configuration.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the media library the configuration belongs to.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the plugin providing the book reader.
|
||||
/// </summary>
|
||||
public required Guid PluginId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the book reader is enabled for the media library.
|
||||
/// </summary>
|
||||
public required bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+13
@@ -47,6 +47,19 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity
|
||||
/// </summary>
|
||||
public bool ShouldAggregateMetadataWhenMissing { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether PDF books are rendered as page images for the user, or not. Rendering PDFs as images preserves the
|
||||
/// original layout, but the pages are not selectable or searchable, unlike their text layer.
|
||||
/// </summary>
|
||||
public bool ShouldRenderPdfAsImages { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the styles of the book content are preserved when it is rendered for the user, or not. Preserving them
|
||||
/// keeps the original look of a book (its fonts, colors, and alignment), but the styles of a book can load resources from
|
||||
/// external servers, which those servers could observe; stripping them removes that possibility, at the cost of the look of the book.
|
||||
/// </summary>
|
||||
public bool ShouldPreserveBookStyles { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for the book reader configurations of media libraries.
|
||||
/// </summary>
|
||||
public interface ILibraryBookReaderConfigurationRepository : IRepository<LibraryBookReaderConfigurationEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets 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 retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryBookReaderConfigurationEntity"/>, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the book reader configuration of the media library identified by <paramref name="libraryId"/> for the plugin identified by <paramref name="pluginId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configuration is retrieved.</param>
|
||||
/// <param name="pluginId">The Id of the plugin whose book reader configuration is 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 <see cref="LibraryBookReaderConfigurationEntity"/>, or an error.</returns>
|
||||
Task<Result<LibraryBookReaderConfigurationEntity?>> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Inserts the provided <paramref name="configuration"/> into the storage medium, or updates it when it already exists.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The book reader configuration to insert or update.</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>
|
||||
Task<Result<Updated>> UpsertAsync(LibraryBookReaderConfigurationEntity configuration, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<Deleted>> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the book reader configurations of the media library identified by <paramref name="libraryId"/> that reference
|
||||
/// one of the plugins identified by <paramref name="pluginIds"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configurations are deleted.</param>
|
||||
/// <param name="pluginIds">The Ids of the plugins whose configurations of the media library 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>
|
||||
Task<Result<Deleted>> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable<Guid> pluginIds, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -82,6 +82,11 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the library book reader configuration repository.
|
||||
/// </summary>
|
||||
ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the plugin repository.
|
||||
/// </summary>
|
||||
|
||||
@@ -12,13 +12,13 @@ using System.Reflection;
|
||||
namespace Lumina.Application.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains all services of the Application layer.
|
||||
/// Utility class for registering the services of the Application layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class ApplicationLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the services of the Application layer into the dependency injection container.
|
||||
/// Registers the services of the Application layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
@@ -52,7 +52,7 @@ public static class ApplicationLayerServices
|
||||
continue;
|
||||
}
|
||||
|
||||
// wrap query, command, and domain event handlers in their telemetry decorator, so that every invocation emits traces, metrics, and structured logs
|
||||
// Wrap query, command, and domain event handlers in their telemetry decorator, so that every invocation emits traces, metrics, and structured logs.
|
||||
services.AddScoped(registration.Contract, serviceProvider =>
|
||||
{
|
||||
object handler = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, registration.Implementation);
|
||||
|
||||
+34
@@ -58,4 +58,38 @@ public interface IMediaLibraryProviderConfigurationStore
|
||||
/// <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>
|
||||
Task<Result<Deleted>> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<Success>> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<Success>> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<Deleted>> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<Deleted>> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Cache of whether the book reader of a plugin is enabled for a media library. The enablement is read from the database on its first
|
||||
/// use and cached afterwards, because it is consulted on every section and resource request, and it only changes when the user toggles
|
||||
/// a reader or a plugin is uninstalled; those operations invalidate the affected entries.
|
||||
/// </summary>
|
||||
public interface IBookReaderEnablementCache
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the cached enablement of the book reader of the plugin identified by <paramref name="pluginId"/> for the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader enablement is retrieved.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the book reader.</param>
|
||||
/// <returns>The cached enablement, or <see langword="null"/> when it is not cached yet.</returns>
|
||||
bool? Get(Guid libraryId, Guid pluginId);
|
||||
|
||||
/// <summary>
|
||||
/// Caches the enablement of the book reader of the plugin identified by <paramref name="pluginId"/> for the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader enablement is cached.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the book reader.</param>
|
||||
/// <param name="isEnabled">Whether the book reader is enabled for the media library.</param>
|
||||
void Set(Guid libraryId, Guid pluginId, bool isEnabled);
|
||||
|
||||
/// <summary>
|
||||
/// Removes the cached enablement of the book reader of the plugin identified by <paramref name="pluginId"/> for the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader enablement is invalidated.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the book reader.</param>
|
||||
void Invalidate(Guid libraryId, Guid pluginId);
|
||||
|
||||
/// <summary>
|
||||
/// Removes every cached enablement of the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader enablements are invalidated.</param>
|
||||
void InvalidateLibrary(Guid libraryId);
|
||||
|
||||
/// <summary>
|
||||
/// Removes every cached enablement of the plugin identified by <paramref name="pluginId"/>.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The Id of the plugin whose book reader enablements are invalidated.</param>
|
||||
void InvalidatePlugin(Guid pluginId);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Registry of the book readers provided by the loaded plugins.
|
||||
/// </summary>
|
||||
public interface IBookReaderRegistry
|
||||
{
|
||||
/// <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>
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> GetSupportedExtensionsByPluginId();
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
#endregion
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
#endregion
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
#endregion
|
||||
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetReadingAvailabilityRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetReadingAvailabilityRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetReadingAvailabilityQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetReadingAvailabilityQuery ToQuery(this GetReadingAvailabilityRequest request)
|
||||
{
|
||||
return new GetReadingAvailabilityQuery(
|
||||
request.BookId
|
||||
);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetReadingManifestRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetReadingManifestRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetReadingManifestQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetReadingManifestQuery ToQuery(this GetReadingManifestRequest request)
|
||||
{
|
||||
return new GetReadingManifestQuery(
|
||||
request.BookId
|
||||
);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetReadingResourceRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetReadingResourceRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetReadingResourceQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetReadingResourceQuery ToQuery(this GetReadingResourceRequest request)
|
||||
{
|
||||
return new GetReadingResourceQuery(
|
||||
request.BookId,
|
||||
request.ResourceKey
|
||||
);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetReadingSectionRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetReadingSectionRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetReadingSectionQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetReadingSectionQuery ToQuery(this GetReadingSectionRequest request)
|
||||
{
|
||||
return new GetReadingSectionQuery(
|
||||
request.BookId,
|
||||
request.LocationRef
|
||||
);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ReadingDocumentDto"/>.
|
||||
/// </summary>
|
||||
public static class ReadingDocumentDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="document"/> to <see cref="ReadingManifestResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="document">The reading document to be converted.</param>
|
||||
/// <returns>The converted reading manifest response.</returns>
|
||||
public static ReadingManifestResponse ToResponse(this ReadingDocumentDto document)
|
||||
{
|
||||
return new ReadingManifestResponse(
|
||||
document.Title,
|
||||
document.Author,
|
||||
document.CoverResourceKey,
|
||||
[.. document.TableOfContents.Select(entry => entry.ToResponse())],
|
||||
[.. document.Spine.Select(spineItem => new ReadingSpineItemResponse(spineItem.LocationRef, spineItem.Title))],
|
||||
[.. document.Resources.Keys],
|
||||
document.HasTextContent
|
||||
);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ReadingTocEntryDto"/>.
|
||||
/// </summary>
|
||||
public static class ReadingTocEntryDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="entry"/> to <see cref="ReadingTocEntryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="entry">The table of contents entry to be converted.</param>
|
||||
/// <returns>The converted table of contents entry response.</returns>
|
||||
public static ReadingTocEntryResponse ToResponse(this ReadingTocEntryDto entry)
|
||||
{
|
||||
return new ReadingTocEntryResponse(
|
||||
entry.Label,
|
||||
entry.LocationRef,
|
||||
[.. entry.Children.Select(child => child.ToResponse())]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetLibraryBookReadersRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetLibraryBookReadersRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetLibraryBookReadersQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetLibraryBookReadersQuery ToQuery(this GetLibraryBookReadersRequest request)
|
||||
{
|
||||
return new GetLibraryBookReadersQuery(
|
||||
request.LibraryId
|
||||
);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="LibraryBookReaderConfigurationEntity"/>.
|
||||
/// </summary>
|
||||
public static class LibraryBookReaderConfigurationEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="configuration"/> to <see cref="LibraryBookReaderResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The repository entity to be converted.</param>
|
||||
/// <param name="readerName">The display name of the book reader.</param>
|
||||
/// <param name="supportedExtensions">The file extensions supported by the book reader.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static LibraryBookReaderResponse ToResponse(this LibraryBookReaderConfigurationEntity configuration, string readerName, IReadOnlyList<string> supportedExtensions)
|
||||
{
|
||||
return new LibraryBookReaderResponse(
|
||||
configuration.PluginId,
|
||||
readerName,
|
||||
supportedExtensions,
|
||||
configuration.IsEnabled
|
||||
);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="SetLibraryBookReaderEnabledRequest"/>.
|
||||
/// </summary>
|
||||
public static class SetLibraryBookReaderEnabledRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="SetLibraryBookReaderEnabledCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static SetLibraryBookReaderEnabledCommand ToCommand(this SetLibraryBookReaderEnabledRequest request)
|
||||
{
|
||||
return new SetLibraryBookReaderEnabledCommand(
|
||||
request.LibraryId,
|
||||
request.PluginId,
|
||||
request.IsEnabled
|
||||
);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -22,7 +22,9 @@ public static class UpdateUserSettingsRequestMapping
|
||||
request.ItemsPerPage,
|
||||
request.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
request.IsThemeCachingEnabled,
|
||||
request.ShouldAggregateMetadataWhenMissing
|
||||
request.ShouldAggregateMetadataWhenMissing,
|
||||
request.ShouldRenderPdfAsImages,
|
||||
request.ShouldPreserveBookStyles
|
||||
);
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -30,7 +30,9 @@ public static class UserSettingsEntityMapping
|
||||
repositoryEntity.ItemsPerPage,
|
||||
repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
repositoryEntity.IsThemeCachingEnabled,
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing,
|
||||
repositoryEntity.ShouldRenderPdfAsImages,
|
||||
repositoryEntity.ShouldPreserveBookStyles
|
||||
);
|
||||
}
|
||||
|
||||
@@ -47,7 +49,9 @@ public static class UserSettingsEntityMapping
|
||||
repositoryEntity.ItemsPerPage,
|
||||
repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
repositoryEntity.IsThemeCachingEnabled,
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing,
|
||||
repositoryEntity.ShouldRenderPdfAsImages,
|
||||
repositoryEntity.ShouldPreserveBookStyles
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,9 @@ public static class UserSettingsMapping
|
||||
ItemsPerPage = domainEntity.ItemsPerPage,
|
||||
ShouldIgnoreThePrefixForAlphaPicker = domainEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled,
|
||||
ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing
|
||||
ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing,
|
||||
ShouldRenderPdfAsImages = domainEntity.ShouldRenderPdfAsImages,
|
||||
ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,7 +45,9 @@ public static class UserSettingsMapping
|
||||
domainEntity.ItemsPerPage,
|
||||
domainEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
domainEntity.IsThemeCachingEnabled,
|
||||
domainEntity.ShouldAggregateMetadataWhenMissing
|
||||
domainEntity.ShouldAggregateMetadataWhenMissing,
|
||||
domainEntity.ShouldRenderPdfAsImages,
|
||||
domainEntity.ShouldPreserveBookStyles
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for storing the artwork of a book into the internal media directory and serving its relative path.
|
||||
+1
-1
@@ -9,7 +9,7 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Command for adding a book.
|
||||
+1
-1
@@ -23,7 +23,7 @@ using System.Threading.Tasks;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add a book.
|
||||
+1
-1
@@ -6,7 +6,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddBookCommand"/>.
|
||||
+1
-1
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting all the books of a media library.
|
||||
+1
-1
@@ -19,7 +19,7 @@ using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get all books.
|
||||
+1
-1
@@ -5,7 +5,7 @@ using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetBooksQuery"/>.
|
||||
+1
-1
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the lightweight details of all the books of a media library.
|
||||
+1
-1
@@ -19,7 +19,7 @@ using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the lightweight details of all books.
|
||||
+1
-1
@@ -6,7 +6,7 @@ using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetBooksLiteQuery"/>.
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Query for checking the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading availability is checked.</param>
|
||||
public record GetReadingAvailabilityQuery(
|
||||
Guid BookId
|
||||
) : IQuery;
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to check the reading availability of a book.
|
||||
/// </summary>
|
||||
public class GetReadingAvailabilityQueryHandler : IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingAvailabilityQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingAvailabilityQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingAvailabilityQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to check the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</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>> HandleAsync(GetReadingAvailabilityQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
return await _bookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingAvailabilityQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingAvailabilityQueryValidator : AbstractValidator<GetReadingAvailabilityQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingAvailabilityQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading manifest is retrieved.</param>
|
||||
public record GetReadingManifestQuery(
|
||||
Guid BookId
|
||||
) : IQuery;
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the reading manifest of a book.
|
||||
/// </summary>
|
||||
public class GetReadingManifestQueryHandler : IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingManifestQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingManifestQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingManifestQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingManifestQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</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>> HandleAsync(GetReadingManifestQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preference decides whether a PDF is rendered as page images or has its text layer extracted; a
|
||||
// missing settings row falls back to the default, which is to extract the text layer.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
|
||||
return await _bookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingManifestQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingManifestQueryValidator : AbstractValidator<GetReadingManifestQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingManifestQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingManifestQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting a resource of a book, for reading.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose resource is retrieved.</param>
|
||||
/// <param name="ResourceKey">The opaque resource key of the resource.</param>
|
||||
public record GetReadingResourceQuery(
|
||||
Guid BookId,
|
||||
string ResourceKey
|
||||
) : IQuery;
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a resource of a book, for reading.
|
||||
/// </summary>
|
||||
public class GetReadingResourceQueryHandler : IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingResourceQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingResourceQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingResourceQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingResourceQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a resource of a book, for reading.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</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 of the book, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingResourceDataDto>> HandleAsync(GetReadingResourceQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preference decides whether a PDF is rendered as page images or has its text layer extracted; a
|
||||
// missing settings row falls back to the default, which is to extract the text layer.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
|
||||
return await _bookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingResourceQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingResourceQueryValidator : AbstractValidator<GetReadingResourceQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingResourceQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingResourceQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.ResourceKey)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.ResourceKeyCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the content of a reading section of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading section is retrieved.</param>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
|
||||
public record GetReadingSectionQuery(
|
||||
Guid BookId,
|
||||
string LocationRef
|
||||
) : IQuery;
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the content of a reading section of a book.
|
||||
/// </summary>
|
||||
public class GetReadingSectionQueryHandler : IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingSectionQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingSectionQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingSectionQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingSectionQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the content of a reading section of a book.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</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>> HandleAsync(GetReadingSectionQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preferences decide how the book is rendered: whether a PDF is rendered as page images or has its text
|
||||
// layer extracted, and whether the styles of the section content are preserved; a missing settings row falls back to the
|
||||
// defaults, which are to extract the text layer and to preserve the styles.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
bool shouldPreserveStyles = getSettingsResult.Value is null || getSettingsResult.Value.ShouldPreserveBookStyles;
|
||||
|
||||
return await _bookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages, shouldPreserveStyles, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingSectionQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingSectionQueryValidator : AbstractValidator<GetReadingSectionQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingSectionQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingSectionQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.LocationRef)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.LocationRefCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for reading books, using the book reader plugins configured for their media library.
|
||||
/// </summary>
|
||||
public interface IBookReadingService
|
||||
{
|
||||
/// <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>
|
||||
Task<Result<ReadingManifestResponse>> GetManifestAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, bool shouldRenderPdfAsImages, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<ReadingSectionDto>> GetSectionAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string locationRef, bool shouldRenderPdfAsImages, bool shouldPreserveStyles, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<ReadingResourceDataDto>> GetResourceAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string resourceKey, bool shouldRenderPdfAsImages, CancellationToken cancellationToken);
|
||||
|
||||
/// <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>
|
||||
Task<Result<ReadingAvailabilityResponse>> GetAvailabilityAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Command for enabling or disabling a book reader for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library whose book reader is enabled or disabled.</param>
|
||||
/// <param name="PluginId">The unique identifier of the plugin providing the book reader.</param>
|
||||
/// <param name="IsEnabled">Whether the book reader should be enabled for the media library.</param>
|
||||
public record SetLibraryBookReaderEnabledCommand(
|
||||
Guid LibraryId,
|
||||
Guid PluginId,
|
||||
bool IsEnabled
|
||||
) : ICommand;
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Reading;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to enable or disable a book reader for a media library.
|
||||
/// </summary>
|
||||
public class SetLibraryBookReaderEnabledCommandHandler : ICommandHandler<SetLibraryBookReaderEnabledCommand, Result<Success>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReaderEnablementCache _enablementCache;
|
||||
private readonly IValidator<SetLibraryBookReaderEnabledCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="enablementCache">Injected cache of whether the book reader of a plugin is enabled for a media library.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public SetLibraryBookReaderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderEnablementCache enablementCache, IUnitOfWork unitOfWork, IValidator<SetLibraryBookReaderEnabledCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_enablementCache = enablementCache;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to enable or disable a book reader for a media library.
|
||||
/// </summary>
|
||||
/// <param name="command">The request to be handled.</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>> HandleAsync(SetLibraryBookReaderEnabledCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Admins can configure the book readers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryBookReaderConfigurationEntity?> getConfigurationResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationResult.IsFailure)
|
||||
return getConfigurationResult.Errors;
|
||||
|
||||
LibraryBookReaderConfigurationEntity configuration;
|
||||
if (getConfigurationResult.Value is not null)
|
||||
{
|
||||
configuration = getConfigurationResult.Value;
|
||||
configuration.IsEnabled = command.IsEnabled;
|
||||
}
|
||||
else
|
||||
{
|
||||
configuration = new LibraryBookReaderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = command.LibraryId,
|
||||
PluginId = command.PluginId,
|
||||
IsEnabled = command.IsEnabled,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
}
|
||||
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
return upsertResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// The reading service caches the enablement of a reader, because it consults it on every request; the cache is invalidated here,
|
||||
// so that disabling a reader cuts access to its books immediately, without waiting for the cache to expire.
|
||||
_enablementCache.Invalidate(command.LibraryId, command.PluginId);
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="SetLibraryBookReaderEnabledCommand"/>.
|
||||
/// </summary>
|
||||
public class SetLibraryBookReaderEnabledCommandValidator : AbstractValidator<SetLibraryBookReaderEnabledCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public SetLibraryBookReaderEnabledCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PluginId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.PluginIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the book readers configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library whose book readers are retrieved.</param>
|
||||
public record GetLibraryBookReadersQuery(
|
||||
Guid LibraryId
|
||||
) : IQuery;
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Reading;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the book readers configured for a media library.
|
||||
/// </summary>
|
||||
public class GetLibraryBookReadersQueryHandler : IQueryHandler<GetLibraryBookReadersQuery, Result<IReadOnlyList<LibraryBookReaderResponse>>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReaderRegistry _bookReaderRegistry;
|
||||
private readonly IValidator<GetLibraryBookReadersQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryBookReadersQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReaderRegistry">Injected registry of the book readers provided by the loaded plugins.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetLibraryBookReadersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderRegistry bookReaderRegistry, IUnitOfWork unitOfWork, IValidator<GetLibraryBookReadersQuery> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReaderRegistry = bookReaderRegistry;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the book readers configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="query">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryBookReaderResponse"/>, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<IReadOnlyList<LibraryBookReaderResponse>>> HandleAsync(GetLibraryBookReadersQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Admins can read the book readers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
|
||||
// Build a plugin name lookup from the detected plugins.
|
||||
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getPluginsResult.IsFailure)
|
||||
return getPluginsResult.Errors;
|
||||
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
|
||||
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> supportedExtensionsByPluginId = _bookReaderRegistry.GetSupportedExtensionsByPluginId();
|
||||
|
||||
return getConfigurationsResult.Value
|
||||
.OrderBy(configuration => configuration.IsEnabled ? 0 : 1)
|
||||
.ThenBy(configuration => pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty, StringComparer.OrdinalIgnoreCase)
|
||||
.Select(configuration => configuration.ToResponse(
|
||||
pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty,
|
||||
supportedExtensionsByPluginId.GetValueOrDefault(configuration.PluginId) ?? []))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetLibraryBookReadersQuery"/>.
|
||||
/// </summary>
|
||||
public class GetLibraryBookReadersQueryValidator : AbstractValidator<GetLibraryBookReadersQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryBookReadersQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryBookReadersQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -12,10 +12,14 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="ShouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="ShouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
|
||||
/// <param name="ShouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
|
||||
public record UpdateUserSettingsCommand(
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled,
|
||||
bool ShouldAggregateMetadataWhenMissing
|
||||
bool ShouldAggregateMetadataWhenMissing,
|
||||
bool ShouldRenderPdfAsImages,
|
||||
bool ShouldPreserveBookStyles
|
||||
) : ICommand;
|
||||
+10
-6
@@ -53,27 +53,29 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get the existing settings of the current user, if any
|
||||
// Get the existing settings of the current user, if any.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
|
||||
if (getSettingsResult.Value is null)
|
||||
{
|
||||
// create the settings of the current user, since they are not stored yet
|
||||
// Create the settings of the current user, since they are not stored yet.
|
||||
Result<UserSettings> createSettingsResult = UserSettings.Create(
|
||||
UserId.Create(userId),
|
||||
command.IsPaginationEnabled,
|
||||
command.ItemsPerPage,
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled,
|
||||
command.ShouldAggregateMetadataWhenMissing);
|
||||
command.ShouldAggregateMetadataWhenMissing,
|
||||
command.ShouldRenderPdfAsImages,
|
||||
command.ShouldPreserveBookStyles);
|
||||
if (createSettingsResult.IsFailure)
|
||||
return createSettingsResult.Errors;
|
||||
|
||||
@@ -83,7 +85,7 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
}
|
||||
else
|
||||
{
|
||||
// update the stored settings of the current user
|
||||
// Update the stored settings of the current user.
|
||||
Result<UserSettings> toDomainEntityResult = getSettingsResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
@@ -93,7 +95,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
command.ItemsPerPage,
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled,
|
||||
command.ShouldAggregateMetadataWhenMissing);
|
||||
command.ShouldAggregateMetadataWhenMissing,
|
||||
command.ShouldRenderPdfAsImages,
|
||||
command.ShouldPreserveBookStyles);
|
||||
if (updateSettingsResult.IsFailure)
|
||||
return updateSettingsResult.Errors;
|
||||
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the normalized document model of a book, produced by a reader plugin.
|
||||
/// </summary>
|
||||
/// <param name="Title">The title of the book.</param>
|
||||
/// <param name="Author">The author of the book, if known.</param>
|
||||
/// <param name="CoverResourceKey">The resource key of the cover image of the book, if applicable.</param>
|
||||
/// <param name="TableOfContents">The hierarchical table of contents of the book.</param>
|
||||
/// <param name="Spine">The ordered spine of the reading sections of the book.</param>
|
||||
/// <param name="Resources">The resources of the book, keyed by their resource key.</param>
|
||||
/// <param name="HasTextContent">Whether the book has extractable text content. A scanned book, whose pages are only images, has no text content.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
public sealed record ReadingDocumentDto(
|
||||
string Title,
|
||||
string? Author,
|
||||
string? CoverResourceKey,
|
||||
IReadOnlyList<ReadingTocEntryDto> TableOfContents,
|
||||
IReadOnlyList<ReadingSpineItemDto> Spine,
|
||||
IReadOnlyDictionary<string, ReadingResourceInfoDto> Resources,
|
||||
bool HasTextContent
|
||||
);
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the binary data of a reading resource.
|
||||
/// </summary>
|
||||
/// <param name="Data">The binary data of the resource.</param>
|
||||
/// <param name="MimeType">The MIME type of the resource.</param>
|
||||
[DebuggerDisplay("MimeType: {MimeType}")]
|
||||
public sealed record ReadingResourceDataDto(
|
||||
byte[] Data,
|
||||
string MimeType
|
||||
);
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the file information of a resource of a reading document.
|
||||
/// </summary>
|
||||
/// <param name="RelativeFilePath">The path of the resource file, relative to the extraction directory of the book.</param>
|
||||
/// <param name="MimeType">The MIME type of the resource.</param>
|
||||
[DebuggerDisplay("RelativeFilePath: {RelativeFilePath}")]
|
||||
public sealed record ReadingResourceInfoDto(
|
||||
string RelativeFilePath,
|
||||
string MimeType
|
||||
);
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the content of a reading section.
|
||||
/// </summary>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
|
||||
/// <param name="Title">The title of the reading section, if known.</param>
|
||||
/// <param name="ContentHtml">The sanitized HTML content of the reading section, ready to be rendered by the client.</param>
|
||||
[DebuggerDisplay("LocationRef: {LocationRef}")]
|
||||
public sealed record ReadingSectionDto(
|
||||
string LocationRef,
|
||||
string? Title,
|
||||
string ContentHtml
|
||||
);
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for an item of the spine of a reading document.
|
||||
/// </summary>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
|
||||
/// <param name="Title">The title of the reading section, if known.</param>
|
||||
/// <param name="RelativeSectionFilePath">The path of the section content file, relative to the extraction directory of the book.</param>
|
||||
[DebuggerDisplay("LocationRef: {LocationRef}")]
|
||||
public sealed record ReadingSpineItemDto(
|
||||
string LocationRef,
|
||||
string? Title,
|
||||
string RelativeSectionFilePath
|
||||
);
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for an entry of the table of contents of a reading document.
|
||||
/// </summary>
|
||||
/// <param name="Label">The label of the table of contents entry.</param>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section the entry points to.</param>
|
||||
/// <param name="Children">The child entries of the table of contents entry.</param>
|
||||
[DebuggerDisplay("Label: {Label}")]
|
||||
public sealed record ReadingTocEntryDto(
|
||||
string Label,
|
||||
string LocationRef,
|
||||
IReadOnlyList<ReadingTocEntryDto> Children
|
||||
);
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to check the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading availability is checked. Required.</param>
|
||||
[DebuggerDisplay("BookId: {BookId}")]
|
||||
public sealed record GetReadingAvailabilityRequest(
|
||||
Guid BookId
|
||||
);
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to get the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading manifest is retrieved. Required.</param>
|
||||
[DebuggerDisplay("BookId: {BookId}")]
|
||||
public sealed record GetReadingManifestRequest(
|
||||
Guid BookId
|
||||
);
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to get a resource of a book, for reading.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose resource is retrieved. Required.</param>
|
||||
/// <param name="ResourceKey">The opaque resource key of the resource. Required.</param>
|
||||
[DebuggerDisplay("BookId: {BookId}, ResourceKey: {ResourceKey}")]
|
||||
public sealed record GetReadingResourceRequest(
|
||||
Guid BookId,
|
||||
string ResourceKey
|
||||
);
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to get the content of a reading section of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading section is retrieved. Required.</param>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section. Required.</param>
|
||||
[DebuggerDisplay("BookId: {BookId}, LocationRef: {LocationRef}")]
|
||||
public sealed record GetReadingSectionRequest(
|
||||
Guid BookId,
|
||||
string LocationRef
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to get the book readers configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library whose book readers are retrieved. Required.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}")]
|
||||
public sealed record GetLibraryBookReadersRequest(
|
||||
Guid LibraryId
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to enable or disable a book reader for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library whose book reader is enabled or disabled. Required.</param>
|
||||
/// <param name="PluginId">The unique identifier of the plugin providing the book reader. Required.</param>
|
||||
/// <param name="IsEnabled">Whether the book reader should be enabled for the media library. Required.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
|
||||
public sealed record SetLibraryBookReaderEnabledRequest(
|
||||
Guid LibraryId,
|
||||
Guid PluginId,
|
||||
bool IsEnabled
|
||||
);
|
||||
@@ -12,11 +12,15 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.</param>
|
||||
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not. Required.</param>
|
||||
/// <param name="ShouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required.</param>
|
||||
/// <param name="ShouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not. Required.</param>
|
||||
/// <param name="ShouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not. Required.</param>
|
||||
[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")]
|
||||
public sealed record UpdateUserSettingsRequest(
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled,
|
||||
bool ShouldAggregateMetadataWhenMissing
|
||||
bool ShouldAggregateMetadataWhenMissing,
|
||||
bool ShouldRenderPdfAsImages,
|
||||
bool ShouldPreserveBookStyles
|
||||
);
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading availability is reported.</param>
|
||||
/// <param name="LibraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="IsAvailable">Whether the book can be opened for reading.</param>
|
||||
/// <param name="ErrorCode">The code of the error preventing the book from being read, when it cannot be read. Can be <see langword="null"/> when the book is available.</param>
|
||||
[DebuggerDisplay("BookId: {BookId}, IsAvailable: {IsAvailable}")]
|
||||
public sealed record ReadingAvailabilityResponse(
|
||||
Guid BookId,
|
||||
Guid LibraryId,
|
||||
bool IsAvailable,
|
||||
string? ErrorCode
|
||||
);
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the reading manifest of a book, containing everything the client needs to render the reader.
|
||||
/// </summary>
|
||||
/// <param name="Title">The title of the book.</param>
|
||||
/// <param name="Author">The author of the book, if known.</param>
|
||||
/// <param name="CoverResourceKey">The resource key of the cover image of the book, if applicable.</param>
|
||||
/// <param name="TableOfContents">The hierarchical table of contents of the book.</param>
|
||||
/// <param name="Spine">The ordered spine of the reading sections of the book.</param>
|
||||
/// <param name="ResourceKeys">The resource keys of the resources of the book.</param>
|
||||
/// <param name="HasTextContent">Whether the book has extractable text content. A scanned book, whose pages are only images, has no text content.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
public sealed record ReadingManifestResponse(
|
||||
string Title,
|
||||
string? Author,
|
||||
string? CoverResourceKey,
|
||||
IReadOnlyList<ReadingTocEntryResponse> TableOfContents,
|
||||
IReadOnlyList<ReadingSpineItemResponse> Spine,
|
||||
IReadOnlyList<string> ResourceKeys,
|
||||
bool HasTextContent
|
||||
);
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an item of the spine of the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
|
||||
/// <param name="Title">The title of the reading section, if known.</param>
|
||||
[DebuggerDisplay("LocationRef: {LocationRef}")]
|
||||
public sealed record ReadingSpineItemResponse(
|
||||
string LocationRef,
|
||||
string? Title
|
||||
);
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an entry of the table of contents of the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="Label">The label of the table of contents entry.</param>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section the entry points to.</param>
|
||||
/// <param name="Children">The child entries of the table of contents entry.</param>
|
||||
[DebuggerDisplay("Label: {Label}")]
|
||||
public sealed record ReadingTocEntryResponse(
|
||||
string Label,
|
||||
string LocationRef,
|
||||
IReadOnlyList<ReadingTocEntryResponse> Children
|
||||
);
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a book reader configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="PluginId">The unique identifier of the plugin providing the book reader.</param>
|
||||
/// <param name="Name">The display name of the book reader.</param>
|
||||
/// <param name="SupportedExtensions">The file extensions supported by the book reader.</param>
|
||||
/// <param name="IsEnabled">Whether the book reader is enabled for the media library.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
public sealed record LibraryBookReaderResponse(
|
||||
Guid PluginId,
|
||||
string Name,
|
||||
IReadOnlyList<string> SupportedExtensions,
|
||||
bool IsEnabled
|
||||
);
|
||||
@@ -14,6 +14,8 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="ShouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="ShouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
|
||||
/// <param name="ShouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
|
||||
[DebuggerDisplay("UserId: {UserId}")]
|
||||
public sealed record UserSettingsResponse(
|
||||
Guid UserId,
|
||||
@@ -21,5 +23,7 @@ public sealed record UserSettingsResponse(
|
||||
int ItemsPerPage,
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled,
|
||||
bool ShouldAggregateMetadataWhenMissing
|
||||
bool ShouldAggregateMetadataWhenMissing,
|
||||
bool ShouldRenderPdfAsImages,
|
||||
bool ShouldPreserveBookStyles
|
||||
);
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="LibraryBookReaderConfigurationEntity"/> entity.
|
||||
/// </summary>
|
||||
public class LibraryBookReaderConfigurationConfiguration : IEntityTypeConfiguration<LibraryBookReaderConfigurationEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="LibraryBookReaderConfigurationEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<LibraryBookReaderConfigurationEntity> builder)
|
||||
{
|
||||
builder.ToTable("LibraryBookReaderConfigurations");
|
||||
builder.HasKey(configuration => configuration.Id);
|
||||
builder.Property(configuration => configuration.Id)
|
||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
||||
.HasColumnOrder(0);
|
||||
builder.Property(configuration => configuration.LibraryId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
builder.Property(configuration => configuration.PluginId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
builder.Property(configuration => configuration.IsEnabled)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
// audit
|
||||
builder.Property(configuration => configuration.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
builder.Property(configuration => configuration.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(configuration => configuration.UpdatedOnUtc)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(configuration => configuration.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(7);
|
||||
|
||||
// A media library has at most one book reader configuration per plugin, so the pair is unique; the repository upserts on it, and
|
||||
// the constraint guarantees that two concurrent upserts cannot insert duplicate rows.
|
||||
builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId })
|
||||
.IsUnique();
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,14 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
|
||||
.IsRequired()
|
||||
.HasColumnOrder(10);
|
||||
|
||||
builder.Property(settings => settings.ShouldRenderPdfAsImages)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(11);
|
||||
|
||||
builder.Property(settings => settings.ShouldPreserveBookStyles)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(12);
|
||||
|
||||
builder.Property(settings => settings.IsThemeCachingEnabled)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(9);
|
||||
|
||||
@@ -7,7 +7,6 @@ using Lumina.DataAccess.Core.Seed;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
@@ -16,13 +15,13 @@ using System.Reflection;
|
||||
namespace Lumina.DataAccess.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains all services of the DataAccess layer.
|
||||
/// Utility class for registering the services of the Data Access layer into the Dependency Injection container..
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class DataAccessLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Extension method for adding the DataAccess layer services to the DI container.
|
||||
/// Registers the services of the Data Access layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
|
||||
+1615
File diff suppressed because it is too large.
Load diff
+70
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "ShouldRenderPdfAsImages",
|
||||
table: "UserSettings",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: false)
|
||||
.Annotation("Relational:ColumnOrder", 11);
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "ShouldPreserveBookStyles",
|
||||
table: "UserSettings",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: true)
|
||||
.Annotation("Relational:ColumnOrder", 12);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "LibraryBookReaderConfigurations",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
PluginId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
IsEnabled = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_LibraryBookReaderConfigurations", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryBookReaderConfigurations_LibraryId_PluginId",
|
||||
table: "LibraryBookReaderConfigurations",
|
||||
columns: new[] { "LibraryId", "PluginId" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "LibraryBookReaderConfigurations");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ShouldRenderPdfAsImages",
|
||||
table: "UserSettings");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ShouldPreserveBookStyles",
|
||||
table: "UserSettings");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -929,6 +929,48 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.ToTable("LibraryArtworkProviderConfigurations", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<bool>("IsEnabled")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid>("PluginId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("LibraryId", "PluginId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("LibraryBookReaderConfigurations", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -1215,6 +1257,14 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<bool>("ShouldRenderPdfAsImages")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<bool>("ShouldPreserveBookStyles")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for the book reader configurations of media libraries.
|
||||
/// </summary>
|
||||
internal sealed class LibraryBookReaderConfigurationRepository : ILibraryBookReaderConfigurationRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryBookReaderConfigurationRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public LibraryBookReaderConfigurationRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets 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 retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryBookReaderConfigurationEntity"/>, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.LibraryBookReaderConfigurations
|
||||
.Where(configuration => configuration.LibraryId == libraryId)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the book reader configuration of the media library identified by <paramref name="libraryId"/> for the plugin identified by <paramref name="pluginId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configuration is retrieved.</param>
|
||||
/// <param name="pluginId">The Id of the plugin whose book reader configuration is 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 <see cref="LibraryBookReaderConfigurationEntity"/>, or an error.</returns>
|
||||
public async Task<Result<LibraryBookReaderConfigurationEntity?>> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.LibraryBookReaderConfigurations
|
||||
.FirstOrDefaultAsync(configuration => configuration.LibraryId == libraryId && configuration.PluginId == pluginId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts a book reader configuration into the storage medium, or updates it when it already exists.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The book reader configuration to insert or update.</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<Updated>> UpsertAsync(LibraryBookReaderConfigurationEntity configuration, CancellationToken cancellationToken)
|
||||
{
|
||||
LibraryBookReaderConfigurationEntity? existingConfiguration = await _luminaDbContext.LibraryBookReaderConfigurations
|
||||
.FirstOrDefaultAsync(repositoryConfiguration => repositoryConfiguration.LibraryId == configuration.LibraryId && repositoryConfiguration.PluginId == configuration.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (existingConfiguration is null)
|
||||
_luminaDbContext.LibraryBookReaderConfigurations.Add(configuration);
|
||||
else
|
||||
{
|
||||
// Update only the mutable fields, preserving the Id of the existing configuration.
|
||||
existingConfiguration.LibraryId = configuration.LibraryId;
|
||||
existingConfiguration.PluginId = configuration.PluginId;
|
||||
existingConfiguration.IsEnabled = configuration.IsEnabled;
|
||||
}
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <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>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
List<LibraryBookReaderConfigurationEntity> configurations = await _luminaDbContext.LibraryBookReaderConfigurations
|
||||
.Where(configuration => configuration.LibraryId == libraryId)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (configurations.Count > 0)
|
||||
_luminaDbContext.LibraryBookReaderConfigurations.RemoveRange(configurations);
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <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>> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken)
|
||||
{
|
||||
List<LibraryBookReaderConfigurationEntity> configurations = await _luminaDbContext.LibraryBookReaderConfigurations
|
||||
.Where(configuration => configuration.PluginId == pluginId)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (configurations.Count > 0)
|
||||
_luminaDbContext.LibraryBookReaderConfigurations.RemoveRange(configurations);
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the book reader configurations of the media library identified by <paramref name="libraryId"/> that reference
|
||||
/// one of the plugins identified by <paramref name="pluginIds"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configurations are deleted.</param>
|
||||
/// <param name="pluginIds">The Ids of the plugins whose configurations of the media library 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>> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable<Guid> pluginIds, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Guid> pluginIdList = [.. pluginIds];
|
||||
List<LibraryBookReaderConfigurationEntity> configurations = await _luminaDbContext.LibraryBookReaderConfigurations
|
||||
.Where(configuration => configuration.LibraryId == libraryId && pluginIdList.Contains(configuration.PluginId))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (configurations.Count > 0)
|
||||
_luminaDbContext.LibraryBookReaderConfigurations.RemoveRange(configurations);
|
||||
return Result.Deleted;
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ public class LuminaDbContext : DbContext
|
||||
public virtual DbSet<PluginEntity> Plugins { get; set; } = null!;
|
||||
public virtual DbSet<LibraryMetadataProviderConfigurationEntity> LibraryMetadataProviderConfigurations { get; set; } = null!;
|
||||
public virtual DbSet<LibraryArtworkProviderConfigurationEntity> LibraryArtworkProviderConfigurations { get; set; } = null!;
|
||||
public virtual DbSet<LibraryBookReaderConfigurationEntity> LibraryBookReaderConfigurations { get; set; } = null!;
|
||||
public virtual DbSet<ThemeEntity> Themes { get; set; } = null!;
|
||||
public virtual DbSet<MediaContributorEntity> MediaContributors { get; set; } = null!;
|
||||
public virtual DbSet<BookContributorEntity> BookContributors { get; set; } = null!;
|
||||
|
||||
@@ -43,6 +43,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository;
|
||||
private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository;
|
||||
private IArtworkProviderConfigurationRepository? _artworkProviderConfigurationRepository;
|
||||
private ILibraryBookReaderConfigurationRepository? _libraryBookReaderConfigurationRepository;
|
||||
private IPluginRepository? _pluginRepository;
|
||||
private IThemeRepository? _themeRepository;
|
||||
private IUserRepository? _userRepository;
|
||||
@@ -201,6 +202,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the library book reader configuration repository.
|
||||
/// </summary>
|
||||
public ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_libraryBookReaderConfigurationRepository ??= new LibraryBookReaderConfigurationRepository(_luminaDbContext);
|
||||
return _libraryBookReaderConfigurationRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the plugin repository.
|
||||
/// </summary>
|
||||
|
||||
@@ -16,13 +16,13 @@ using System.IO.Abstractions;
|
||||
namespace Lumina.Domain.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains all services of the Domain layer.
|
||||
/// Utility class for registering the services of the Domain layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class DomainLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the services of the Domain layer into the dependency injection container.
|
||||
/// Registers the services of the Domain layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Common.Errors;
|
||||
|
||||
/// <summary>
|
||||
/// Domain reading related error types.
|
||||
/// </summary>
|
||||
public static partial class Errors
|
||||
{
|
||||
public static class Reading
|
||||
{
|
||||
public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty));
|
||||
public static Error LocationRefCannotBeEmpty => Error.Validation(description: nameof(LocationRefCannotBeEmpty));
|
||||
public static Error ResourceKeyCannotBeEmpty => Error.Validation(description: nameof(ResourceKeyCannotBeEmpty));
|
||||
public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound));
|
||||
public static Error NoReaderAvailable => Error.NotFound(description: nameof(NoReaderAvailable));
|
||||
public static Error ReaderDisabled => Error.NotFound(description: nameof(ReaderDisabled));
|
||||
public static Error BookFileNotFound => Error.NotFound(description: nameof(BookFileNotFound));
|
||||
public static Error SectionNotFound => Error.NotFound(description: nameof(SectionNotFound));
|
||||
public static Error ResourceNotFound => Error.NotFound(description: nameof(ResourceNotFound));
|
||||
}
|
||||
}
|
||||
+63
-8
@@ -20,6 +20,8 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
private const bool DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER = false;
|
||||
private const bool DEFAULT_IS_THEME_CACHING_ENABLED = true;
|
||||
private const bool DEFAULT_AGGREGATE_METADATA_WHEN_MISSING = false;
|
||||
private const bool DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES = false;
|
||||
private const bool DEFAULT_SHOULD_PRESERVE_BOOK_STYLES = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the object representing the unique identifier of the user that owns these settings.
|
||||
@@ -51,6 +53,19 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
/// </summary>
|
||||
public bool ShouldAggregateMetadataWhenMissing { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether PDF books are rendered as page images for the user, or not. Rendering PDFs as images preserves the original
|
||||
/// layout, but the pages are not selectable or searchable, unlike their text layer.
|
||||
/// </summary>
|
||||
public bool ShouldRenderPdfAsImages { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the styles of the book content are preserved when it is rendered for the user, or not. Preserving them keeps the
|
||||
/// original look of a book (its fonts, colors, and alignment), but the styles of a book can load resources from external servers,
|
||||
/// which those servers could observe; stripping them removes that possibility, at the cost of the look of the book.
|
||||
/// </summary>
|
||||
public bool ShouldPreserveBookStyles { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserSettings"/> class.
|
||||
/// </summary>
|
||||
@@ -61,6 +76,8 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
|
||||
/// <param name="shouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
|
||||
private UserSettings(
|
||||
UserSettingsId id,
|
||||
UserId userId,
|
||||
@@ -68,7 +85,9 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
int itemsPerPage,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker,
|
||||
bool isThemeCachingEnabled,
|
||||
bool shouldAggregateMetadataWhenMissing) : base(id)
|
||||
bool shouldAggregateMetadataWhenMissing,
|
||||
bool shouldRenderPdfAsImages,
|
||||
bool shouldPreserveBookStyles) : base(id)
|
||||
{
|
||||
UserId = userId;
|
||||
IsPaginationEnabled = isPaginationEnabled;
|
||||
@@ -76,6 +95,8 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker;
|
||||
IsThemeCachingEnabled = isThemeCachingEnabled;
|
||||
ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing;
|
||||
ShouldRenderPdfAsImages = shouldRenderPdfAsImages;
|
||||
ShouldPreserveBookStyles = shouldPreserveBookStyles;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -86,7 +107,16 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
/// </returns>
|
||||
public static Result<UserSettings> Create()
|
||||
{
|
||||
return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING);
|
||||
return Create(
|
||||
UserId.CreateUnique(),
|
||||
DEFAULT_IS_PAGINATION_ENABLED,
|
||||
DEFAULT_ITEMS_PER_PAGE,
|
||||
DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER,
|
||||
DEFAULT_IS_THEME_CACHING_ENABLED,
|
||||
DEFAULT_AGGREGATE_METADATA_WHEN_MISSING,
|
||||
DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES,
|
||||
DEFAULT_SHOULD_PRESERVE_BOOK_STYLES
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -98,7 +128,16 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
/// </returns>
|
||||
public static Result<UserSettings> Create(UserId userId)
|
||||
{
|
||||
return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING);
|
||||
return Create(
|
||||
userId,
|
||||
DEFAULT_IS_PAGINATION_ENABLED,
|
||||
DEFAULT_ITEMS_PER_PAGE,
|
||||
DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER,
|
||||
DEFAULT_IS_THEME_CACHING_ENABLED,
|
||||
DEFAULT_AGGREGATE_METADATA_WHEN_MISSING,
|
||||
DEFAULT_SHOULD_RENDER_PDF_AS_IMAGES,
|
||||
DEFAULT_SHOULD_PRESERVE_BOOK_STYLES
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -110,6 +149,8 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
|
||||
/// <param name="shouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="UserSettings"/>, or an error message.
|
||||
/// </returns>
|
||||
@@ -119,7 +160,9 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
int itemsPerPage,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker,
|
||||
bool isThemeCachingEnabled,
|
||||
bool shouldAggregateMetadataWhenMissing)
|
||||
bool shouldAggregateMetadataWhenMissing,
|
||||
bool shouldRenderPdfAsImages,
|
||||
bool shouldPreserveBookStyles)
|
||||
{
|
||||
if (itemsPerPage <= 0)
|
||||
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
|
||||
@@ -131,7 +174,9 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
itemsPerPage,
|
||||
shouldIgnoreThePrefixForAlphaPicker,
|
||||
isThemeCachingEnabled,
|
||||
shouldAggregateMetadataWhenMissing);
|
||||
shouldAggregateMetadataWhenMissing,
|
||||
shouldRenderPdfAsImages,
|
||||
shouldPreserveBookStyles);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -144,6 +189,8 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
|
||||
/// <param name="shouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="UserSettings"/>, or an error message.
|
||||
/// </returns>
|
||||
@@ -154,12 +201,14 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
int itemsPerPage,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker,
|
||||
bool isThemeCachingEnabled,
|
||||
bool shouldAggregateMetadataWhenMissing)
|
||||
bool shouldAggregateMetadataWhenMissing,
|
||||
bool shouldRenderPdfAsImages,
|
||||
bool shouldPreserveBookStyles)
|
||||
{
|
||||
if (itemsPerPage <= 0)
|
||||
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
|
||||
|
||||
return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing);
|
||||
return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing, shouldRenderPdfAsImages, shouldPreserveBookStyles);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -170,13 +219,17 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
|
||||
/// <param name="shouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
|
||||
public Result<Updated> UpdateSettings(
|
||||
bool isPaginationEnabled,
|
||||
int itemsPerPage,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker,
|
||||
bool isThemeCachingEnabled,
|
||||
bool shouldAggregateMetadataWhenMissing)
|
||||
bool shouldAggregateMetadataWhenMissing,
|
||||
bool shouldRenderPdfAsImages,
|
||||
bool shouldPreserveBookStyles)
|
||||
{
|
||||
if (itemsPerPage <= 0)
|
||||
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
|
||||
@@ -186,6 +239,8 @@ public class UserSettings : AggregateRoot<UserSettingsId>
|
||||
ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker;
|
||||
IsThemeCachingEnabled = isThemeCachingEnabled;
|
||||
ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing;
|
||||
ShouldRenderPdfAsImages = shouldRenderPdfAsImages;
|
||||
ShouldPreserveBookStyles = shouldPreserveBookStyles;
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
+21
-12
@@ -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
|
||||
);
|
||||
+1
-1
@@ -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;
|
||||
|
||||
+2
-2
@@ -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.
|
||||
+50
@@ -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 _);
|
||||
}
|
||||
}
|
||||
+54
@@ -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;
|
||||
}
|
||||
}
|
||||
+558
@@ -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);
|
||||
}
|
||||
+26
@@ -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);
|
||||
}
|
||||
}
|
||||
+77
@@ -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" />
|
||||
|
||||
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user