Adds book reading support with EPUB and PDF reader plugins

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

No files matched your search

@@ -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; }
}
@@ -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>
@@ -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);
@@ -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,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,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,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
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -22,7 +22,9 @@ public static class UpdateUserSettingsRequestMapping
request.ItemsPerPage,
request.ShouldIgnoreThePrefixForAlphaPicker,
request.IsThemeCachingEnabled,
request.ShouldAggregateMetadataWhenMissing
request.ShouldAggregateMetadataWhenMissing,
request.ShouldRenderPdfAsImages,
request.ShouldPreserveBookStyles
);
}
}
@@ -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
);
}
}
@@ -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;
@@ -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.
@@ -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.
@@ -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.
@@ -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"/>.
@@ -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.
@@ -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.
@@ -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"/>.
@@ -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.
@@ -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.
@@ -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"/>.
@@ -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;
@@ -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);
}
}
@@ -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);
}
}
@@ -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;
@@ -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);
}
}
@@ -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);
}
}
@@ -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;
@@ -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);
}
}
@@ -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);
}
}
@@ -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;
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
@@ -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;
@@ -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;
}
}
@@ -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);
}
}
@@ -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;
@@ -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();
}
}
@@ -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);
}
}
@@ -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;
@@ -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;