From f7ccdf3d1c980416fde39007b324f2a505dd4a8d Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 2 Sep 2026 04:45:11 -0700 Subject: [PATCH 1/4] Adds book reading support with EPUB and PDF reader plugins --- Directory.Packages.props | 3 + .../DependencyInjection/CalibreServices.cs | 10 +- .../Lumina.Plugins.Calibre.csproj | 2 +- .../DependencyInjection/EpubServices.cs | 30 + .../Common/Models/DTO/Opf/OpfDocumentDto.cs | 54 + .../Models/DTO/Opf/OpfManifestItemDto.cs | 27 + .../Core/Epub/EpubDocumentParser.cs | 932 ++++++++++ .../Lumina.Plugins.Epub/Core/EpubPlugin.cs | 64 + .../Lumina.Plugins.Epub/Core/EpubReader.cs | 62 + .../Lumina.Plugins.Epub.csproj | 32 + .../Properties/AssemblyInfo.cs | 4 + .../OpenLibraryServices.cs | 8 +- .../Lumina.Plugins.OpenLibrary.csproj | 2 +- .../Common/DependencyInjection/PdfServices.cs | 30 + .../Core/Pdf/PdfDocumentParser.cs | 271 +++ plugins/Lumina.Plugins.Pdf/Core/PdfPlugin.cs | 64 + plugins/Lumina.Plugins.Pdf/Core/PdfReader.cs | 70 + .../Lumina.Plugins.Pdf.csproj | 50 + .../Properties/AssemblyInfo.cs | 4 + .../LibraryBookReaderConfigurationEntity.cs | 54 + .../UsersManagement/UserSettingsEntity.cs | 13 + ...ibraryBookReaderConfigurationRepository.cs | 68 + .../Common/DataAccess/UoW/IUnitOfWork.cs | 5 + .../ApplicationLayerServices.cs | 6 +- ...IMediaLibraryProviderConfigurationStore.cs | 34 + .../Reading/IBookReaderEnablementCache.cs | 48 + .../Reading/IBookReaderRegistry.cs | 18 + .../Books/AddBookRequestMapping.cs | 2 +- .../Books/GetBooksLiteRequestMapping.cs | 2 +- .../Books/GetBooksRequestMapping.cs | 2 +- .../GetReadingAvailabilityRequestMapping.cs | 24 + .../Books/GetReadingManifestRequestMapping.cs | 24 + .../Books/GetReadingResourceRequestMapping.cs | 25 + .../Books/GetReadingSectionRequestMapping.cs | 25 + .../Books/ReadingDocumentDtoMapping.cs | 31 + .../Books/ReadingTocEntryDtoMapping.cs | 27 + .../GetLibraryBookReadersRequestMapping.cs | 24 + ...aryBookReaderConfigurationEntityMapping.cs | 30 + ...tLibraryBookReaderEnabledRequestMapping.cs | 26 + .../Users/UpdateUserSettingsRequestMapping.cs | 4 +- .../Users/UserSettingsEntityMapping.cs | 8 +- .../Users/UserSettingsMapping.cs | 8 +- ...braryMediaItemDeletedDomainEventHandler.cs | 2 +- .../Artwork/IBookArtworkService.cs | 2 +- .../Books/Commands/AddBook/AddBookCommand.cs | 2 +- .../Commands/AddBook/AddBookCommandHandler.cs | 2 +- .../AddBook/AddBookCommandValidator.cs | 2 +- .../Books/Queries/GetBooks/GetBooksQuery.cs | 2 +- .../Queries/GetBooks/GetBooksQueryHandler.cs | 2 +- .../GetBooks/GetBooksQueryValidator.cs | 2 +- .../Queries/GetBooksLite/GetBooksLiteQuery.cs | 2 +- .../GetBooksLite/GetBooksLiteQueryHandler.cs | 2 +- .../GetBooksLiteQueryValidator.cs | 2 +- .../GetReadingAvailabilityQuery.cs | 14 + .../GetReadingAvailabilityQueryHandler.cs | 95 + .../GetReadingAvailabilityQueryValidator.cs | 24 + .../GetReadingManifestQuery.cs | 14 + .../GetReadingManifestQueryHandler.cs | 103 ++ .../GetReadingManifestQueryValidator.cs | 24 + .../GetReadingResourceQuery.cs | 16 + .../GetReadingResourceQueryHandler.cs | 102 ++ .../GetReadingResourceQueryValidator.cs | 28 + .../GetReadingSectionQuery.cs | 16 + .../GetReadingSectionQueryHandler.cs | 105 ++ .../GetReadingSectionQueryValidator.cs | 28 + .../Reading/IBookReadingService.cs | 68 + .../SetLibraryBookReaderEnabledCommand.cs | 18 + ...tLibraryBookReaderEnabledCommandHandler.cs | 106 ++ ...ibraryBookReaderEnabledCommandValidator.cs | 28 + .../GetLibraryBookReadersQuery.cs | 14 + .../GetLibraryBookReadersQueryHandler.cs | 97 + .../GetLibraryBookReadersQueryValidator.cs | 24 + .../UpdateUserSettingsCommand.cs | 6 +- .../UpdateUserSettingsCommandHandler.cs | 16 +- .../BookLibrary/Reading/ReadingDocumentDto.cs | 27 + .../Reading/ReadingResourceDataDto.cs | 16 + .../Reading/ReadingResourceInfoDto.cs | 16 + .../BookLibrary/Reading/ReadingSectionDto.cs | 18 + .../Reading/ReadingSpineItemDto.cs | 18 + .../BookLibrary/Reading/ReadingTocEntryDto.cs | 19 + .../Reading/GetReadingAvailabilityRequest.cs | 15 + .../Reading/GetReadingManifestRequest.cs | 15 + .../Reading/GetReadingResourceRequest.cs | 17 + .../Books/Reading/GetReadingSectionRequest.cs | 17 + .../Plugins/GetLibraryBookReadersRequest.cs | 15 + .../SetLibraryBookReaderEnabledRequest.cs | 19 + .../Settings/UpdateUserSettingsRequest.cs | 6 +- .../Reading/ReadingAvailabilityResponse.cs | 21 + .../Books/Reading/ReadingManifestResponse.cs | 27 + .../Books/Reading/ReadingSpineItemResponse.cs | 16 + .../Books/Reading/ReadingTocEntryResponse.cs | 19 + .../Plugins/LibraryBookReaderResponse.cs | 22 + .../Settings/UserSettingsResponse.cs | 6 +- ...aryBookReaderConfigurationConfiguration.cs | 57 + .../UserSettingsConfiguration.cs | 8 + .../DataAccessLayerServices.cs | 5 +- ...enderPdfAsImagesToUserSettings.Designer.cs | 1615 +++++++++++++++++ ...ndShouldRenderPdfAsImagesToUserSettings.cs | 70 + .../LuminaDbContextModelSnapshot.cs | 50 + ...ibraryBookReaderConfigurationRepository.cs | 130 ++ .../Core/UoW/LuminaDbContext.cs | 1 + src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs | 13 + .../DomainLayerServices.cs | 4 +- .../Common/Errors/Errors.Reading.cs | 24 + .../UserSettingsAggregate/UserSettings.cs | 71 +- .../InfrastructureLayerServices.cs | 33 +- .../Models/DTO/Plugins/PluginLoadResultDto.cs | 9 +- .../MediaLibraryScanArtworkEnrichmentJob.cs | 2 +- .../Artwork/BookArtworkService.cs | 4 +- .../Reading/BookReaderEnablementCache.cs | 50 + .../BookLibrary/Reading/BookReaderRegistry.cs | 54 + .../BookLibrary/Reading/BookReadingService.cs | 558 ++++++ .../BookLibrary/Reading/ReadingCachePaths.cs | 26 + .../Reading/ReadingContentSanitizer.cs | 77 + .../MediaLibraryProviderConfigurationStore.cs | 300 ++- .../Core/Plugins/PluginDetectionSyncJob.cs | 21 +- .../Core/Plugins/PluginLoader.cs | 68 +- .../Core/Plugins/PluginManager.cs | 7 +- .../Lumina.Infrastructure.csproj | 1 + .../Core/Reading/IBookReader.cs | 50 + .../PresentationApiLayerServices.cs | 53 +- .../PresentationApiTelemetryServices.cs | 6 +- .../Library/Management/ApiRoutes.Libraries.cs | 2 + .../BookLibrary/ApiRoutes.Books.cs | 4 + .../Books/AddBook/AddBookEndpoint.cs | 2 +- .../Books/GetBooks/GetBooksEndpoint.cs | 2 +- .../GetBooksLite/GetBooksLiteEndpoint.cs | 2 +- .../GetReadingAvailabilityEndpoint.cs | 55 + .../GetReadingAvailabilityEndpointSummary.cs | 102 ++ .../GetReadingManifestEndpoint.cs | 55 + .../GetReadingManifestEndpointSummary.cs | 120 ++ .../GetReadingResourceEndpoint.cs | 86 + .../GetReadingResourceEndpointSummary.cs | 92 + .../GetReadingSectionEndpoint.cs | 55 + .../GetReadingSectionEndpointSummary.cs | 103 ++ .../GetLibraryBookReadersEndpoint.cs | 56 + .../GetLibraryBookReadersEndpointSummary.cs | 113 ++ .../SetLibraryBookReaderEnabledEndpoint.cs | 53 + ...LibraryBookReaderEnabledEndpointSummary.cs | 99 + .../GetUserSettingsEndpointSummary.cs | 4 +- .../UpdateUserSettingsEndpointSummary.cs | 6 +- .../Core/Themes/Bundled/editorial-paper.zip | Bin 316689 -> 317372 bytes .../Core/Themes/Bundled/lumina-default.zip | Bin 316152 -> 316835 bytes src/Lumina.Presentation.Api/Program.cs | 39 +- .../DTO/Plugins/LibraryBookReaderDto.cs | 34 + .../DTO/Reading/ReadingAvailabilityDto.cs | 33 + .../Common/DTO/Reading/ReadingManifestDto.cs | 48 + .../Common/DTO/Reading/ReadingSectionDto.cs | 27 + .../Common/DTO/Reading/ReadingSpineItemDto.cs | 22 + .../Common/DTO/Reading/ReadingTocEntryDto.cs | 28 + .../DTO/UsersManagement/UserSettingsDto.cs | 13 + .../PresentationWebLayerServices.cs | 82 +- .../PresentationWebTelemetryServices.cs | 10 +- .../Path/GetPathParentRequest.cs | 2 +- .../Thumbnails/GetThumbnailRequest.cs | 4 +- .../Library/Management/EditLibraryRequest.cs | 2 +- .../Management/GetArtworkProvidersRequest.cs | 2 +- .../Management/GetBookReadersRequest.cs | 15 + .../Management/GetMetadataProvidersRequest.cs | 2 +- .../BookLibrary/Books/GetBookRequest.cs | 2 +- .../BookLibrary/Books/GetBooksViewRequest.cs | 2 +- .../GetBookReadingAvailabilityRequest.cs | 15 + .../Reading/GetBookReadingManifestRequest.cs | 15 + .../Reading/GetBookReadingResourceRequest.cs | 17 + .../Reading/GetBookReadingSectionRequest.cs | 17 + .../Books/Reading/ReadBookViewRequest.cs | 15 + .../Plugins/SetBookReaderEnabledRequest.cs | 28 + .../Requests/Themes/DeleteThemeRequest.cs | 2 +- .../Requests/Themes/GetThemeArchiveRequest.cs | 2 +- .../Requests/Themes/GetThemeAssetRequest.cs | 4 +- .../Requests/Themes/RestoreThemeRequest.cs | 2 +- .../Requests/Themes/SetCurrentThemeRequest.cs | 2 +- .../Requests/Tools/SetLanguageRequest.cs | 4 +- .../Authentication/LoginViewRequest.cs | 2 +- .../Requests/UsersManagement/LoginRequest.cs | 2 +- .../Common/Routes/ApiRoutes.Books.cs | 4 + .../Common/Routes/ApiRoutes.Libraries.cs | 2 + .../Common/Routes/WebRoutes.Books.cs | 5 + .../Routes/WebRoutes.LibraryManagement.cs | 2 + .../DeleteRole/DeleteRoleEndpointSummary.cs | 6 +- .../GetRolePermissionsEndpointSummary.cs | 6 +- .../DeleteTheme/DeleteThemeEndpointSummary.cs | 6 +- .../DownloadThemeEndpointSummary.cs | 6 +- .../SetCurrentThemeEndpointSummary.cs | 6 +- .../GetUserPermissionsEndpointSummary.cs | 6 +- .../GetUserRole/GetUserRoleEndpointSummary.cs | 6 +- .../GetDirectoriesEndpointSummary.cs | 9 +- .../Files/GetFiles/GetFilesEndpointSummary.cs | 9 +- .../GetTreeFilesEndpointSummary.cs | 9 +- .../CheckPathExistsEndpointSummary.cs | 9 +- .../GetPathParentEndpointSummary.cs | 8 +- .../GetPathRoot/GetPathRootEndpointSummary.cs | 6 +- .../SplitPath/SplitPathEndpointSummary.cs | 8 +- .../ValidatePathEndpointSummary.cs | 6 +- .../CancelLibraryScanEndpointSummary.cs | 9 +- .../DeleteLibraryEndpointSummary.cs | 6 +- .../EditLibraryViewEndpointSummary.cs | 6 +- .../GetArtworkProvidersEndpointSummary.cs | 6 +- .../GetBookReaders/GetBookReadersEndpoint.cs | 54 + .../GetBookReadersEndpointSummary.cs | 31 + .../GetMetadataProvidersEndpointSummary.cs | 6 +- .../ScanLibrary/ScanLibraryEndpointSummary.cs | 6 +- .../SetBookReaderEnabledEndpoint.cs | 54 + .../SetBookReaderEnabledEndpointSummary.cs | 37 + .../EditBook/EditBookViewEndpointSummary.cs | 6 +- .../GetLibraryItemsEndpointSummary.cs | 30 +- .../Books/Index/BooksIndexViewEndpoint.cs | 3 + .../Index/BooksIndexViewEndpointSummary.cs | 6 +- .../GetReadingAvailabilityEndpoint.cs | 54 + .../GetReadingAvailabilityEndpointSummary.cs | 37 + .../GetReadingManifestEndpoint.cs | 68 + .../GetReadingManifestEndpointSummary.cs | 38 + .../GetReadingResourceEndpoint.cs | 59 + .../GetReadingResourceEndpointSummary.cs | 33 + .../GetReadingSectionEndpoint.cs | 57 + .../GetReadingSectionEndpointSummary.cs | 33 + .../Books/Reading/Read/ReadViewEndpoint.cs | 40 + .../Reading/Read/ReadViewEndpointSummary.cs | 31 + .../GetPluginSettingsEndpointSummary.cs | 6 +- .../ThemeAssets/ThemeAssetsEndpointSummary.cs | 9 +- .../SetLanguage/SetLanguageEndpointSummary.cs | 9 +- .../Login/LoginViewEndpointSummary.cs | 6 +- .../Views/Library/Management/Item.ar-SA.resx | 13 +- .../Views/Library/Management/Item.de-DE.resx | 13 +- .../Views/Library/Management/Item.en-US.resx | 9 + .../Views/Library/Management/Item.es-ES.resx | 13 +- .../Views/Library/Management/Item.fr-FR.resx | 13 +- .../Views/Library/Management/Item.it-IT.resx | 13 +- .../Views/Library/Management/Item.ja-JP.resx | 13 +- .../Views/Library/Management/Item.resx | 9 + .../Views/Library/Management/Item.ro-RO.resx | 13 +- .../Views/Library/Management/Item.uk-UA.resx | 13 +- .../Views/Library/Management/Item.zh-CN.resx | 13 +- .../BookLibrary/Books/Index.ar-SA.resx | 8 +- .../BookLibrary/Books/Index.de-DE.resx | 6 + .../BookLibrary/Books/Index.en-US.resx | 6 + .../BookLibrary/Books/Index.es-ES.resx | 6 + .../BookLibrary/Books/Index.fr-FR.resx | 6 + .../BookLibrary/Books/Index.it-IT.resx | 6 + .../BookLibrary/Books/Index.ja-JP.resx | 6 + .../BookLibrary/Books/Index.resx | 6 + .../BookLibrary/Books/Index.ro-RO.resx | 6 + .../BookLibrary/Books/Index.uk-UA.resx | 8 +- .../BookLibrary/Books/Index.zh-CN.resx | 6 + .../BookLibrary/Books/Read.ar-SA.resx | 150 ++ .../BookLibrary/Books/Read.de-DE.resx | 150 ++ .../BookLibrary/Books/Read.en-US.resx | 150 ++ .../BookLibrary/Books/Read.es-ES.resx | 150 ++ .../BookLibrary/Books/Read.fr-FR.resx | 150 ++ .../BookLibrary/Books/Read.it-IT.resx | 150 ++ .../BookLibrary/Books/Read.ja-JP.resx | 150 ++ .../BookLibrary/Books/Read.resx | 150 ++ .../BookLibrary/Books/Read.ro-RO.resx | 150 ++ .../BookLibrary/Books/Read.uk-UA.resx | 150 ++ .../BookLibrary/Books/Read.zh-CN.resx | 150 ++ .../Resources/Views/Tools/Settings.ar-SA.resx | 12 + .../Resources/Views/Tools/Settings.de-DE.resx | 12 + .../Resources/Views/Tools/Settings.en-US.resx | 12 + .../Resources/Views/Tools/Settings.es-ES.resx | 12 + .../Resources/Views/Tools/Settings.fr-FR.resx | 12 + .../Resources/Views/Tools/Settings.it-IT.resx | 12 + .../Resources/Views/Tools/Settings.ja-JP.resx | 12 + .../Core/Resources/Views/Tools/Settings.resx | 12 + .../Resources/Views/Tools/Settings.ro-RO.resx | 12 + .../Resources/Views/Tools/Settings.uk-UA.resx | 12 + .../Resources/Views/Tools/Settings.zh-CN.resx | 12 + .../Core/Views/Library/Management/Item.cshtml | 68 +- .../BookLibrary/Books/Index.cshtml | 90 +- .../BookLibrary/Books/Read.cshtml | 320 ++++ .../Core/Views/Tools/Settings.cshtml | 64 +- .../wwwroot/css/site.css | 78 +- 271 files changed, 11501 insertions(+), 361 deletions(-) create mode 100644 plugins/Lumina.Plugins.Epub/Common/DependencyInjection/EpubServices.cs create mode 100644 plugins/Lumina.Plugins.Epub/Common/Models/DTO/Opf/OpfDocumentDto.cs create mode 100644 plugins/Lumina.Plugins.Epub/Common/Models/DTO/Opf/OpfManifestItemDto.cs create mode 100644 plugins/Lumina.Plugins.Epub/Core/Epub/EpubDocumentParser.cs create mode 100644 plugins/Lumina.Plugins.Epub/Core/EpubPlugin.cs create mode 100644 plugins/Lumina.Plugins.Epub/Core/EpubReader.cs create mode 100644 plugins/Lumina.Plugins.Epub/Lumina.Plugins.Epub.csproj create mode 100644 plugins/Lumina.Plugins.Epub/Properties/AssemblyInfo.cs create mode 100644 plugins/Lumina.Plugins.Pdf/Common/DependencyInjection/PdfServices.cs create mode 100644 plugins/Lumina.Plugins.Pdf/Core/Pdf/PdfDocumentParser.cs create mode 100644 plugins/Lumina.Plugins.Pdf/Core/PdfPlugin.cs create mode 100644 plugins/Lumina.Plugins.Pdf/Core/PdfReader.cs create mode 100644 plugins/Lumina.Plugins.Pdf/Lumina.Plugins.Pdf.csproj create mode 100644 plugins/Lumina.Plugins.Pdf/Properties/AssemblyInfo.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryBookReaderConfigurationEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryBookReaderConfigurationRepository.cs create mode 100644 src/Lumina.Application/Common/Infrastructure/Reading/IBookReaderEnablementCache.cs create mode 100644 src/Lumina.Application/Common/Infrastructure/Reading/IBookReaderRegistry.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/ReadingDocumentDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/ReadingTocEntryDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/GetLibraryBookReadersRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/LibraryBookReaderConfigurationEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Artwork/IBookArtworkService.cs (98%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Commands/AddBook/AddBookCommand.cs (98%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Commands/AddBook/AddBookCommandHandler.cs (99%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Commands/AddBook/AddBookCommandValidator.cs (99%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Queries/GetBooks/GetBooksQuery.cs (96%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Queries/GetBooks/GetBooksQueryHandler.cs (99%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Queries/GetBooks/GetBooksQueryValidator.cs (95%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs (95%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs (98%) rename src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs (97%) create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/IBookReadingService.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQuery.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryValidator.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingDocumentDto.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceDataDto.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceInfoDto.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSectionDto.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSpineItemDto.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingTocEntryDto.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Plugins/GetLibraryBookReadersRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingAvailabilityResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingManifestResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingSpineItemResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingTocEntryResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/LibraryBookReaderConfigurationConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryBookReaderConfigurationRepository.cs create mode 100644 src/Lumina.Domain/Common/Errors/Errors.Reading.cs rename src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/{BooksLibrary => BookLibrary}/Artwork/BookArtworkService.cs (99%) create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReaderEnablementCache.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReaderRegistry.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingService.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingCachePaths.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingContentSanitizer.cs create mode 100644 src/Lumina.Plugins.Contracts/Core/Reading/IBookReader.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Plugins/LibraryBookReaderDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingAvailabilityDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingManifestDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingSectionDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingSpineItemDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingTocEntryDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetBookReadersRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.de-DE.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.en-US.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.es-ES.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.fr-FR.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.it-IT.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ja-JP.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ro-RO.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.uk-UA.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.zh-CN.resx create mode 100644 src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml diff --git a/Directory.Packages.props b/Directory.Packages.props index 7f669fa1..e22e17c7 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -14,6 +14,7 @@ + @@ -49,6 +50,8 @@ + + diff --git a/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs b/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs index 20b7b97f..a5998bf0 100644 --- a/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs +++ b/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs @@ -8,16 +8,16 @@ using System; namespace Lumina.Plugins.Calibre.Common.DependencyInjection; /// -/// Provides extension methods for registering the Calibre metadata and artwork providers. +/// Utility class for registering the services of the Calibre metadata and artwork providers into the Dependency Injection container. /// internal static class CalibreServices { /// - /// Registers the Calibre book metadata provider, associated with the plugin that provides it. + /// Registers the services of the Calibre metadata provider into the Dependency Injection container. /// - /// The service collection to register the services into. + /// The service collection to add the services to. /// The unique identifier of the plugin that provides the metadata. - /// The service collection, for chaining. + /// The updated . internal static IServiceCollection AddCalibreBookMetadataProvider(this IServiceCollection services, Guid pluginId) { ArgumentNullException.ThrowIfNull(services); @@ -29,7 +29,7 @@ internal static class CalibreServices } /// - /// Registers the Calibre artwork provider, associated with the plugin that provides it. + /// Registers the services of the Calibre artwork provider into the Dependency Injection container. /// /// The service collection to register the services into. /// The unique identifier of the plugin that provides the artwork. diff --git a/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj b/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj index d8974eac..21cb19f4 100644 --- a/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj +++ b/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj @@ -21,7 +21,7 @@ - false + false runtime diff --git a/plugins/Lumina.Plugins.Epub/Common/DependencyInjection/EpubServices.cs b/plugins/Lumina.Plugins.Epub/Common/DependencyInjection/EpubServices.cs new file mode 100644 index 00000000..284e6180 --- /dev/null +++ b/plugins/Lumina.Plugins.Epub/Common/DependencyInjection/EpubServices.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Reading; +using Lumina.Plugins.Epub.Core; +using Microsoft.Extensions.DependencyInjection; +using System; +#endregion + +namespace Lumina.Plugins.Epub.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the EPUB format reader into the Dependency Injection container. +/// +internal static class EpubServices +{ + /// + /// Registers the services of the EPUB format reader into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the book reader. + /// The updated . + internal static IServiceCollection AddEpubReader(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // Register the book reader as a keyed by pluginId transient service, so it can be resolved specifically among other IBookReader implementations. + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.Epub/Common/Models/DTO/Opf/OpfDocumentDto.cs b/plugins/Lumina.Plugins.Epub/Common/Models/DTO/Opf/OpfDocumentDto.cs new file mode 100644 index 00000000..b3e6dc6b --- /dev/null +++ b/plugins/Lumina.Plugins.Epub/Common/Models/DTO/Opf/OpfDocumentDto.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Epub.Common.Models.DTO.Opf; + +/// +/// Data transfer object for the parsed OPF package document of an EPUB. +/// +[DebuggerDisplay("Title: {Title}")] +internal sealed class OpfDocumentDto +{ + /// + /// Gets or sets the title of the book. + /// + public string? Title { get; set; } + + /// + /// Gets or sets the author of the book, if applicable. + /// + public string? Author { get; set; } + + /// + /// Gets the manifest items of the EPUB. + /// + public List Items { get; } = []; + + /// + /// Gets the manifest items of the EPUB, keyed by their Id. + /// + public Dictionary ItemsById { get; } = []; + + /// + /// Gets the Ids of the manifest items that are reading sections, in reading order. + /// + public List SpineIds { get; } = []; + + /// + /// Gets or sets the Id of the manifest item of the navigation document, if applicable. + /// + public string? NavItemId { get; set; } + + /// + /// Gets or sets the Id of the manifest item of the NCX document, if applicable. + /// + public string? NcxItemId { get; set; } + + /// + /// Gets or sets the Id of the manifest item of the cover image, if applicable. + /// + public string? CoverItemId { get; set; } +} diff --git a/plugins/Lumina.Plugins.Epub/Common/Models/DTO/Opf/OpfManifestItemDto.cs b/plugins/Lumina.Plugins.Epub/Common/Models/DTO/Opf/OpfManifestItemDto.cs new file mode 100644 index 00000000..b493ef34 --- /dev/null +++ b/plugins/Lumina.Plugins.Epub/Common/Models/DTO/Opf/OpfManifestItemDto.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Epub.Common.Models.DTO.Opf; + +/// +/// Data transfer object for a manifest item of the OPF package document of an EPUB. +/// +[DebuggerDisplay("Id: {Id}")] +internal sealed class OpfManifestItemDto +{ + /// + /// Gets or sets the Id of the manifest item. + /// + public string Id { get; set; } = string.Empty; + + /// + /// Gets or sets the href of the manifest item. + /// + public string Href { get; set; } = string.Empty; + + /// + /// Gets or sets the media type of the manifest item. + /// + public string MediaType { get; set; } = string.Empty; +} diff --git a/plugins/Lumina.Plugins.Epub/Core/Epub/EpubDocumentParser.cs b/plugins/Lumina.Plugins.Epub/Core/Epub/EpubDocumentParser.cs new file mode 100644 index 00000000..bf5ade85 --- /dev/null +++ b/plugins/Lumina.Plugins.Epub/Core/Epub/EpubDocumentParser.cs @@ -0,0 +1,932 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Plugins.Epub.Common.Models.DTO.Opf; +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Xml; +using System.Xml.Linq; +#endregion + +namespace Lumina.Plugins.Epub.Core.Epub; + +/// +/// Parses an EPUB into a normalized reading document, extracting its sections and resources into a working directory. +/// +/// +/// An EPUB is a ZIP archive, so this parser works entirely with archive entry paths (always separated by '/', regardless of +/// the host operating system) and never touches the real file system except for the working directory it writes into. +/// The structure of an EPUB, read from the archive: +/// +/// +/// +/// META-INF/container.xml is the entry point. Its rootfile element points to the OPF package file. +/// +/// +/// +/// +/// The OPF package file describes the whole book, with three relevant sections: +/// +/// +/// +/// metadata: the title, the author, the language, etc. (in the Dublin Core namespace, prefixed dc). +/// +/// +/// +/// +/// manifest: the list of every file that is part of the publication (chapters, images, fonts, CSS, the +/// navigation document). Each item has an id (unique within the manifest), an href (the path of the +/// file relative to the OPF file), and a media-type. +/// +/// +/// +/// +/// spine: the READING ORDER of the book, named after the spine of a physical book. It is a list of +/// itemref elements, each referencing a manifest item by its id. The spine is literally how the book +/// reads front to back: chapter 1 first, then chapter 2, and so on. The items listed in the spine are the +/// "sections" this reader serves. +/// +/// +/// +/// +/// +/// +/// +/// The table of contents comes from the navigation document (EPUB 3) or the NCX document (EPUB 2). +/// +/// +/// +/// This parser extracts each spine section as an HTML file and each other usable file (images, fonts, CSS) as a resource, +/// and describes the result with the format-agnostic model. The host serves those files. +/// +internal static class EpubDocumentParser +{ + // The archive is untrusted input, so every document read from it is bounded, and the total expanded size is capped so + // that a tiny archive cannot expand into a decompression bomb that exhausts the memory of the host. + private const long MAX_CONTAINER_FILE_SIZE_BYTES = 1024 * 1024; + private const long MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024; + private const long MAX_NAV_FILE_SIZE_BYTES = 5 * 1024 * 1024; + private const long MAX_SECTION_FILE_SIZE_BYTES = 10 * 1024 * 1024; + private const long MAX_RESOURCE_FILE_SIZE_BYTES = 20 * 1024 * 1024; + private const long MAX_TOTAL_EXPANDED_BYTES = 256 * 1024 * 1024; + private const int MAX_ARCHIVE_ENTRIES = 20_000; + + private static readonly XNamespace s_opfNamespace = "http://www.idpf.org/2007/opf"; + private static readonly XNamespace s_dcNamespace = "http://purl.org/dc/elements/1.1/"; + private static readonly XNamespace s_ncxNamespace = "http://www.daisy.org/z3986/2005/ncx/"; + private static readonly XNamespace s_epubNamespace = "http://www.idpf.org/2007/ops"; + private static readonly XNamespace s_xlinkNamespace = "http://www.w3.org/1999/xlink"; + private static readonly XNamespace s_containerNamespace = "urn:oasis:names:tc:opendocument:xmlns:container"; + + // The XHTML content documents, the navigation documents, and the package documents of real books declare a DTD (for example + // "") and use the named character references that the DTD defines (for example  ). The parser must + // never load those external DTDs, because they are untrusted input, so before a document is parsed, its document type declaration + // is removed and the HTML named character references the DTD would have defined are resolved into the characters they stand for. + // The XML parser still resolves the five entities defined by XML itself (&, <, >, ", ') and the numeric references. + private static readonly Dictionary s_htmlNamedCharacterReferences = new() + { + ["nbsp"] = '\u00A0', ["iexcl"] = '\u00A1', ["cent"] = '\u00A2', ["pound"] = '\u00A3', ["curren"] = '\u00A4', ["yen"] = '\u00A5', + ["brvbar"] = '\u00A6', ["sect"] = '\u00A7', ["uml"] = '\u00A8', ["copy"] = '\u00A9', ["ordf"] = '\u00AA', ["laquo"] = '\u00AB', + ["not"] = '\u00AC', ["shy"] = '\u00AD', ["reg"] = '\u00AE', ["macr"] = '\u00AF', ["deg"] = '\u00B0', ["plusmn"] = '\u00B1', + ["sup2"] = '\u00B2', ["sup3"] = '\u00B3', ["acute"] = '\u00B4', ["micro"] = '\u00B5', ["para"] = '\u00B6', ["middot"] = '\u00B7', + ["cedil"] = '\u00B8', ["sup1"] = '\u00B9', ["ordm"] = '\u00BA', ["raquo"] = '\u00BB', ["frac14"] = '\u00BC', ["frac12"] = '\u00BD', + ["frac34"] = '\u00BE', ["iquest"] = '\u00BF', ["Agrave"] = '\u00C0', ["Aacute"] = '\u00C1', ["Acirc"] = '\u00C2', ["Atilde"] = '\u00C3', + ["Auml"] = '\u00C4', ["Aring"] = '\u00C5', ["AElig"] = '\u00C6', ["Ccedil"] = '\u00C7', ["Egrave"] = '\u00C8', ["Eacute"] = '\u00C9', + ["Ecirc"] = '\u00CA', ["Euml"] = '\u00CB', ["Igrave"] = '\u00CC', ["Iacute"] = '\u00CD', ["Icirc"] = '\u00CE', ["Iuml"] = '\u00CF', + ["ETH"] = '\u00D0', ["Ntilde"] = '\u00D1', ["Ograve"] = '\u00D2', ["Oacute"] = '\u00D3', ["Ocirc"] = '\u00D4', ["Otilde"] = '\u00D5', + ["Ouml"] = '\u00D6', ["times"] = '\u00D7', ["Oslash"] = '\u00D8', ["Ugrave"] = '\u00D9', ["Uacute"] = '\u00DA', ["Ucirc"] = '\u00DB', + ["Uuml"] = '\u00DC', ["Yacute"] = '\u00DD', ["THORN"] = '\u00DE', ["szlig"] = '\u00DF', ["agrave"] = '\u00E0', ["aacute"] = '\u00E1', + ["acirc"] = '\u00E2', ["atilde"] = '\u00E3', ["auml"] = '\u00E4', ["aring"] = '\u00E5', ["aelig"] = '\u00E6', ["ccedil"] = '\u00E7', + ["egrave"] = '\u00E8', ["eacute"] = '\u00E9', ["ecirc"] = '\u00EA', ["euml"] = '\u00EB', ["igrave"] = '\u00EC', ["iacute"] = '\u00ED', + ["icirc"] = '\u00EE', ["iuml"] = '\u00EF', ["eth"] = '\u00F0', ["ntilde"] = '\u00F1', ["ograve"] = '\u00F2', ["oacute"] = '\u00F3', + ["ocirc"] = '\u00F4', ["otilde"] = '\u00F5', ["ouml"] = '\u00F6', ["divide"] = '\u00F7', ["oslash"] = '\u00F8', ["ugrave"] = '\u00F9', + ["uacute"] = '\u00FA', ["ucirc"] = '\u00FB', ["uuml"] = '\u00FC', ["yacute"] = '\u00FD', ["thorn"] = '\u00FE', ["yuml"] = '\u00FF', + ["OElig"] = '\u0152', ["oelig"] = '\u0153', ["Scaron"] = '\u0160', ["scaron"] = '\u0161', ["Yuml"] = '\u0178', ["fnof"] = '\u0192', + ["circ"] = '\u02C6', ["tilde"] = '\u02DC', ["ensp"] = '\u2002', ["emsp"] = '\u2003', ["thinsp"] = '\u2009', ["zwnj"] = '\u200C', + ["zwj"] = '\u200D', ["lrm"] = '\u200E', ["rlm"] = '\u200F', ["ndash"] = '\u2013', ["mdash"] = '\u2014', ["lsquo"] = '\u2018', + ["rsquo"] = '\u2019', ["sbquo"] = '\u201A', ["ldquo"] = '\u201C', ["rdquo"] = '\u201D', ["bdquo"] = '\u201E', ["dagger"] = '\u2020', + ["Dagger"] = '\u2021', ["bull"] = '\u2022', ["hellip"] = '\u2026', ["permil"] = '\u2030', ["prime"] = '\u2032', ["Prime"] = '\u2033', + ["lsaquo"] = '\u2039', ["rsaquo"] = '\u203A', ["oline"] = '\u203E', ["frasl"] = '\u2044', ["euro"] = '\u20AC', ["image"] = '\u2111', + ["weierp"] = '\u2118', ["real"] = '\u211C', ["trade"] = '\u2122', ["alefsym"] = '\u2135', ["larr"] = '\u2190', ["uarr"] = '\u2191', + ["rarr"] = '\u2192', ["darr"] = '\u2193', ["harr"] = '\u2194', ["crarr"] = '\u21B5', ["lArr"] = '\u21D0', ["uArr"] = '\u21D1', + ["rArr"] = '\u21D2', ["dArr"] = '\u21D3', ["hArr"] = '\u21D4', ["forall"] = '\u2200', ["part"] = '\u2202', ["exist"] = '\u2203', + ["empty"] = '\u2205', ["nabla"] = '\u2207', ["isin"] = '\u2208', ["notin"] = '\u2209', ["ni"] = '\u220B', ["prod"] = '\u220F', + ["sum"] = '\u2211', ["minus"] = '\u2212', ["lowast"] = '\u2217', ["radic"] = '\u221A', ["prop"] = '\u221D', ["infin"] = '\u221E', + ["ang"] = '\u2220', ["and"] = '\u2227', ["or"] = '\u2228', ["cap"] = '\u2229', ["cup"] = '\u222A', ["int"] = '\u222B', + ["there4"] = '\u2234', ["sim"] = '\u223C', ["cong"] = '\u2245', ["asymp"] = '\u2248', ["ne"] = '\u2260', ["equiv"] = '\u2261', + ["le"] = '\u2264', ["ge"] = '\u2265', ["sub"] = '\u2282', ["sup"] = '\u2283', ["nsub"] = '\u2284', ["sube"] = '\u2286', + ["supe"] = '\u2287', ["oplus"] = '\u2295', ["otimes"] = '\u2297', ["perp"] = '\u22A5', ["sdot"] = '\u22C5', ["lceil"] = '\u2308', + ["rceil"] = '\u2309', ["lfloor"] = '\u230A', ["rfloor"] = '\u230B', ["lang"] = '\u2329', ["rang"] = '\u232A', ["loz"] = '\u25CA', + ["spades"] = '\u2660', ["clubs"] = '\u2663', ["hearts"] = '\u2665', ["diams"] = '\u2666' + }; + private static readonly Regex s_namedCharacterReferencePattern = new("&([A-Za-z][A-Za-z0-9]*);", RegexOptions.Compiled); + + /// + /// Parses the EPUB stored at , extracting its sections and resources into , and returns its normalized reading document. + /// + /// The file system path of the EPUB. + /// The directory into which the sections and resources of the EPUB are extracted. + /// Cancellation token that can be used to stop the execution. + /// The normalized reading document of the EPUB. + public static ReadingDocumentDto Parse(string epubPath, string workingDirectory, CancellationToken cancellationToken) + { + // The EPUB is opened as a ZIP archive. + using FileStream fileStream = File.OpenRead(epubPath); + using ZipArchive zipArchive = new(fileStream, ZipArchiveMode.Read); + ValidateArchive(zipArchive); + + // The declared sizes are not trustworthy, so the total-expanded cap is enforced on the bytes actually read: every entry read below is streamed through + // ReadEntry, which adds every byte it returns to this running total and rejects the archive the moment the cap is exceeded (see ReadEntry). + long totalExpandedBytes = 0; + + // The container document points to the OPF package file, the file that describes the whole book; + // without it, there is no way to know what the book contains, so there is nothing left to parse. + string? opfPath = ReadContainerPath(zipArchive, ref totalExpandedBytes, cancellationToken) ?? throw new InvalidDataException("The EPUB contains no OPF file."); + + // The manifest hrefs are relative to the directory of the OPF file, so that directory is kept around to resolve them. + string opfDirectory = GetDirectory(opfPath); + OpfDocumentDto opfDocument = ReadOpf(zipArchive, opfPath, ref totalExpandedBytes, cancellationToken); + + // The spine is the reading order of the book. An EPUB with an empty spine declares no readable content at all - there is nothing to present to the reader. + if (opfDocument.SpineIds.Count == 0) + throw new InvalidDataException("The EPUB contains no reading sections."); + + // Build a lookup that maps every reachable archive file to the opaque value its references should be rewritten to. + // A section's HTML references other files of the book by their archive path, for example, , but the client could be remote, and cannot reach into the ZIP. + // So, before a section is served, every such reference must be replaced by a marker (data-lumina-resource) that the host turns into a resource endpoint URL. + // This lookup is what makes that rewrite possible: given the archive path a reference points to, it answers which marker to use. + Dictionary targetByResolvedPath = []; + HashSet spineItemIds = [.. opfDocument.SpineIds]; + foreach (OpfManifestItemDto epubManifestItem in opfDocument.Items) + { + // Resolve the href of the manifest item into its actual archive entry path; null means the href is broken or escapes the archive (for example, an absolute path or a path with ".." above the root), + // which is _ONE_ bad manifest item, so it is skipped and the rest of the book is still parsed. + string? entryPath = ResolveEntryPath(opfDirectory, epubManifestItem.Href); + if (entryPath is null) + continue; + + // A reference to a spine section is rewritten to the section's location reference (the manifest item Id), so the client can navigate to it; a reference to any other extractable resource is rewritten to the resource + // key, so the client can load it. + if (spineItemIds.Contains(epubManifestItem.Id)) + targetByResolvedPath[entryPath] = epubManifestItem.Id; + else if (IsResourceMediaType(epubManifestItem.MediaType)) + targetByResolvedPath[entryPath] = CreateResourceKey(epubManifestItem.Href); + } + + // The rest of the extraction follows the same order as the document model: resources first, then the table of contents, then the sections, so that every stage has what the next one needs. + Dictionary resources = ExtractResources(zipArchive, workingDirectory, opfDirectory, opfDocument, spineItemIds, ref totalExpandedBytes, cancellationToken); + + (List tableOfContents, Dictionary titlesByItemId) = BuildTableOfContents(zipArchive, opfDocument, opfDirectory, targetByResolvedPath, ref totalExpandedBytes, cancellationToken); + + List spine = ExtractSections(zipArchive, workingDirectory, opfDirectory, opfDocument, targetByResolvedPath, titlesByItemId, ref totalExpandedBytes, cancellationToken); + + // The cover is the manifest item flagged as the cover image (see ReadOpf), exposed to the client as a resource key so the client can fetch it through the resource endpoint like any other image of the book. + string? coverResourceKey = null; + if (opfDocument.CoverItemId is not null && opfDocument.ItemsById.TryGetValue(opfDocument.CoverItemId, out OpfManifestItemDto? coverItem) && resources.TryGetValue(CreateResourceKey(coverItem.Href), out _)) + coverResourceKey = CreateResourceKey(coverItem.Href); + + // Fall back to the file name when the package declares no title, so that the book always has a usable title. + string title = !string.IsNullOrWhiteSpace(opfDocument.Title) ? opfDocument.Title.Trim() : Path.GetFileNameWithoutExtension(epubPath); + return new ReadingDocumentDto(title, opfDocument.Author, coverResourceKey, tableOfContents, spine, resources, HasTextContent: true); + } + + /// + /// Validates the archive bounds, so that a decompression bomb cannot exhaust the memory of the host. + /// + /// The EPUB archive to validate. + private static void ValidateArchive(ZipArchive zipArchive) + { + // A decompression bomb is a small ZIP whose entries expand into a huge amount of data; a simple way to defend against it is to bound how many entries the archive may declare and how much uncompressed data it may claim. + if (zipArchive.Entries.Count > MAX_ARCHIVE_ENTRIES) + throw new InvalidDataException("The EPUB archive contains too many entries."); + + // The declared uncompressed sizes are not trustworthy, so this sum only bounds the worst case before any single entry is read; it is a cheap first guard, + // not the real defense. The real cap is enforced on the bytes actually read while every entry is streamed (see ReadEntry), because a hostile archive could + // declare small sizes yet expand into far more data than the parser is willing to extract. + long totalExpandedBytes = 0; + foreach (ZipArchiveEntry zipArchiveEntry in zipArchive.Entries) + { + totalExpandedBytes += zipArchiveEntry.Length; + if (totalExpandedBytes > MAX_TOTAL_EXPANDED_BYTES) + throw new InvalidDataException("The expanded EPUB archive is too large."); + } + } + + /// + /// Reads the path of the OPF file from the container document of the EPUB. + /// + /// The EPUB archive. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The path of the OPF file, or when it could not be read. + private static string? ReadContainerPath(ZipArchive zipArchive, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + // The container document lives at a fixed, mandatory location inside the archive; if it is missing, the EPUB is structurally invalid and cannot be opened. + ZipArchiveEntry? containerEntry = zipArchive.GetEntry("META-INF/container.xml"); + if (containerEntry is null) + return null; + + XDocument container; + try + { + container = ReadXmlEntry(zipArchive, "META-INF/container.xml", MAX_CONTAINER_FILE_SIZE_BYTES, ref totalExpandedBytes, cancellationToken); + } + catch (XmlException) + { + // A malformed container document means the book cannot be opened, but it must not crash the host, so it is reported as "no OPF file" instead of propagating the parse error. + return null; + } + + // The rootfile element holds the path of the OPF package file in its "full-path" attribute; the container uses its own XML namespace, which is unrelated to the OPF namespace used by the rest of the book. + return container.Descendants(s_containerNamespace + "rootfile").FirstOrDefault()?.Attribute("full-path")?.Value; + } + + /// + /// Reads and parses the OPF document of the EPUB. + /// + /// The EPUB archive. + /// The path of the OPF file. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The parsed OPF document. + private static OpfDocumentDto ReadOpf(ZipArchive zipArchive, string opfPath, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + XDocument xDocument = ReadXmlEntry(zipArchive, opfPath, MAX_OPF_FILE_SIZE_BYTES, ref totalExpandedBytes, cancellationToken); + XElement? package = xDocument.Root; + + // The metadata holds the title and the author of the book, in the Dublin Core namespace. + OpfDocumentDto opfDocument = new() + { + Title = package?.Element(s_opfNamespace + "metadata")?.Element(s_dcNamespace + "title")?.Value, + Author = package?.Element(s_opfNamespace + "metadata")?.Element(s_dcNamespace + "creator")?.Value + }; + + // The navigation document and the cover image are identified by the properties of their manifest items; both are + // optional (an EPUB may have no table of contents and no cover), and the first item carrying the property wins. + string? navItemId = null; + string? coverItemId = null; + foreach (XElement itemElement in package?.Element(s_opfNamespace + "manifest")?.Elements(s_opfNamespace + "item") ?? []) + { + string? id = itemElement.Attribute("id")?.Value; + string? href = itemElement.Attribute("href")?.Value; + string? mediaType = itemElement.Attribute("media-type")?.Value; + // An item without an id or an href cannot be referenced by the spine or by the sections, so it is useless and skipped, like any other single broken manifest item. + if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(href)) + continue; + + OpfManifestItemDto opfManifestItem = new() + { + Id = id, + Href = href.Trim(), + MediaType = mediaType ?? string.Empty + }; + opfDocument.ItemsById[id] = opfManifestItem; + opfDocument.Items.Add(opfManifestItem); + + string? properties = itemElement.Attribute("properties")?.Value; + if (properties is not null && properties.Split(' ').Any(property => string.Equals(property, "nav", StringComparison.OrdinalIgnoreCase))) + navItemId ??= id; + if (properties is not null && properties.Split(' ').Any(property => string.Equals(property, "cover-image", StringComparison.OrdinalIgnoreCase))) + coverItemId ??= id; + } + + // The spine lists the reading order of the sections, as references to manifest item Ids (see the class remarks). + // An item that is not listed in the spine is not a section, even when it carries textual content (for example, the navigation document), which is why the sections are derived from the spine and not from the manifest. + // The lookup against itemsById drops the itemrefs that reference an unknown Id, since they are broken references. + opfDocument.SpineIds.AddRange(package?.Element(s_opfNamespace + "spine")?.Elements(s_opfNamespace + "itemref") + .Select(itemRef => itemRef.Attribute("idref")?.Value) + .Where(idref => idref is not null) + .Select(idref => idref!) + .Where(id => opfDocument.ItemsById.ContainsKey(id)) ?? []); + + // EPUB 2 declares the cover with a meta element referencing the manifest item of the cover image, instead of the cover-image property of the item itself, so both declarations are honored and whichever one exists wins. + foreach (XElement metaElement in package?.Element(s_opfNamespace + "metadata")?.Elements(s_opfNamespace + "meta") ?? []) + { + if (string.Equals(metaElement.Attribute("name")?.Value, "cover", StringComparison.OrdinalIgnoreCase)) + { + string? content = metaElement.Attribute("content")?.Value; + if (content is not null && opfDocument.ItemsById.ContainsKey(content)) + coverItemId ??= content; + } + } + + // The NCX document, used as the fallback table of contents of EPUB 2, is referenced by the "toc" attribute of the spine, and is used only when the book has no EPUB 3 navigation document (see BuildTableOfContents). + opfDocument.NavItemId = navItemId; + opfDocument.CoverItemId = coverItemId; + opfDocument.NcxItemId = package?.Element(s_opfNamespace + "spine")?.Attribute("toc")?.Value; + + return opfDocument; + } + + /// + /// Extracts the resources of the EPUB into the resources directory of the working directory. + /// + /// The EPUB archive. + /// The directory into which the resources are extracted. + /// The directory of the OPF file, used to resolve the manifest hrefs. + /// The parsed OPF document. + /// The Ids of the manifest items that are reading sections, which are not extracted as resources. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The extracted resources, keyed by their resource key. + private static Dictionary ExtractResources(ZipArchive zipArchive, string workingDirectory, string opfDirectory, OpfDocumentDto opfDocument, HashSet spineItemIds, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + Dictionary resources = []; + foreach (OpfManifestItemDto opfManifestItem in opfDocument.Items) + { + // The spine sections are extracted separately as readable sections, so they are skipped here; everything else that is a usable media file (image, font, CSS, audio, video) is extracted as a resource, + // and the rest of the manifest (for example the navigation document) is not extracted at all, because nothing references it. + if (spineItemIds.Contains(opfManifestItem.Id) || !IsResourceMediaType(opfManifestItem.MediaType)) + continue; + + string? entryPath = ResolveEntryPath(opfDirectory, opfManifestItem.Href); + if (entryPath is null) + continue; + ZipArchiveEntry? zipArchiveEntry = zipArchive.GetEntry(entryPath); + if (zipArchiveEntry is null) + continue; + + // The resource key is derived from the manifest href, so the same file referenced from several sections maps to one extracted file, and the key doubles as a safe, opaque file name that cannot contain path characters. + string key = CreateResourceKey(opfManifestItem.Href); + if (resources.ContainsKey(key)) + continue; + + byte[] data = ReadEntry(zipArchiveEntry, MAX_RESOURCE_FILE_SIZE_BYTES, ref totalExpandedBytes, cancellationToken); + string destinationDirectory = Path.Combine(workingDirectory, "resources"); + Directory.CreateDirectory(destinationDirectory); + File.WriteAllBytes(Path.Combine(destinationDirectory, key), data); + // The media type declared by the manifest is kept, so that the host can serve the resource with the right Content-Type; a missing media type falls back to a generic binary type. + resources[key] = new ReadingResourceInfoDto($"resources/{key}", string.IsNullOrWhiteSpace(opfManifestItem.MediaType) ? "application/octet-stream" : opfManifestItem.MediaType); + } + return resources; + } + + /// + /// Extracts the reading sections of the EPUB into the sections directory of the working directory. + /// + /// The EPUB archive. + /// The directory into which the sections are extracted. + /// The directory of the OPF file, used to resolve the manifest hrefs. + /// The parsed OPF document. + /// The target of every resolvable manifest item, keyed by its resolved archive path. + /// The titles of the reading sections, keyed by the Id of their manifest item. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The extracted reading sections of the EPUB. + private static List ExtractSections(ZipArchive zipArchive, string workingDirectory, string opfDirectory, OpfDocumentDto opfDocument, Dictionary targetByResolvedPath, Dictionary titlesByItemId, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + List spine = []; + string sectionsDirectory = Path.Combine(workingDirectory, "sections"); + Directory.CreateDirectory(sectionsDirectory); + for (int index = 0; index < opfDocument.SpineIds.Count; index++) + { + string itemId = opfDocument.SpineIds[index]; + OpfManifestItemDto opfManifestItem = opfDocument.ItemsById[itemId]; + + string? entryPath = ResolveEntryPath(opfDirectory, opfManifestItem.Href); + if (entryPath is null) + continue; + ZipArchiveEntry? zipArchiveEntry = zipArchive.GetEntry(entryPath); + if (zipArchiveEntry is null) + continue; + + byte[] data = ReadEntry(zipArchiveEntry, MAX_SECTION_FILE_SIZE_BYTES, ref totalExpandedBytes, cancellationToken); + string content = RewriteSectionContent(data, entryPath, targetByResolvedPath, cancellationToken); + + // The section file name is the spine position, which is stable, while the location reference exposed to the client is the manifest item Id, + // which is the identifier shared with the table of contents entries; keeping the two separate means the file name never leaks to the client. + string sectionFileName = $"{index}.html"; + File.WriteAllText(Path.Combine(sectionsDirectory, sectionFileName), content, Encoding.UTF8); + spine.Add(new ReadingSpineItemDto(itemId, titlesByItemId.GetValueOrDefault(itemId), $"sections/{sectionFileName}")); + } + return spine; + } + + /// + /// Rewrites the resource references of a reading section into the resource marker attribute, so that the host can + /// rewrite them to the resource endpoint when serving the section. + /// + /// The raw content of the reading section. + /// The archive path of the reading section, used to resolve its references. + /// The target of every resolvable manifest item, keyed by its resolved archive path. + /// Cancellation token that can be used to stop the execution. + /// The rewritten content of the reading section. + private static string RewriteSectionContent(byte[] data, string sectionEntryPath, Dictionary targetByResolvedPath, CancellationToken cancellationToken) + { + // The section is parsed as XML so that its references can be rewritten in a structured, attribute-by-attribute way. + XDocument xDocument; + try + { + // A section of a real book typically declares a DTD (for example "") and uses the named character + // references that the DTD defines (for example  ); the external DTD is never loaded because it is untrusted, so the content + // is normalized first - the document type declaration is removed and the HTML named character references are resolved - and only + // then parsed as XML. + string normalizedContent = NormalizeDocumentText(data); + XmlReaderSettings xmlReaderSettings = new() + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + MaxCharactersInDocument = MAX_SECTION_FILE_SIZE_BYTES, + MaxCharactersFromEntities = 0 + }; + using StringReader stringReader = new(normalizedContent); + using XmlReader xmlReader = XmlReader.Create(stringReader, xmlReaderSettings); + xDocument = XDocument.Load(xmlReader, LoadOptions.None); + } + catch (XmlException) + { + // A section that is not well formed XML cannot have its references rewritten in a structured way, so it is served "as-is", + // with its internal references unresolved; the host still sanitizes it before serving, so the section stays safe even when its images cannot load. + return Encoding.UTF8.GetString(data); + } + + string sectionDirectory = GetDirectory(sectionEntryPath); + + // xDocument is the XML tree of the section: an element can contain child elements, which contain their own children, and so on, like a family tree. Descendants() yields EVERY element nested at any depth below the root - + // the direct children, the grandchildren, the great-grandchildren, etc. - unlike Elements(), which yields only the direct children. The whole tree must be walked, because the images and links of a chapter can be nested + // arbitrarily deep inside divs, paragraphs, tables, etc., and every one of their references needs the same rewrite. + foreach (XElement element in xDocument.Descendants()) + { + cancellationToken.ThrowIfCancellationRequested(); + + // ToList() takes a snapshot of the attributes before iterating, because the loop removes the rewritten attributes below (attribute.Remove()); mutating a collection while enumerating it would throw an exception. + // An attribute is a name="value" pair written on the opening tag of the element (for example class, id, style). + foreach (XAttribute attribute in element.Attributes().ToList()) + { + // Most attributes cannot point at another file (class, id, style, ...), so they are skipped right away; only the ones that carry a reference (src, href, poster, xlink:href) are candidates for the rewrite. + if (!IsResourceReferenceAttribute(attribute)) + continue; + + // References that cannot point inside the archive are left untouched: same-page anchors (starting with "#"), inline data URIs, and absolute web references, all keep their original value, + // and the sanitizer strips the dangerous ones before the section is served. + string? reference = attribute.Value?.Trim(); + if (string.IsNullOrWhiteSpace(reference)) + continue; + if (reference.StartsWith('#') || reference.StartsWith("data:", StringComparison.OrdinalIgnoreCase) + || reference.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || reference.StartsWith("https://", StringComparison.OrdinalIgnoreCase) + || reference.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase) || reference.StartsWith("tel:", StringComparison.OrdinalIgnoreCase)) + continue; + + // Spliit the fragment off the path, resolve the path against the directory of the section, and only rewrite references that point at an extracted + // manifest item; a broken reference (a path that does not exist in the manifest) is left alone, instead of being rewritten to a marker that leads nowhere. + string path = reference.Contains('#') ? reference[..reference.IndexOf('#')] : reference; + string? resolvedPath = ResolveEntryPath(sectionDirectory, path); + if (resolvedPath is null || !targetByResolvedPath.TryGetValue(resolvedPath, out string? target)) + continue; + + // The original attribute is removed and replaced by the resource marker, so that the browser does not attempt to load the internal archive path, + // which it cannot reach; the client resolves the marker to the resource endpoint instead. + element.SetAttributeValue("data-lumina-resource", target); + attribute.Remove(); + } + } + + return xDocument.ToString(SaveOptions.DisableFormatting); + } + + /// + /// Determines whether is an attribute carrying a resource reference. + /// + /// The attribute to check. + /// when the attribute carries a resource reference, otherwise. + private static bool IsResourceReferenceAttribute(XAttribute attribute) + { + // These are the attributes in which a section can point at another file of the book; xlink:href is used by SVG, and the local name is compared, so that the check works regardless of the XML namespace of the element. + string localName = attribute.Name.LocalName; + return localName is "src" or "poster" or "href" || attribute.Name == s_xlinkNamespace + "href"; + } + + /// + /// Builds the table of contents of the EPUB, from its navigation document or its NCX document. + /// + /// The EPUB archive. + /// The parsed OPF document. + /// The directory of the OPF file, used to resolve the manifest hrefs. + /// The target of every resolvable manifest item, keyed by its resolved archive path. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The table of contents entries, and the titles of the reading sections keyed by the Id of their manifest item. + private static (List entries, Dictionary titlesByItemId) BuildTableOfContents(ZipArchive zipArchive, OpfDocumentDto opfDocument, string opfDirectory, Dictionary targetByResolvedPath, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + Dictionary titlesByItemId = []; + List entries = []; + + // EPUB 3 carries its table of contents in the navigation document; EPUB 2 falls back to the NCX document, and only when the EPUB 3 one produced no entries, so that a book carrying both prefers the newer format. + if (opfDocument.NavItemId is not null && opfDocument.ItemsById.TryGetValue(opfDocument.NavItemId, out OpfManifestItemDto? navItem)) + { + string? navPath = ResolveEntryPath(opfDirectory, navItem.Href); + if (navPath is not null) + entries = ReadNavigationDocument(zipArchive, navPath, targetByResolvedPath, titlesByItemId, ref totalExpandedBytes, cancellationToken); + } + + if (entries.Count == 0 && opfDocument.NcxItemId is not null && opfDocument.ItemsById.TryGetValue(opfDocument.NcxItemId, out OpfManifestItemDto? ncxItem)) + { + string? ncxPath = ResolveEntryPath(opfDirectory, ncxItem.Href); + if (ncxPath is not null) + entries = ReadNcxDocument(zipArchive, ncxPath, targetByResolvedPath, titlesByItemId, ref totalExpandedBytes, cancellationToken); + } + + return (entries, titlesByItemId); + } + + /// + /// Reads the table of contents from the navigation document of an EPUB 3. + /// + /// The EPUB archive. + /// The archive path of the navigation document. + /// The target of every resolvable manifest item, keyed by its resolved archive path. + /// The titles of the reading sections, keyed by the Id of their manifest item. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The table of contents entries. + private static List ReadNavigationDocument(ZipArchive zipArchive, string navPath, Dictionary targetByResolvedPath, Dictionary titlesByItemId, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + XDocument xDocument; + try + { + xDocument = ReadXmlEntry(zipArchive, navPath, MAX_NAV_FILE_SIZE_BYTES, ref totalExpandedBytes, cancellationToken); + } + catch (XmlException) + { + return []; + } + + // The table of contents is the nav element declared with the epub:type "toc"; a navigation document may carry other nav elements (for example the page list), which are ignored because they are not the table of contents. + XElement? navElement = xDocument.Descendants() + .FirstOrDefault(element => string.Equals(element.Name.LocalName, "nav", StringComparison.OrdinalIgnoreCase) + && element.Attributes().Any(attribute => string.Equals(attribute.Name.LocalName, "type", StringComparison.OrdinalIgnoreCase) + && string.Equals(attribute.Value, "toc", StringComparison.OrdinalIgnoreCase))); + if (navElement is null) + return []; + + // The entries of the table of contents are the list items of that nav element; the nested lists inside a list item become its children, which preserves the hierarchy of the table of contents. + return [.. navElement.Descendants() + .Where(element => string.Equals(element.Name.LocalName, "li", StringComparison.OrdinalIgnoreCase)) + .Select(element => ParseNavListItem(element, navPath, targetByResolvedPath, titlesByItemId))]; + } + + /// + /// Parses a list item of the navigation document into a table of contents entry. + /// + /// The list item element to parse. + /// The archive path of the navigation document. + /// The target of every resolvable manifest item, keyed by its resolved archive path. + /// The titles of the reading sections, keyed by the Id of their manifest item. + /// The parsed table of contents entry. + private static ReadingTocEntryDto ParseNavListItem(XElement listItem, string navPath, Dictionary targetByResolvedPath, Dictionary titlesByItemId) + { + // The label of the entry is the text of its anchor, and its target is the section the anchor points to. + XElement? anchor = listItem.Elements().FirstOrDefault(element => string.Equals(element.Name.LocalName, "a", StringComparison.OrdinalIgnoreCase)); + string label = string.IsNullOrWhiteSpace(anchor?.Value) ? string.Empty : anchor.Value.Trim(); + string locationRef = GetLocationRef(anchor?.Attribute("href")?.Value, navPath, targetByResolvedPath, titlesByItemId, label); + + // The nested lists of the list item become the children of the entry, so the hierarchy of the table of contents is preserved; a list item that carries no anchor yields an entry whose label and location reference + // are both empty, which the client simply does not render as a navigable entry. + List children = [.. listItem.Elements() + .Where(element => string.Equals(element.Name.LocalName, "ol", StringComparison.OrdinalIgnoreCase)) + .SelectMany(element => element.Elements().Where(child => string.Equals(child.Name.LocalName, "li", StringComparison.OrdinalIgnoreCase))) + .Select(child => ParseNavListItem(child, navPath, targetByResolvedPath, titlesByItemId))]; + + return new ReadingTocEntryDto(label, locationRef, children); + } + + /// + /// Reads the table of contents from the NCX document of an EPUB 2. + /// + /// The EPUB archive. + /// The archive path of the NCX document. + /// The target of every resolvable manifest item, keyed by its resolved archive path. + /// The titles of the reading sections, keyed by the Id of their manifest item. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The table of contents entries. + private static List ReadNcxDocument(ZipArchive zipArchive, string ncxPath, Dictionary targetByResolvedPath, Dictionary titlesByItemId, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + XDocument xDocument; + try + { + xDocument = ReadXmlEntry(zipArchive, ncxPath, MAX_NAV_FILE_SIZE_BYTES, ref totalExpandedBytes, cancellationToken); + } + catch (XmlException) + { + return []; + } + + // The table of contents of an NCX document lives in its navMap element, as a tree of nested navPoint elements. + return [.. xDocument.Descendants(s_ncxNamespace + "navMap") + .SelectMany(element => element.Elements(s_ncxNamespace + "navPoint")) + .Select(element => ParseNcxNavPoint(element, ncxPath, targetByResolvedPath, titlesByItemId))]; + } + + /// + /// Parses a navigation point of the NCX document into a table of contents entry. + /// + /// The navigation point element to parse. + /// The archive path of the NCX document. + /// The target of every resolvable manifest item, keyed by its resolved archive path. + /// The titles of the reading sections, keyed by the Id of their manifest item. + /// The parsed table of contents entry. + private static ReadingTocEntryDto ParseNcxNavPoint(XElement navigationPoint, string ncxPath, Dictionary targetByResolvedPath, Dictionary titlesByItemId) + { + // The label of the entry is the text of its navLabel, and its target is the src of its content element; nested navigation points become the children of the entry, mirroring the hierarchy of the navigation document. + string label = string.IsNullOrWhiteSpace(navigationPoint.Element(s_ncxNamespace + "navLabel")?.Element(s_ncxNamespace + "text")?.Value) + ? string.Empty + : navigationPoint.Element(s_ncxNamespace + "navLabel")!.Element(s_ncxNamespace + "text")!.Value.Trim(); + string? href = navigationPoint.Element(s_ncxNamespace + "content")?.Attribute("src")?.Value; + string locationRef = GetLocationRef(href, ncxPath, targetByResolvedPath, titlesByItemId, label); + + List children = [.. navigationPoint.Elements(s_ncxNamespace + "navPoint") + .Select(child => ParseNcxNavPoint(child, ncxPath, targetByResolvedPath, titlesByItemId))]; + + return new ReadingTocEntryDto(label, locationRef, children); + } + + /// + /// Resolves the location reference of a table of contents reference, and records the title of its target section. + /// + /// The href of the table of contents reference. + /// The archive path of the document containing the reference. + /// The target of every resolvable manifest item, keyed by its resolved archive path. + /// The titles of the reading sections, keyed by the Id of their manifest item. + /// The label of the table of contents entry. + /// The location reference of the target section, or an empty string when it could not be resolved. + private static string GetLocationRef(string? href, string documentPath, Dictionary targetByResolvedPath, Dictionary titlesByItemId, string label) + { + if (string.IsNullOrWhiteSpace(href)) + return string.Empty; + + // A table of contents reference may carry a same-page fragment, which is dropped because the reader navigates at the section level, not at a position inside a section. + string path = href.Contains('#') ? href[..href.IndexOf('#')] : href; + string? resolvedPath = ResolveEntryPath(GetDirectory(documentPath), path); + // A reference that cannot be resolved to a known section yields an entry that points nowhere, so that one broken table of contents entry does not drop the whole table of contents. + if (resolvedPath is null || !targetByResolvedPath.TryGetValue(resolvedPath, out string? target)) + return string.Empty; + + // The label of the first table of contents entry pointing at a section becomes its title, so that the spine items show the chapter names instead of being untitled; + // TryAdd keeps the first label seen, since it is the one the table of contents lists first. + if (!string.IsNullOrWhiteSpace(label)) + titlesByItemId.TryAdd(target, label); + return target; + } + + /// + /// Determines whether the provided media type identifies a resource that is extracted from the EPUB. + /// + /// The media type to check. + /// when the media type identifies an extractable resource, otherwise. + private static bool IsResourceMediaType(string mediaType) + { + if (mediaType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) + return true; + if (mediaType.StartsWith("font/", StringComparison.OrdinalIgnoreCase)) + return true; + if (mediaType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || mediaType.StartsWith("video/", StringComparison.OrdinalIgnoreCase)) + return true; + // The font media types do not share a common prefix, so the common ones are listed explicitly; everything else in the manifest (for example the navigation document or a script) is not a resource the reader serves. + return mediaType is "text/css" + or "application/font-woff" or "application/font-woff2" or "application/vnd.ms-opentype" + or "application/x-font-ttf" or "application/x-font-opentype"; + } + + /// + /// Resolves a manifest href against the , rejecting paths that escape the archive. + /// + /// The directory against which the href is resolved. + /// The href to resolve. + /// The normalized archive path, or when it escapes the archive. + private static string? ResolveEntryPath(string baseDirectory, string href) + { + // The paths are ZIP archive entry paths, which the ZIP spec always separates with '/', so backslashes (which a hostile EPUB could contain) are normalized to '/' + // and the segments are split on '/' regardless of the host OS. This is why the whole method must NOT use Path.DirectorySeparatorChar or Path.Combine: an EPUB read + // on Windows still has '/' inside its archive. + string normalized = href.Replace('\\', '/').Trim(); + // An empty, absolute, or NUL-containing path can never be a legitimate archive entry: an absolute path would point outside the archive, and a NUL byte is a path injection, so both are rejected. + if (normalized.Length == 0 || normalized.StartsWith('/') || normalized.Contains('\0')) + return null; + + // The href is relative to the base directory, so they are joined, and then the "." and ".." segments are resolved by hand; a ".." that would walk above the root + // of the archive would escape it, so it is rejected (a path traversal attempt), which is why the method returns null instead of an entry path. + string combined = string.IsNullOrEmpty(baseDirectory) ? normalized : $"{baseDirectory}/{normalized}"; + string[] segments = combined.Split('/'); + Stack stack = []; + foreach (string segment in segments) + { + if (segment is "" or ".") + continue; + if (segment == "..") + { + if (stack.Count == 0) + return null; + stack.Pop(); + continue; + } + stack.Push(segment); + } + + return string.Join('/', stack.Reverse()); + } + + /// + /// Gets the directory part of an archive path. + /// + /// The archive path. + /// The directory of the archive path. + private static string GetDirectory(string path) + { + // The paths are ZIP archive entry paths, which the ZIP spec always separates with '/' regardless of the host OS, so this must NOT use Path.DirectorySeparatorChar: an EPUB read on Windows still has '/' inside its archive. + int lastSlash = path.LastIndexOf('/'); + return lastSlash < 0 ? string.Empty : path[..lastSlash]; + } + + /// + /// Creates the opaque resource key of a manifest href. + /// + /// The manifest href. + /// The resource key of the href. + private static string CreateResourceKey(string href) + { + // Hashing the href yields a stable key per file, regardless of the characters it contains, so the same file referenced from several sections always maps to the + // same extracted file; and a hex digest is a safe file name that cannot contain path characters, so it is used both as the extracted file name and as the resource + // key the client sends back to the resource endpoint. + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(href)))[..32].ToLowerInvariant(); + } + + /// + /// Converts the raw content of an XML or XHTML document of the archive into text that the XML parser can load: the document type + /// declaration is removed, because the external DTD it references is untrusted and must never be loaded, and the HTML named character + /// references that the declaration would have defined are resolved into the characters they stand for (see the field documentation). + /// + /// The raw content of the document. + /// The content, normalized for XML parsing. + private static string NormalizeDocumentText(byte[] data) + { + string text = DecodeDocumentText(data); + if (text.IndexOf("= 0) + text = RemoveDocumentTypeDeclaration(text); + if (text.IndexOf('&') >= 0) + text = ResolveNamedCharacterReferences(text); + return text; + } + + /// + /// Decodes the raw content of an XML or XHTML document of the archive into text, honoring its byte order mark. + /// + /// The raw content of the document. + /// The decoded text of the document, without its byte order mark. + private static string DecodeDocumentText(byte[] data) + { + // EPUB mandates UTF-8 or UTF-16, so the byte order mark is the reliable way to tell the two apart; a document without a mark is UTF-8. + if (data.Length >= 2 && data[0] == 0xFF && data[1] == 0xFE) + return Encoding.Unicode.GetString(data, 2, data.Length - 2); + if (data.Length >= 2 && data[0] == 0xFE && data[1] == 0xFF) + return Encoding.BigEndianUnicode.GetString(data, 2, data.Length - 2); + if (data.Length >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF) + return Encoding.UTF8.GetString(data, 3, data.Length - 3); + return Encoding.UTF8.GetString(data); + } + + /// + /// Removes every document type declaration of an XML or XHTML document, including any internal subset it carries, so that the XML + /// parser never encounters the external DTD the declaration references. + /// + /// The text of the document. + /// The text of the document without its document type declarations. + private static string RemoveDocumentTypeDeclaration(string text) + { + // The declaration spans from "", which must be tracked through quoted strings (a declaration can quote a + // system identifier) and through the "[ ... ]" of an internal subset (which can contain ">" inside entity declarations). + int declarationStart = text.IndexOf("= 0) + { + char activeQuote = '\0'; + int internalSubsetDepth = 0; + int declarationEnd = -1; + for (int index = declarationStart + "' && internalSubsetDepth <= 0) + { + declarationEnd = index; + break; + } + } + if (declarationEnd < 0) + break; + text = text.Remove(declarationStart, declarationEnd - declarationStart + 1); + declarationStart = text.IndexOf(" + /// Resolves the HTML named character references of an XML or XHTML document into the characters they stand for. The five entities that + /// XML defines itself and the numeric references are left to the XML parser; an entity that is not mapped is left untouched, so that the + /// parse then fails and the caller falls back to its existing resilience path. + /// + /// The text of the document. + /// The text of the document with its mapped HTML named character references resolved. + private static string ResolveNamedCharacterReferences(string text) + { + return s_namedCharacterReferencePattern.Replace(text, match => + { + string entityName = match.Groups[1].Value; + if (entityName is "amp" or "lt" or "gt" or "quot" or "apos") + return match.Value; + return s_htmlNamedCharacterReferences.TryGetValue(entityName, out char character) ? character.ToString() : match.Value; + }); + } + + /// + /// Reads an XML entry of the archive with hardened XML settings. + /// + /// The EPUB archive. + /// The archive path of the entry. + /// The maximum allowed size of the entry. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The parsed XML document. + private static XDocument ReadXmlEntry(ZipArchive zipArchive, string entryPath, long maxBytes, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + ZipArchiveEntry? zipArchiveEntry = zipArchive.GetEntry(entryPath) ?? throw new InvalidDataException($"The archive contains no entry at '{entryPath}'."); + byte[] data = ReadEntry(zipArchiveEntry, maxBytes, ref totalExpandedBytes, cancellationToken); + + // Every XML document of the EPUB is untrusted input, so DTD processing and external entity resolution are disabled (a DTD could declare entities that read local files, or expand into the "billion laughs" attack), and the size of the document is bounded. + // The content is normalized first (see NormalizeDocumentText), so that the document type declaration the document may carry - and its + // external DTD - is removed before the XML parser sees it, without loosening the hardened settings above. + string normalizedContent = NormalizeDocumentText(data); + XmlReaderSettings xmlReaderSettings = new() + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + MaxCharactersInDocument = maxBytes, + MaxCharactersFromEntities = 0 + }; + using StringReader stringReader = new(normalizedContent); + using XmlReader xmlReader = XmlReader.Create(stringReader, xmlReaderSettings); + return XDocument.Load(xmlReader, LoadOptions.None); + } + + /// + /// Reads the content of an archive entry, bounded by . + /// + /// The archive entry to read. + /// The maximum allowed size of the entry. + /// The running total of the bytes actually read from the archive, so that the cap on the total expanded size is enforced on the streamed content rather than on the untrustworthy declared sizes. + /// Cancellation token that can be used to stop the execution. + /// The content of the archive entry. + private static byte[] ReadEntry(ZipArchiveEntry entry, long maxBytes, ref long totalExpandedBytes, CancellationToken cancellationToken) + { + // The declared size of the entry is checked up front, as a cheap first guard, but it is not trustworthy, so the bound is enforced again while the entry is streamed, + // and every byte actually read is added to the running total of the whole EPUB, so that no sum of small entries can bypass the total-expanded cap. + if (entry.Length > maxBytes) + throw new InvalidDataException($"The archive entry '{entry.FullName}' is too large."); + + // The entry is then streamed into memory while the limit is enforced again on the bytes actually read, because the declared size is not trustworthy and a hostile archive could lie about it. + using Stream stream = entry.Open(); + using MemoryStream memoryStream = new(); + byte[] buffer = new byte[64 * 1024]; + long totalBytes = 0; + while (true) + { + int read = stream.Read(buffer, 0, buffer.Length); + if (read == 0) + break; + cancellationToken.ThrowIfCancellationRequested(); + totalBytes += read; + if (totalBytes > maxBytes) + throw new InvalidDataException($"The archive entry '{entry.FullName}' is too large."); + totalExpandedBytes += read; + if (totalExpandedBytes > MAX_TOTAL_EXPANDED_BYTES) + throw new InvalidDataException("The expanded EPUB archive is too large."); + memoryStream.Write(buffer, 0, read); + } + return memoryStream.ToArray(); + } +} diff --git a/plugins/Lumina.Plugins.Epub/Core/EpubPlugin.cs b/plugins/Lumina.Plugins.Epub/Core/EpubPlugin.cs new file mode 100644 index 00000000..dfd531cf --- /dev/null +++ b/plugins/Lumina.Plugins.Epub/Core/EpubPlugin.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Epub.Common.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.Epub.Core; + +/// +/// Plugin that decodes EPUB books into a normalized reading document. +/// +public sealed class EpubPlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("b1e8a8e0-4f3a-4d2c-9a1e-6d3f8a9b2c3d"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "EPUB Reader"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Allows reading of EPUB format books."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return []; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddEpubReader(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.Epub/Core/EpubReader.cs b/plugins/Lumina.Plugins.Epub/Core/EpubReader.cs new file mode 100644 index 00000000..eca7cb73 --- /dev/null +++ b/plugins/Lumina.Plugins.Epub/Core/EpubReader.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Reading; +using Lumina.Plugins.Epub.Core.Epub; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Epub.Core; + +/// +/// Book reader for the EPUB format. +/// +/// +/// See for what an EPUB is, and how it is decoded; this class only declares the supported format and delegates the decoding to the parser. +/// +internal sealed class EpubReader : IBookReader +{ + /// + /// Gets the file extensions supported by the reader. + /// + public IReadOnlyList SupportedExtensions => [".epub"]; + + /// + /// Gets the media library types the reader supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.EBook, LibraryType.Book]; + + /// + /// Opens the EPUB stored at , extracting its sections and resources into + /// , and returns its normalized reading document. + /// + /// The file system path of the EPUB. + /// The directory into which the sections and resources of the EPUB are extracted. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. An EPUB always has a text layer, so this is ignored. + /// Cancellation token that can be used to stop the execution. + /// The normalized reading document of the EPUB. + public Task OpenAsync(string path, string workingDirectory, bool shouldRenderPdfAsImages, CancellationToken cancellationToken) + { + return Task.FromResult(EpubDocumentParser.Parse(path, workingDirectory, cancellationToken)); + } + + /// + /// Produces the resource identified by of the EPUB stored at . + /// Every resource of an EPUB is extracted to the working directory when the book is opened, so this reads the + /// already extracted file. The resource key is the safe file name the parser derives from the manifest href, and the + /// file is contained-checked by the host before it is served, so the key cannot escape the resources directory. + /// + /// The file system path of the EPUB. + /// The directory into which the sections and resources of the EPUB are extracted. + /// The opaque resource key of the resource to produce. + /// Cancellation token that can be used to stop the execution. + /// The binary data of the extracted resource. + public Task GetResourceAsync(string path, string workingDirectory, string resourceKey, CancellationToken cancellationToken) + { + byte[] data = File.ReadAllBytes(Path.Combine(workingDirectory, "resources", resourceKey)); + return Task.FromResult(data); + } +} diff --git a/plugins/Lumina.Plugins.Epub/Lumina.Plugins.Epub.csproj b/plugins/Lumina.Plugins.Epub/Lumina.Plugins.Epub.csproj new file mode 100644 index 00000000..21cb19f4 --- /dev/null +++ b/plugins/Lumina.Plugins.Epub/Lumina.Plugins.Epub.csproj @@ -0,0 +1,32 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + + + + + + + + + + + + + + false + runtime + + + + + + + diff --git a/plugins/Lumina.Plugins.Epub/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Epub/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..d1808970 --- /dev/null +++ b/plugins/Lumina.Plugins.Epub/Properties/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.Epub.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Epub.Fixtures")] diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs index 3505cf7c..d6cca097 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs @@ -13,17 +13,17 @@ using System; namespace Lumina.Plugins.OpenLibrary.Common.DependencyInjection; /// -/// Provides extension methods for registering the Open Library metadata provider services. +/// Utility class for registering the services of the Open Library metadata provider into the Dependency Injection container. /// internal static class OpenLibraryServices { /// - /// Registers the Open Library book metadata provider and its dependencies, associated with the plugin that provides it. + /// Registers the services of the Open Library metadata provider into the Dependency Injection container. /// - /// The service collection to register the services into. + /// The service collection to add the services to. /// The unique identifier of the plugin that provides the metadata. /// Action used to configure the . - /// The service collection, for chaining. + /// The updated . internal static IServiceCollection AddOpenLibraryBookMetadataProvider(this IServiceCollection services, Guid pluginId, Action? settingsCallback = null) { ArgumentNullException.ThrowIfNull(services); diff --git a/plugins/Lumina.Plugins.OpenLibrary/Lumina.Plugins.OpenLibrary.csproj b/plugins/Lumina.Plugins.OpenLibrary/Lumina.Plugins.OpenLibrary.csproj index a0f2e745..56fbb4a4 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Lumina.Plugins.OpenLibrary.csproj +++ b/plugins/Lumina.Plugins.OpenLibrary/Lumina.Plugins.OpenLibrary.csproj @@ -21,7 +21,7 @@ - false + false runtime diff --git a/plugins/Lumina.Plugins.Pdf/Common/DependencyInjection/PdfServices.cs b/plugins/Lumina.Plugins.Pdf/Common/DependencyInjection/PdfServices.cs new file mode 100644 index 00000000..c2c14c22 --- /dev/null +++ b/plugins/Lumina.Plugins.Pdf/Common/DependencyInjection/PdfServices.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Reading; +using Lumina.Plugins.Pdf.Core; +using Microsoft.Extensions.DependencyInjection; +using System; +#endregion + +namespace Lumina.Plugins.Pdf.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the PDF format reader into the Dependency Injection container. +/// +internal static class PdfServices +{ + /// + /// Registers the services of the PDF format reader into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the book reader. + /// The updated . + internal static IServiceCollection AddPdfReader(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // Register the book reader as a keyed by pluginId transient service, so it can be resolved specifically among other IBookReader implementations. + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.Pdf/Core/Pdf/PdfDocumentParser.cs b/plugins/Lumina.Plugins.Pdf/Core/Pdf/PdfDocumentParser.cs new file mode 100644 index 00000000..36168e6b --- /dev/null +++ b/plugins/Lumina.Plugins.Pdf/Core/Pdf/PdfDocumentParser.cs @@ -0,0 +1,271 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using PDFtoImage; +using SkiaSharp; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Runtime.Versioning; +using System.Text; +using System.Threading; +using UglyToad.PdfPig; +using UglyToad.PdfPig.Content; +using UglyToad.PdfPig.Outline; +#endregion + +namespace Lumina.Plugins.Pdf.Core.Pdf; + +/// +/// Parses a PDF into a normalized reading document, extracting the text of its pages into a working directory. +/// +/// +/// A PDF is a fixed-layout document, that positions its content on pages that never change. The reading order of a PDF is simply page 1, page 2, page 3, and so on, so this reader maps each page to one +/// reading section whose location reference is its page number ("page:{n}"). +/// +/// PdfPig reads the text layer of the pages, that is, the text that the PDF encodes for selection and search. A scanned book has no text layer, only page images, so its pages yield no text. +/// The table of contents, when the PDF has one, comes from its bookmarks (the document outline), where each bookmark points to a page. +/// +internal static class PdfDocumentParser +{ + // A PDF is parsed only once per book, and the pages are extracted to disk and served from there, so the in-memory footprint stays bounded regardless of the size of the book; + // the file size and page count are still capped so that a hostile document cannot exhaust the disk or the CPU of the host. + private const long MAX_PDF_FILE_SIZE_BYTES = 500 * 1024 * 1024; + private const int MAX_PAGES = 10_000; + // PDFtoImage renders at the natural size of the page, so the pixel size of the bitmap follows the page size in points: a hostile + // page whose MediaBox declares thousands of points would otherwise allocate a multi-gigabyte bitmap. Rendering is therefore limited + // to pages of at most 4000 points on each side and at most 9,000,000 points squared in area, which keeps the rendered bitmap, four + // bytes per pixel, bounded at a few tens of megabytes. + private const int MAX_RENDER_PAGE_DIMENSION = 4000; + private const int MAX_RENDER_PAGE_AREA = 9_000_000; + + /// + /// Parses the PDF stored at , extracting its pages into , and returns its normalized reading document. + /// + /// The file system path of the PDF. + /// The directory into which the pages of the PDF are extracted. + /// Whether the PDF is rendered as page images instead of extracting its text layer. This is used for scanned PDFs whose pages are only images and therefore yield no text. + /// Cancellation token that can be used to stop the execution. + /// The normalized reading document of the PDF. + public static ReadingDocumentDto Parse(string pdfPath, string workingDirectory, bool shouldRenderPdfAsImages, CancellationToken cancellationToken) + { + FileInfo fileInfo = new(pdfPath); + if (!fileInfo.Exists) + throw new FileNotFoundException("The PDF file could not be found.", pdfPath); + if (fileInfo.Length > MAX_PDF_FILE_SIZE_BYTES) + throw new InvalidDataException("The PDF file is too large."); + + // The pages are extracted into the sections directory, and, when the PDF is rendered as images, the page images into the + // resources directory, from which they are served like any other book resource. + string sectionsDirectory = Path.Combine(workingDirectory, "sections"); + Directory.CreateDirectory(sectionsDirectory); + + // When the PDF is rendered as images, the text layer is not read at all: a scanned PDF has no text layer, so reading it + // would produce nothing, and rendering the pages as images is the only way to make such a book readable. + if (shouldRenderPdfAsImages) + return ParseAsImages(pdfPath, sectionsDirectory, cancellationToken); + + return ParseAsText(pdfPath, sectionsDirectory, cancellationToken); + } + + /// + /// Parses the PDF stored at by enumerating its pages, registering each page as a section whose only + /// element references the page image, and returns its normalized reading document. The page images are not rendered here: a page + /// is rendered to an image only when its resource is requested, so that opening a large book is instant and the user does not + /// wait for every page to be rendered before seeing the first one. + /// + /// The file system path of the PDF. + /// The directory into which the section files of the PDF are written. + /// Cancellation token that can be used to stop the execution. + /// The normalized reading document of the PDF, without a text layer. + private static ReadingDocumentDto ParseAsImages(string pdfPath, string sectionsDirectory, CancellationToken cancellationToken) + { + List spine = []; + Dictionary resources = []; + List tableOfContents = []; + using (PdfDocument pdfDocument = PdfDocument.Open(pdfPath)) + { + foreach (Page page in pdfDocument.GetPages()) + { + cancellationToken.ThrowIfCancellationRequested(); + if (page.Number > MAX_PAGES) + break; + + // The location reference of a page is its 1-based page number (PdfPig pages are numbered from 1), which is the only + // stable identifier a PDF page has, and it doubles as the name of the section file. A page rendered to an image has + // no text, so its section is a single image element pointing at the rendered page resource. + string locationRef = $"page:{page.Number}"; + string resourceKey = $"page:{page.Number}"; + string imageFileName = $"page-{page.Number}.png"; + string fileName = $"{page.Number}.html"; + string sectionHtml = $"
\"{WebUtility.HtmlEncode(locationRef)}\"
"; + File.WriteAllText(Path.Combine(sectionsDirectory, fileName), sectionHtml, Encoding.UTF8); + spine.Add(new ReadingSpineItemDto(locationRef, null, $"sections/{fileName}")); + // The resource is registered with its expected file path, but the image is rendered lazily, when the resource is + // requested, so that opening the book does not render pages the user never looks at. + resources[resourceKey] = new ReadingResourceInfoDto($"resources/{imageFileName}", "image/png"); + } + + // The table of contents is read from the document that was already opened for the pages, so the PDF is not opened twice. + tableOfContents = ReadTableOfContents(pdfDocument); + } + + // The rendered pages have no text layer, and a PDF has no embedded resources to serve beyond the rendered pages. + return new ReadingDocumentDto(Path.GetFileNameWithoutExtension(pdfPath), null, null, tableOfContents, spine, resources, HasTextContent: false); + } + + /// + /// Renders the page image identified by of the PDF stored at . + /// + /// The file system path of the PDF. + /// The resource key of the page image to render, of the form page:{n}. + /// Cancellation token that can be used to stop the execution. + /// The PNG bytes of the rendered page. + /// + /// The PDFtoImage and SkiaSharp APIs used by this method are annotated with the supported platforms of the rendering engine, so this + /// method must repeat that restriction or the CA1416 analyzer, which is a build error here, flags the call. The attributes must not + /// be removed, even though Windows, Linux and macOS are the only platforms Lumina runs on. + /// + [SupportedOSPlatform("windows")] + [SupportedOSPlatform("linux")] + [SupportedOSPlatform("macos")] + public static byte[] RenderResource(string pdfPath, string resourceKey, CancellationToken cancellationToken) + { + // The resource key must name a page of a parseable size: a key that does not start with "page:", does not carry a number, + // or names a page beyond the page cap (or below the first page) can never be a page of this document, and rejecting it here + // avoids opening the PDF at all for keys that no parse could have produced. + if (!resourceKey.StartsWith("page:", StringComparison.Ordinal) || !int.TryParse(resourceKey["page:".Length..], out int pageNumber) || pageNumber < 1 || pageNumber > MAX_PAGES) + throw new InvalidDataException($"The resource key '{resourceKey}' does not identify a PDF page."); + + // The page is validated against the actual document before any bitmap is allocated: a page number that exceeds the number of + // pages of the document, or a page whose MediaBox declares dimensions larger than what the render limits allow, would only be + // discovered by the renderer after it has already allocated a bitmap the size of the page, which a hostile PDF could make huge. + using (PdfDocument pdfDocument = PdfDocument.Open(pdfPath)) + { + if (pageNumber > pdfDocument.NumberOfPages) + throw new InvalidDataException($"The resource key '{resourceKey}' does not identify a PDF page: the PDF contains {pdfDocument.NumberOfPages} pages."); + + Page page = pdfDocument.GetPage(pageNumber); + if (page.Width > MAX_RENDER_PAGE_DIMENSION || page.Height > MAX_RENDER_PAGE_DIMENSION || page.Width * page.Height > MAX_RENDER_PAGE_AREA) + throw new InvalidDataException($"The resource key '{resourceKey}' identifies a page that is too large to render ({page.Width:0.#} by {page.Height:0.#} points)."); + } + + using (FileStream pdfStream = File.OpenRead(pdfPath)) + { + // The page is rendered at its natural size; the height follows the aspect ratio of the page. PdfPig numbers the pages + // from 1, while PDFtoImage indexes them from 0, so the zero-based index of the rendered page is one less than its 1-based number. + using (SKBitmap pageBitmap = Conversion.ToImage(pdfStream, page: new Index(pageNumber - 1), leaveOpen: true)) + { + using (SKData pageImage = pageBitmap.Encode(SKEncodedImageFormat.Png, 100)) + return pageImage.ToArray(); + } + } + } + + /// + /// Parses the PDF stored at by extracting the text layer of its pages, and returns its normalized reading document. + /// + /// The file system path of the PDF. + /// The directory into which the section files of the PDF are written. + /// Cancellation token that can be used to stop the execution. + /// The normalized reading document of the PDF, with a text layer when the PDF has one. + private static ReadingDocumentDto ParseAsText(string pdfPath, string sectionsDirectory, CancellationToken cancellationToken) + { + List spine = []; + bool hasTextContent = false; + List tableOfContents = []; + using (PdfDocument pdfDocument = PdfDocument.Open(pdfPath)) + { + foreach (Page page in pdfDocument.GetPages()) + { + cancellationToken.ThrowIfCancellationRequested(); + if (page.Number > MAX_PAGES) + break; + + // The location reference of a page is its 1-based page number (PdfPig pages are numbered from 1), which is the only stable identifier a PDF page has, and it doubles as the name of the section file. + string locationRef = $"page:{page.Number}"; + string fileName = $"{page.Number}.html"; + string pageHtml = BuildPageHtml(page); + // A page may have no text at all, in which case the HTML is only the empty section wrapper; the text-content + // detection looks at the paragraphs actually produced, because the wrapper is always present. + if (pageHtml.Contains("

")) + hasTextContent = true; + File.WriteAllText(Path.Combine(sectionsDirectory, fileName), pageHtml, Encoding.UTF8); + spine.Add(new ReadingSpineItemDto(locationRef, null, $"sections/{fileName}")); + } + + // The table of contents is read from the document that was already opened for the pages, so the PDF is not opened twice. + tableOfContents = ReadTableOfContents(pdfDocument); + } + + // The author and the cover are not extracted in this text-only iteration, and a PDF has no embedded resources to serve, so the resources dictionary is empty. + return new ReadingDocumentDto(Path.GetFileNameWithoutExtension(pdfPath), null, null, tableOfContents, spine, new Dictionary(), hasTextContent); + } + + ///

+ /// Builds the HTML content of a PDF page, wrapping its extracted text into paragraphs. + /// + /// The PDF page whose content is built. + /// The HTML content of the PDF page. + private static string BuildPageHtml(Page page) + { + // The extracted text comes from the untrusted document, so each line is HTML-encoded before it is wrapped, keeping any embedded markup inert until the host sanitizes the whole section anyway; + // the lines are wrapped in paragraphs so that the page reads like a document, instead of one unbroken wall of text. + StringBuilder stringBuilder = new(); + stringBuilder.Append("
"); + string text = page.Text ?? string.Empty; + foreach (string line in text.Replace("\r\n", "\n").Split('\n')) + { + if (string.IsNullOrWhiteSpace(line)) + continue; + stringBuilder.Append("

").Append(WebUtility.HtmlEncode(line)).Append("

"); + } + stringBuilder.Append("
"); + return stringBuilder.ToString(); + } + + /// + /// Reads the table of contents of the PDF from the bookmarks of the already open document. + /// + /// The open PDF document whose bookmarks are read. + /// The table of contents of the PDF, or an empty list when the PDF has no usable bookmarks. + private static List ReadTableOfContents(PdfDocument pdfDocument) + { + try + { + // Many PDFs have no bookmarks at all (for example a book exported from a word processor), in which case the reader simply shows no table of contents instead of failing the whole book. + if (!pdfDocument.TryGetBookmarks(out Bookmarks? bookmarks) || bookmarks is null || bookmarks.Roots.Count == 0) + return []; + + return [.. bookmarks.Roots.Select(ToTocEntry)]; + } + catch (OperationCanceledException) + { + // A cancelled parse must not silently succeed with an empty table of contents, so the cancellation is rethrown instead of + // being swallowed: the request was aborted, not the bookmarks found unreadable. + throw; + } + catch (Exception) + { + // The bookmarks of a malformed PDF are best effort, so the table of contents is skipped instead of failing the book; the pages themselves are still readable + return []; + } + } + + /// + /// Converts a bookmark of the PDF into a table of contents entry. + /// + /// The bookmark to convert. + /// The converted table of contents entry. + private static ReadingTocEntryDto ToTocEntry(BookmarkNode bookmark) + { + // Only a document bookmark has a destination page; the other bookmark kinds (external, embedded, URI) cannot be navigated inside the reader, so they yield an entry that points nowhere, + // and the client simply does not render it as navigable. + int? pageNumber = bookmark is DocumentBookmarkNode documentBookmark ? documentBookmark.PageNumber : null; + string locationRef = pageNumber is null ? string.Empty : $"page:{pageNumber.Value}"; + // The nested bookmarks of a bookmark become the children of the entry, preserving the hierarchy of the outline. + List children = [.. bookmark.Children.Select(ToTocEntry)]; + return new ReadingTocEntryDto(bookmark.Title ?? string.Empty, locationRef, children); + } +} diff --git a/plugins/Lumina.Plugins.Pdf/Core/PdfPlugin.cs b/plugins/Lumina.Plugins.Pdf/Core/PdfPlugin.cs new file mode 100644 index 00000000..2853b4bc --- /dev/null +++ b/plugins/Lumina.Plugins.Pdf/Core/PdfPlugin.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Pdf.Common.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.Pdf.Core; + +/// +/// Plugin that decodes PDF books into a normalized reading document. +/// +public sealed class PdfPlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("c2f9b8f0-5a4b-4e3d-8b2f-7e4a9c1d3e5f"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "PDF Reader"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Allows reading of PDF format books."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return []; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddPdfReader(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.Pdf/Core/PdfReader.cs b/plugins/Lumina.Plugins.Pdf/Core/PdfReader.cs new file mode 100644 index 00000000..a0494e9b --- /dev/null +++ b/plugins/Lumina.Plugins.Pdf/Core/PdfReader.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Reading; +using Lumina.Plugins.Pdf.Core.Pdf; +using System.Collections.Generic; +using System.Runtime.Versioning; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Pdf.Core; + +/// +/// Book reader for the PDF format. +/// +/// +/// See for how a PDF is decoded; this class only declares the supported format and delegates the decoding to the parser. +/// +internal sealed class PdfReader : IBookReader +{ + /// + /// Gets the file extensions supported by the reader. + /// + public IReadOnlyList SupportedExtensions => [".pdf"]; + + /// + /// Gets the media library types the reader supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.EBook, LibraryType.Book]; + + /// + /// Opens the PDF stored at , extracting its pages into , + /// and returns its normalized reading document. When the PDF is rendered as page images, the page images are not rendered + /// here: a page is rendered only when its resource is requested, so that opening a large book is instant. + /// + /// The file system path of the PDF. + /// The directory into which the pages of the PDF are extracted. + /// Whether the PDF is rendered as page images instead of extracting its text layer. This is used for scanned PDFs whose pages are only images and therefore yield no text. + /// Cancellation token that can be used to stop the execution. + /// The normalized reading document of the PDF. + public Task OpenAsync(string path, string workingDirectory, bool shouldRenderPdfAsImages, CancellationToken cancellationToken) + { + return Task.FromResult(PdfDocumentParser.Parse(path, workingDirectory, shouldRenderPdfAsImages, cancellationToken)); + } + + /// + /// Produces the resource identified by of the PDF stored at , + /// rendering the requested page to an image on demand. Only the page image whose resource is requested is rendered, + /// so that the user does not wait for every page of a large book to be rendered before seeing the first one. + /// + /// The file system path of the PDF. + /// The directory into which the pages of the PDF are extracted. + /// The opaque resource key of the resource to produce, of the form page:{n}. + /// Cancellation token that can be used to stop the execution. + /// The binary data of the rendered page image. + /// + /// The PDFtoImage and SkiaSharp APIs used by are annotated with the supported + /// platforms of the rendering engine, so this method must repeat that restriction or the CA1416 analyzer, which is a build error + /// here, flags the call. The attributes must not be removed, even though Windows, Linux and macOS are the only platforms Lumina runs on. + /// + [SupportedOSPlatform("windows")] + [SupportedOSPlatform("linux")] + [SupportedOSPlatform("macos")] + public Task GetResourceAsync(string path, string workingDirectory, string resourceKey, CancellationToken cancellationToken) + { + byte[] data = PdfDocumentParser.RenderResource(path, resourceKey, cancellationToken); + return Task.FromResult(data); + } +} diff --git a/plugins/Lumina.Plugins.Pdf/Lumina.Plugins.Pdf.csproj b/plugins/Lumina.Plugins.Pdf/Lumina.Plugins.Pdf.csproj new file mode 100644 index 00000000..55750f63 --- /dev/null +++ b/plugins/Lumina.Plugins.Pdf/Lumina.Plugins.Pdf.csproj @@ -0,0 +1,50 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + + + + + + + + + + + + <_CurrentRidNatives Include="$(OutDir)runtimes\$(NETCoreSdkRuntimeIdentifier)\native\*" /> + + + + + + + + + false + runtime + + + + + + + + + + + + diff --git a/plugins/Lumina.Plugins.Pdf/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Pdf/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..fdfba7b5 --- /dev/null +++ b/plugins/Lumina.Plugins.Pdf/Properties/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.Fixtures")] diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryBookReaderConfigurationEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryBookReaderConfigurationEntity.cs new file mode 100644 index 00000000..a4ab4fc6 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryBookReaderConfigurationEntity.cs @@ -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; + +/// +/// Repository entity for the configuration of a book reader of a media library. +/// +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public class LibraryBookReaderConfigurationEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets or sets the Id of the configuration. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the media library the configuration belongs to. + /// + public required Guid LibraryId { get; set; } + + /// + /// Gets or sets the Id of the plugin providing the book reader. + /// + public required Guid PluginId { get; set; } + + /// + /// Gets or sets whether the book reader is enabled for the media library. + /// + public required bool IsEnabled { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs index 5e8de0bf..718dc8cb 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs @@ -47,6 +47,19 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity /// public bool ShouldAggregateMetadataWhenMissing { get; set; } + /// + /// 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. + /// + public bool ShouldRenderPdfAsImages { get; set; } + + /// + /// 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. + /// + public bool ShouldPreserveBookStyles { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryBookReaderConfigurationRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryBookReaderConfigurationRepository.cs new file mode 100644 index 00000000..0f0f3c55 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryBookReaderConfigurationRepository.cs @@ -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; + +/// +/// Interface for the repository for the book reader configurations of media libraries. +/// +public interface ILibraryBookReaderConfigurationRepository : IRepository +{ + /// + /// Gets all the book reader configurations of the media library identified by . + /// + /// The Id of the media library whose book reader configurations are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the book reader configuration of the media library identified by for the plugin identified by . + /// + /// The Id of the media library whose book reader configuration is retrieved. + /// The Id of the plugin whose book reader configuration is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the , or an error. + Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken); + + /// + /// Inserts the provided into the storage medium, or updates it when it already exists. + /// + /// The book reader configuration to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> UpsertAsync(LibraryBookReaderConfigurationEntity configuration, CancellationToken cancellationToken); + + /// + /// Deletes all the book reader configurations of the media library identified by . + /// + /// The Id of the media library whose book reader configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Deletes all the book reader configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose book reader configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken); + + /// + /// Deletes the book reader configurations of the media library identified by that reference + /// one of the plugins identified by . + /// + /// The Id of the media library whose book reader configurations are deleted. + /// The Ids of the plugins whose configurations of the media library are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable pluginIds, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index b314bfab..f748d5dd 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -82,6 +82,11 @@ public interface IUnitOfWork /// IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get; } + /// + /// Gets the library book reader configuration repository. + /// + ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get; } + /// /// Gets the plugin repository. /// diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index b8f5bc7d..306cfeb9 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -12,13 +12,13 @@ using System.Reflection; namespace Lumina.Application.Common.DependencyInjection; /// -/// Contains all services of the Application layer. +/// Utility class for registering the services of the Application layer into the Dependency Injection container. /// [ExcludeFromCodeCoverage] public static class ApplicationLayerServices { /// - /// Registers the services of the Application layer into the dependency injection container. + /// Registers the services of the Application layer into the Dependency Injection container. /// /// The service collection to add the services to. /// The updated . @@ -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); diff --git a/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs b/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs index 6f81bcbd..3f911baa 100644 --- a/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs +++ b/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs @@ -58,4 +58,38 @@ public interface IMediaLibraryProviderConfigurationStore /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken); + + /// + /// 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 . + /// + /// The Id of the media library whose book reader configurations are ensured. + /// The type of the media library, used to determine the plugins whose book readers apply. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); + + /// + /// Replaces the book reader configurations of the media library identified by so that they match the plugins supporting the provided library type. + /// + /// The Id of the media library whose book reader configurations are reconciled. + /// The type of the media library, used to determine the plugins whose book readers apply. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); + + /// + /// Deletes all the book reader configurations of the media library identified by . + /// + /// The Id of the media library whose book reader configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Deletes all the book reader configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose book reader configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/Infrastructure/Reading/IBookReaderEnablementCache.cs b/src/Lumina.Application/Common/Infrastructure/Reading/IBookReaderEnablementCache.cs new file mode 100644 index 00000000..b4025a78 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Reading/IBookReaderEnablementCache.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Reading; + +/// +/// 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. +/// +public interface IBookReaderEnablementCache +{ + /// + /// Gets the cached enablement of the book reader of the plugin identified by for the media library identified by . + /// + /// The Id of the media library whose book reader enablement is retrieved. + /// The Id of the plugin providing the book reader. + /// The cached enablement, or when it is not cached yet. + bool? Get(Guid libraryId, Guid pluginId); + + /// + /// Caches the enablement of the book reader of the plugin identified by for the media library identified by . + /// + /// The Id of the media library whose book reader enablement is cached. + /// The Id of the plugin providing the book reader. + /// Whether the book reader is enabled for the media library. + void Set(Guid libraryId, Guid pluginId, bool isEnabled); + + /// + /// Removes the cached enablement of the book reader of the plugin identified by for the media library identified by . + /// + /// The Id of the media library whose book reader enablement is invalidated. + /// The Id of the plugin providing the book reader. + void Invalidate(Guid libraryId, Guid pluginId); + + /// + /// Removes every cached enablement of the media library identified by . + /// + /// The Id of the media library whose book reader enablements are invalidated. + void InvalidateLibrary(Guid libraryId); + + /// + /// Removes every cached enablement of the plugin identified by . + /// + /// The Id of the plugin whose book reader enablements are invalidated. + void InvalidatePlugin(Guid pluginId); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Reading/IBookReaderRegistry.cs b/src/Lumina.Application/Common/Infrastructure/Reading/IBookReaderRegistry.cs new file mode 100644 index 00000000..b950c4a6 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Reading/IBookReaderRegistry.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Reading; + +/// +/// Registry of the book readers provided by the loaded plugins. +/// +public interface IBookReaderRegistry +{ + /// + /// Gets the file extensions supported by the book readers of each loaded plugin, keyed by the Id of the plugin. + /// + /// The supported extensions of the book readers, keyed by the Id of the plugin providing them. + IReadOnlyDictionary> GetSupportedExtensionsByPluginId(); +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs index 37aed932..0db3fb9f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs @@ -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 diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs index 1a7ca813..8635f179 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs @@ -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 diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs index a3b3255a..a1f6b92f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs @@ -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 diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMapping.cs new file mode 100644 index 00000000..4737e11e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetReadingAvailabilityRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetReadingAvailabilityQuery ToQuery(this GetReadingAvailabilityRequest request) + { + return new GetReadingAvailabilityQuery( + request.BookId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMapping.cs new file mode 100644 index 00000000..79e512c9 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetReadingManifestRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetReadingManifestQuery ToQuery(this GetReadingManifestRequest request) + { + return new GetReadingManifestQuery( + request.BookId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMapping.cs new file mode 100644 index 00000000..68b5927c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetReadingResourceRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetReadingResourceQuery ToQuery(this GetReadingResourceRequest request) + { + return new GetReadingResourceQuery( + request.BookId, + request.ResourceKey + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMapping.cs new file mode 100644 index 00000000..6ed66d56 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetReadingSectionRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetReadingSectionQuery ToQuery(this GetReadingSectionRequest request) + { + return new GetReadingSectionQuery( + request.BookId, + request.LocationRef + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/ReadingDocumentDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/ReadingDocumentDtoMapping.cs new file mode 100644 index 00000000..5a2fe2b5 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/ReadingDocumentDtoMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class ReadingDocumentDtoMapping +{ + /// + /// Converts to . + /// + /// The reading document to be converted. + /// The converted reading manifest response. + 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 + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/ReadingTocEntryDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/ReadingTocEntryDtoMapping.cs new file mode 100644 index 00000000..04dbddd2 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/ReadingTocEntryDtoMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class ReadingTocEntryDtoMapping +{ + /// + /// Converts to . + /// + /// The table of contents entry to be converted. + /// The converted table of contents entry response. + public static ReadingTocEntryResponse ToResponse(this ReadingTocEntryDto entry) + { + return new ReadingTocEntryResponse( + entry.Label, + entry.LocationRef, + [.. entry.Children.Select(child => child.ToResponse())] + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryBookReadersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryBookReadersRequestMapping.cs new file mode 100644 index 00000000..39c06d81 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryBookReadersRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryBookReadersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryBookReadersQuery ToQuery(this GetLibraryBookReadersRequest request) + { + return new GetLibraryBookReadersQuery( + request.LibraryId + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/LibraryBookReaderConfigurationEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/LibraryBookReaderConfigurationEntityMapping.cs new file mode 100644 index 00000000..5ea10108 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/LibraryBookReaderConfigurationEntityMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class LibraryBookReaderConfigurationEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The display name of the book reader. + /// The file extensions supported by the book reader. + /// The converted response. + public static LibraryBookReaderResponse ToResponse(this LibraryBookReaderConfigurationEntity configuration, string readerName, IReadOnlyList supportedExtensions) + { + return new LibraryBookReaderResponse( + configuration.PluginId, + readerName, + supportedExtensions, + configuration.IsEnabled + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs new file mode 100644 index 00000000..727601ca --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class SetLibraryBookReaderEnabledRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static SetLibraryBookReaderEnabledCommand ToCommand(this SetLibraryBookReaderEnabledRequest request) + { + return new SetLibraryBookReaderEnabledCommand( + request.LibraryId, + request.PluginId, + request.IsEnabled + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs index aff25a7d..e4c9c955 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs @@ -22,7 +22,9 @@ public static class UpdateUserSettingsRequestMapping request.ItemsPerPage, request.ShouldIgnoreThePrefixForAlphaPicker, request.IsThemeCachingEnabled, - request.ShouldAggregateMetadataWhenMissing + request.ShouldAggregateMetadataWhenMissing, + request.ShouldRenderPdfAsImages, + request.ShouldPreserveBookStyles ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs index b53990fd..f556846c 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs @@ -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 ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs index cde37e56..01c0e99a 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs @@ -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 ); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs index 84050f4e..551cd269 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs @@ -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; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs similarity index 98% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs index 7967bf82..8db5934c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs @@ -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; /// /// Interface for the service for storing the artwork of a book into the internal media directory and serving its relative path. diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommand.cs similarity index 98% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommand.cs index 0d0b29c9..d83688e4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommand.cs @@ -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; /// /// Command for adding a book. diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs similarity index 99% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index 82be9a0d..ea190340 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -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; /// /// Handler for the command to add a book. diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs similarity index 99% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index 0f7a760f..bcad4b8a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -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; /// /// Validates the needed validation rules for . diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs similarity index 96% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs index 5aef1242..480017ba 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs @@ -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; /// /// Query for getting all the books of a media library. diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs similarity index 99% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 44e25dfc..c75ec08b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -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; /// /// Handler for the query to get all books. diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs similarity index 95% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs index 576e755d..d091269c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs @@ -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; /// /// Validates the needed validation rules for . diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs similarity index 95% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs index 0aec829f..87dd8ef0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs @@ -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; /// /// Query for getting the lightweight details of all the books of a media library. diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs similarity index 98% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs index f7c2ecf5..79c58486 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs @@ -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; /// /// Handler for the query to get the lightweight details of all books. diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs similarity index 97% rename from src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs rename to src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs index 6c8fb14b..ba7c48eb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs @@ -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; /// /// Validates the needed validation rules for . diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQuery.cs new file mode 100644 index 00000000..94ab3754 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQuery.cs @@ -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; + +/// +/// Query for checking the reading availability of a book. +/// +/// The Id of the book whose reading availability is checked. +public record GetReadingAvailabilityQuery( + Guid BookId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandler.cs new file mode 100644 index 00000000..b1d8b9c4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandler.cs @@ -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; + +/// +/// Handler for the query to check the reading availability of a book. +/// +public class GetReadingAvailabilityQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IBookReadingService _bookReadingService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for reading books using the book reader plugins. + /// Injected validator for application validation rules. + public GetReadingAvailabilityQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _bookReadingService = bookReadingService; + _validator = validator; + } + + /// + /// Handles the query to check the reading availability of a book. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the reading availability of the book, or an error. + /// + public async Task> HandleAsync(GetReadingAvailabilityQuery query, CancellationToken cancellationToken) + { + List 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 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( + userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result 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); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidator.cs new file mode 100644 index 00000000..8207145e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetReadingAvailabilityQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingAvailabilityQueryValidator() + { + RuleFor(query => query.BookId) + .NotEmpty() + .WithError(Errors.Reading.BookIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQuery.cs new file mode 100644 index 00000000..ebae8e5b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQuery.cs @@ -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; + +/// +/// Query for getting the reading manifest of a book. +/// +/// The Id of the book whose reading manifest is retrieved. +public record GetReadingManifestQuery( + Guid BookId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandler.cs new file mode 100644 index 00000000..302c74f3 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get the reading manifest of a book. +/// +public class GetReadingManifestQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IBookReadingService _bookReadingService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for reading books using the book reader plugins. + /// Injected validator for application validation rules. + public GetReadingManifestQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _bookReadingService = bookReadingService; + _validator = validator; + } + + /// + /// Handles the query to get the reading manifest of a book. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the reading manifest of the book, or an error. + /// + public async Task> HandleAsync(GetReadingManifestQuery query, CancellationToken cancellationToken) + { + List 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 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( + userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result 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 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); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidator.cs new file mode 100644 index 00000000..27e12875 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetReadingManifestQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingManifestQueryValidator() + { + RuleFor(query => query.BookId) + .NotEmpty() + .WithError(Errors.Reading.BookIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQuery.cs new file mode 100644 index 00000000..1de80056 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQuery.cs @@ -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; + +/// +/// Query for getting a resource of a book, for reading. +/// +/// The Id of the book whose resource is retrieved. +/// The opaque resource key of the resource. +public record GetReadingResourceQuery( + Guid BookId, + string ResourceKey +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandler.cs new file mode 100644 index 00000000..83f9c772 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get a resource of a book, for reading. +/// +public class GetReadingResourceQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IBookReadingService _bookReadingService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for reading books using the book reader plugins. + /// Injected validator for application validation rules. + public GetReadingResourceQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _bookReadingService = bookReadingService; + _validator = validator; + } + + /// + /// Handles the query to get a resource of a book, for reading. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the resource of the book, or an error. + /// + public async Task> HandleAsync(GetReadingResourceQuery query, CancellationToken cancellationToken) + { + List 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 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(userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result 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 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); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryValidator.cs new file mode 100644 index 00000000..20c07c15 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetReadingResourceQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingResourceQueryValidator() + { + RuleFor(query => query.BookId) + .NotEmpty() + .WithError(Errors.Reading.BookIdCannotBeEmpty); + + RuleFor(query => query.ResourceKey) + .NotEmpty() + .WithError(Errors.Reading.ResourceKeyCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQuery.cs new file mode 100644 index 00000000..62b4e2b9 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQuery.cs @@ -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; + +/// +/// Query for getting the content of a reading section of a book. +/// +/// The Id of the book whose reading section is retrieved. +/// The opaque location reference of the reading section. +public record GetReadingSectionQuery( + Guid BookId, + string LocationRef +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandler.cs new file mode 100644 index 00000000..fb1ca0c5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get the content of a reading section of a book. +/// +public class GetReadingSectionQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IBookReadingService _bookReadingService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for reading books using the book reader plugins. + /// Injected validator for application validation rules. + public GetReadingSectionQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _bookReadingService = bookReadingService; + _validator = validator; + } + + /// + /// Handles the query to get the content of a reading section of a book. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the content of the reading section, or an error. + /// + public async Task> HandleAsync(GetReadingSectionQuery query, CancellationToken cancellationToken) + { + List 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 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( + userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result 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 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); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryValidator.cs new file mode 100644 index 00000000..0d7dab90 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetReadingSectionQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingSectionQueryValidator() + { + RuleFor(query => query.BookId) + .NotEmpty() + .WithError(Errors.Reading.BookIdCannotBeEmpty); + + RuleFor(query => query.LocationRef) + .NotEmpty() + .WithError(Errors.Reading.LocationRefCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/IBookReadingService.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/IBookReadingService.cs new file mode 100644 index 00000000..a47d1748 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/IBookReadingService.cs @@ -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; + +/// +/// Interface for the service for reading books, using the book reader plugins configured for their media library. +/// +public interface IBookReadingService +{ + /// + /// Gets the reading manifest of the book stored at . + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Cancellation token that can be used to stop the execution. + /// An containing either the reading manifest of the book, or an error. + Task> GetManifestAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, bool shouldRenderPdfAsImages, CancellationToken cancellationToken); + + /// + /// Gets the content of the reading section identified by of the book stored at . + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// The opaque location reference of the reading section. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Whether the styles of the section content are preserved when it is sanitized, or stripped. + /// Cancellation token that can be used to stop the execution. + /// An containing either the content of the reading section, or an error. + Task> GetSectionAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string locationRef, bool shouldRenderPdfAsImages, bool shouldPreserveStyles, CancellationToken cancellationToken); + + /// + /// Gets the resource identified by of the book stored at . + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// The opaque resource key of the resource. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Cancellation token that can be used to stop the execution. + /// An containing either the resource, or an error. + Task> GetResourceAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string resourceKey, bool shouldRenderPdfAsImages, CancellationToken cancellationToken); + + /// + /// Checks whether the book stored at 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. + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// Cancellation token that can be used to stop the execution. + /// An containing either the reading availability of the book, or an error. + Task> GetAvailabilityAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs new file mode 100644 index 00000000..a40b4e93 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; + +/// +/// Command for enabling or disabling a book reader for a media library. +/// +/// The Id of the media library whose book reader is enabled or disabled. +/// The unique identifier of the plugin providing the book reader. +/// Whether the book reader should be enabled for the media library. +public record SetLibraryBookReaderEnabledCommand( + Guid LibraryId, + Guid PluginId, + bool IsEnabled +) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs new file mode 100644 index 00000000..aa8c8749 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs @@ -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; + +/// +/// Handler for the command to enable or disable a book reader for a media library. +/// +public class SetLibraryBookReaderEnabledCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IBookReaderEnablementCache _enablementCache; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected cache of whether the book reader of a plugin is enabled for a media library. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public SetLibraryBookReaderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderEnablementCache enablementCache, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _enablementCache = enablementCache; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to enable or disable a book reader for a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(SetLibraryBookReaderEnabledCommand command, CancellationToken cancellationToken) + { + List 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(userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result 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 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; + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs new file mode 100644 index 00000000..1178b5f9 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class SetLibraryBookReaderEnabledCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public SetLibraryBookReaderEnabledCommandValidator() + { + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + + RuleFor(command => command.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQuery.cs new file mode 100644 index 00000000..c2800541 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQuery.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders; + +/// +/// Query for getting the book readers configured for a media library. +/// +/// The Id of the media library whose book readers are retrieved. +public record GetLibraryBookReadersQuery( + Guid LibraryId +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandler.cs new file mode 100644 index 00000000..d379ee7f --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get the book readers configured for a media library. +/// +public class GetLibraryBookReadersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IBookReaderRegistry _bookReaderRegistry; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected registry of the book readers provided by the loaded plugins. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryBookReadersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderRegistry bookReaderRegistry, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _bookReaderRegistry = bookReaderRegistry; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the book readers configured for a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryBookReadersQuery query, CancellationToken cancellationToken) + { + List 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( + userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> 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> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + IReadOnlyDictionary> 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(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryValidator.cs new file mode 100644 index 00000000..b47734a3 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryBookReadersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryBookReadersQueryValidator() + { + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs index e29088bf..44a547f4 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs @@ -12,10 +12,14 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. +/// Whether PDF books are rendered as page images for the user, or not. +/// Whether the styles of the book content are preserved when it is rendered for the user, or not. public record UpdateUserSettingsCommand( bool IsPaginationEnabled, int ItemsPerPage, bool ShouldIgnoreThePrefixForAlphaPicker, bool IsThemeCachingEnabled, - bool ShouldAggregateMetadataWhenMissing + bool ShouldAggregateMetadataWhenMissing, + bool ShouldRenderPdfAsImages, + bool ShouldPreserveBookStyles ) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs index 9af3a222..8b7bf775 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -53,27 +53,29 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler 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 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 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 toDomainEntityResult = getSettingsResult.Value.ToDomainEntity(); if (toDomainEntityResult.IsFailure) return toDomainEntityResult.Errors; @@ -93,7 +95,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler +/// Data transfer object for the normalized document model of a book, produced by a reader plugin. +/// +/// The title of the book. +/// The author of the book, if known. +/// The resource key of the cover image of the book, if applicable. +/// The hierarchical table of contents of the book. +/// The ordered spine of the reading sections of the book. +/// The resources of the book, keyed by their resource key. +/// Whether the book has extractable text content. A scanned book, whose pages are only images, has no text content. +[DebuggerDisplay("Title: {Title}")] +public sealed record ReadingDocumentDto( + string Title, + string? Author, + string? CoverResourceKey, + IReadOnlyList TableOfContents, + IReadOnlyList Spine, + IReadOnlyDictionary Resources, + bool HasTextContent +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceDataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceDataDto.cs new file mode 100644 index 00000000..d26bd727 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceDataDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; + +/// +/// Data transfer object for the binary data of a reading resource. +/// +/// The binary data of the resource. +/// The MIME type of the resource. +[DebuggerDisplay("MimeType: {MimeType}")] +public sealed record ReadingResourceDataDto( + byte[] Data, + string MimeType +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceInfoDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceInfoDto.cs new file mode 100644 index 00000000..3d819cc3 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceInfoDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; + +/// +/// Data transfer object for the file information of a resource of a reading document. +/// +/// The path of the resource file, relative to the extraction directory of the book. +/// The MIME type of the resource. +[DebuggerDisplay("RelativeFilePath: {RelativeFilePath}")] +public sealed record ReadingResourceInfoDto( + string RelativeFilePath, + string MimeType +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSectionDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSectionDto.cs new file mode 100644 index 00000000..e90c65af --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSectionDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; + +/// +/// Data transfer object for the content of a reading section. +/// +/// The opaque location reference of the reading section. +/// The title of the reading section, if known. +/// The sanitized HTML content of the reading section, ready to be rendered by the client. +[DebuggerDisplay("LocationRef: {LocationRef}")] +public sealed record ReadingSectionDto( + string LocationRef, + string? Title, + string ContentHtml +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSpineItemDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSpineItemDto.cs new file mode 100644 index 00000000..0f1f0f9c --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSpineItemDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; + +/// +/// Data transfer object for an item of the spine of a reading document. +/// +/// The opaque location reference of the reading section. +/// The title of the reading section, if known. +/// The path of the section content file, relative to the extraction directory of the book. +[DebuggerDisplay("LocationRef: {LocationRef}")] +public sealed record ReadingSpineItemDto( + string LocationRef, + string? Title, + string RelativeSectionFilePath +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingTocEntryDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingTocEntryDto.cs new file mode 100644 index 00000000..6301f6d2 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingTocEntryDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; + +/// +/// Data transfer object for an entry of the table of contents of a reading document. +/// +/// The label of the table of contents entry. +/// The opaque location reference of the reading section the entry points to. +/// The child entries of the table of contents entry. +[DebuggerDisplay("Label: {Label}")] +public sealed record ReadingTocEntryDto( + string Label, + string LocationRef, + IReadOnlyList Children +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequest.cs new file mode 100644 index 00000000..9dff87d4 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents a request to check the reading availability of a book. +/// +/// The Id of the book whose reading availability is checked. Required. +[DebuggerDisplay("BookId: {BookId}")] +public sealed record GetReadingAvailabilityRequest( + Guid BookId +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequest.cs new file mode 100644 index 00000000..abcf6fd3 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents a request to get the reading manifest of a book. +/// +/// The Id of the book whose reading manifest is retrieved. Required. +[DebuggerDisplay("BookId: {BookId}")] +public sealed record GetReadingManifestRequest( + Guid BookId +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequest.cs new file mode 100644 index 00000000..6d82017d --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents a request to get a resource of a book, for reading. +/// +/// The Id of the book whose resource is retrieved. Required. +/// The opaque resource key of the resource. Required. +[DebuggerDisplay("BookId: {BookId}, ResourceKey: {ResourceKey}")] +public sealed record GetReadingResourceRequest( + Guid BookId, + string ResourceKey +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequest.cs new file mode 100644 index 00000000..aef859de --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents a request to get the content of a reading section of a book. +/// +/// The Id of the book whose reading section is retrieved. Required. +/// The opaque location reference of the reading section. Required. +[DebuggerDisplay("BookId: {BookId}, LocationRef: {LocationRef}")] +public sealed record GetReadingSectionRequest( + Guid BookId, + string LocationRef +); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryBookReadersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryBookReadersRequest.cs new file mode 100644 index 00000000..b3d9d026 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryBookReadersRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the book readers configured for a media library. +/// +/// The Id of the media library whose book readers are retrieved. Required. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public sealed record GetLibraryBookReadersRequest( + Guid LibraryId +); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs new file mode 100644 index 00000000..3392ae17 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to enable or disable a book reader for a media library. +/// +/// The Id of the media library whose book reader is enabled or disabled. Required. +/// The unique identifier of the plugin providing the book reader. Required. +/// Whether the book reader should be enabled for the media library. Required. +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public sealed record SetLibraryBookReaderEnabledRequest( + Guid LibraryId, + Guid PluginId, + bool IsEnabled +); diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs index b37216ac..34c12869 100644 --- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs @@ -12,11 +12,15 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings; /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required. /// Whether the theme data served to this user is cached, or not. Required. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required. +/// Whether PDF books are rendered as page images for the user, or not. Required. +/// Whether the styles of the book content are preserved when it is rendered for the user, or not. Required. [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 ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingAvailabilityResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingAvailabilityResponse.cs new file mode 100644 index 00000000..dc3210e0 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingAvailabilityResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents the reading availability of a book. +/// +/// The Id of the book whose reading availability is reported. +/// The Id of the media library the book belongs to. +/// Whether the book can be opened for reading. +/// The code of the error preventing the book from being read, when it cannot be read. Can be when the book is available. +[DebuggerDisplay("BookId: {BookId}, IsAvailable: {IsAvailable}")] +public sealed record ReadingAvailabilityResponse( + Guid BookId, + Guid LibraryId, + bool IsAvailable, + string? ErrorCode +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingManifestResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingManifestResponse.cs new file mode 100644 index 00000000..6e6cb72a --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingManifestResponse.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents the reading manifest of a book, containing everything the client needs to render the reader. +/// +/// The title of the book. +/// The author of the book, if known. +/// The resource key of the cover image of the book, if applicable. +/// The hierarchical table of contents of the book. +/// The ordered spine of the reading sections of the book. +/// The resource keys of the resources of the book. +/// Whether the book has extractable text content. A scanned book, whose pages are only images, has no text content. +[DebuggerDisplay("Title: {Title}")] +public sealed record ReadingManifestResponse( + string Title, + string? Author, + string? CoverResourceKey, + IReadOnlyList TableOfContents, + IReadOnlyList Spine, + IReadOnlyList ResourceKeys, + bool HasTextContent +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingSpineItemResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingSpineItemResponse.cs new file mode 100644 index 00000000..e7fb54bd --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingSpineItemResponse.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents an item of the spine of the reading manifest of a book. +/// +/// The opaque location reference of the reading section. +/// The title of the reading section, if known. +[DebuggerDisplay("LocationRef: {LocationRef}")] +public sealed record ReadingSpineItemResponse( + string LocationRef, + string? Title +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingTocEntryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingTocEntryResponse.cs new file mode 100644 index 00000000..a2254eb8 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingTocEntryResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents an entry of the table of contents of the reading manifest of a book. +/// +/// The label of the table of contents entry. +/// The opaque location reference of the reading section the entry points to. +/// The child entries of the table of contents entry. +[DebuggerDisplay("Label: {Label}")] +public sealed record ReadingTocEntryResponse( + string Label, + string LocationRef, + IReadOnlyList Children +); diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs new file mode 100644 index 00000000..bb095299 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Plugins; + +/// +/// Represents a book reader configured for a media library. +/// +/// The unique identifier of the plugin providing the book reader. +/// The display name of the book reader. +/// The file extensions supported by the book reader. +/// Whether the book reader is enabled for the media library. +[DebuggerDisplay("Name: {Name}")] +public sealed record LibraryBookReaderResponse( + Guid PluginId, + string Name, + IReadOnlyList SupportedExtensions, + bool IsEnabled +); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs index 3f5c59e3..0db9b39e 100644 --- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs @@ -14,6 +14,8 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings; /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. +/// Whether PDF books are rendered as page images for the user, or not. +/// Whether the styles of the book content are preserved when it is rendered for the user, or not. [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 ); diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryBookReaderConfigurationConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryBookReaderConfigurationConfiguration.cs new file mode 100644 index 00000000..81a5b821 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryBookReaderConfigurationConfiguration.cs @@ -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; + +/// +/// Configures the entity mapping for the entity. +/// +public class LibraryBookReaderConfigurationConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder 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(); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs index 84a4f221..3e88f89f 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs @@ -50,6 +50,14 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration settings.ShouldRenderPdfAsImages) + .IsRequired() + .HasColumnOrder(11); + + builder.Property(settings => settings.ShouldPreserveBookStyles) + .IsRequired() + .HasColumnOrder(12); + builder.Property(settings => settings.IsThemeCachingEnabled) .IsRequired() .HasColumnOrder(9); diff --git a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs index ea604dbf..8581aeaa 100644 --- a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs +++ b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs @@ -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; /// -/// Contains all services of the DataAccess layer. +/// Utility class for registering the services of the Data Access layer into the Dependency Injection container.. /// [ExcludeFromCodeCoverage] public static class DataAccessLayerServices { /// - /// 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. /// /// The service collection to add the services to. /// The updated . diff --git a/src/Lumina.DataAccess/Common/Migrations/20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings.Designer.cs new file mode 100644 index 00000000..86ec543b --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings.Designer.cs @@ -0,0 +1,1615 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings")] + partial class AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("RoleCategory") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId"); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookContributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookArtwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("BookArtwork"); + + b.Navigation("BookContributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings.cs b/src/Lumina.DataAccess/Common/Migrations/20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings.cs new file mode 100644 index 00000000..4fcf0797 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260901062343_AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings.cs @@ -0,0 +1,70 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsLibraryBookReaderConfigurationsAndShouldRenderPdfAsImagesToUserSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ShouldRenderPdfAsImages", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 11); + + migrationBuilder.AddColumn( + name: "ShouldPreserveBookStyles", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 12); + + migrationBuilder.CreateTable( + name: "LibraryBookReaderConfigurations", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + PluginId = table.Column(type: "TEXT", nullable: false), + IsEnabled = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(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); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "LibraryBookReaderConfigurations"); + + migrationBuilder.DropColumn( + name: "ShouldRenderPdfAsImages", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "ShouldPreserveBookStyles", + table: "UserSettings"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 6d6090c1..746a9146 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("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("Id") @@ -1215,6 +1257,14 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(4); + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + b.Property("UpdatedBy") .HasColumnType("TEXT") .HasColumnOrder(8); diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryBookReaderConfigurationRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryBookReaderConfigurationRepository.cs new file mode 100644 index 00000000..40b03a00 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryBookReaderConfigurationRepository.cs @@ -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; + +/// +/// Repository for the book reader configurations of media libraries. +/// +internal sealed class LibraryBookReaderConfigurationRepository : ILibraryBookReaderConfigurationRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public LibraryBookReaderConfigurationRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets all the book reader configurations of the media library identified by . + /// + /// The Id of the media library whose book reader configurations are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryBookReaderConfigurations + .Where(configuration => configuration.LibraryId == libraryId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the book reader configuration of the media library identified by for the plugin identified by . + /// + /// The Id of the media library whose book reader configuration is retrieved. + /// The Id of the plugin whose book reader configuration is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the , or an error. + public async Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryBookReaderConfigurations + .FirstOrDefaultAsync(configuration => configuration.LibraryId == libraryId && configuration.PluginId == pluginId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Inserts a book reader configuration into the storage medium, or updates it when it already exists. + /// + /// The book reader configuration to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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; + } + + /// + /// Deletes all the book reader configurations of the media library identified by . + /// + /// The Id of the media library whose book reader configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + List configurations = await _luminaDbContext.LibraryBookReaderConfigurations + .Where(configuration => configuration.LibraryId == libraryId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (configurations.Count > 0) + _luminaDbContext.LibraryBookReaderConfigurations.RemoveRange(configurations); + return Result.Deleted; + } + + /// + /// Deletes all the book reader configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose book reader configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken) + { + List configurations = await _luminaDbContext.LibraryBookReaderConfigurations + .Where(configuration => configuration.PluginId == pluginId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (configurations.Count > 0) + _luminaDbContext.LibraryBookReaderConfigurations.RemoveRange(configurations); + return Result.Deleted; + } + + /// + /// Deletes the book reader configurations of the media library identified by that reference + /// one of the plugins identified by . + /// + /// The Id of the media library whose book reader configurations are deleted. + /// The Ids of the plugins whose configurations of the media library are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable pluginIds, CancellationToken cancellationToken) + { + List pluginIdList = [.. pluginIds]; + List 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; + } +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 066b02a5..46c62e07 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -35,6 +35,7 @@ public class LuminaDbContext : DbContext public virtual DbSet Plugins { get; set; } = null!; public virtual DbSet LibraryMetadataProviderConfigurations { get; set; } = null!; public virtual DbSet LibraryArtworkProviderConfigurations { get; set; } = null!; + public virtual DbSet LibraryBookReaderConfigurations { get; set; } = null!; public virtual DbSet Themes { get; set; } = null!; public virtual DbSet MediaContributors { get; set; } = null!; public virtual DbSet BookContributors { get; set; } = null!; diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index 48274881..b0260bff 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -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 } } + /// + /// Gets the library book reader configuration repository. + /// + public ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository + { + get + { + _libraryBookReaderConfigurationRepository ??= new LibraryBookReaderConfigurationRepository(_luminaDbContext); + return _libraryBookReaderConfigurationRepository; + } + } + /// /// Gets the plugin repository. /// diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index a12a72a1..b7ce03d8 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -16,13 +16,13 @@ using System.IO.Abstractions; namespace Lumina.Domain.Common.DependencyInjection; /// -/// Contains all services of the Domain layer. +/// Utility class for registering the services of the Domain layer into the Dependency Injection container. /// [ExcludeFromCodeCoverage] public static class DomainLayerServices { /// - /// Registers the services of the Domain layer into the dependency injection container. + /// Registers the services of the Domain layer into the Dependency Injection container. /// /// The service collection to add the services to. /// The updated . diff --git a/src/Lumina.Domain/Common/Errors/Errors.Reading.cs b/src/Lumina.Domain/Common/Errors/Errors.Reading.cs new file mode 100644 index 00000000..271bfe9d --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Reading.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Domain reading related error types. +/// +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)); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs index b463dd44..067f3f0a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs @@ -20,6 +20,8 @@ public class UserSettings : AggregateRoot 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; /// /// Gets the object representing the unique identifier of the user that owns these settings. @@ -51,6 +53,19 @@ public class UserSettings : AggregateRoot /// public bool ShouldAggregateMetadataWhenMissing { get; private set; } + /// + /// 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. + /// + public bool ShouldRenderPdfAsImages { get; private set; } + + /// + /// 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. + /// + public bool ShouldPreserveBookStyles { get; private set; } + /// /// Initializes a new instance of the class. /// @@ -61,6 +76,8 @@ public class UserSettings : AggregateRoot /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// Whether PDF books are rendered as page images for the user, or not. + /// Whether the styles of the book content are preserved when it is rendered for the user, or not. private UserSettings( UserSettingsId id, UserId userId, @@ -68,7 +85,9 @@ public class UserSettings : AggregateRoot 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 ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; IsThemeCachingEnabled = isThemeCachingEnabled; ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing; + ShouldRenderPdfAsImages = shouldRenderPdfAsImages; + ShouldPreserveBookStyles = shouldPreserveBookStyles; } /// @@ -86,7 +107,16 @@ public class UserSettings : AggregateRoot /// public static Result 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 + ); } /// @@ -98,7 +128,16 @@ public class UserSettings : AggregateRoot /// public static Result 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 + ); } /// @@ -110,6 +149,8 @@ public class UserSettings : AggregateRoot /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// Whether PDF books are rendered as page images for the user, or not. + /// Whether the styles of the book content are preserved when it is rendered for the user, or not. /// /// An containing either a successfully created , or an error message. /// @@ -119,7 +160,9 @@ public class UserSettings : AggregateRoot 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 itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, - shouldAggregateMetadataWhenMissing); + shouldAggregateMetadataWhenMissing, + shouldRenderPdfAsImages, + shouldPreserveBookStyles); } /// @@ -144,6 +189,8 @@ public class UserSettings : AggregateRoot /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// Whether PDF books are rendered as page images for the user, or not. + /// Whether the styles of the book content are preserved when it is rendered for the user, or not. /// /// An containing either a successfully created , or an error message. /// @@ -154,12 +201,14 @@ public class UserSettings : AggregateRoot 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); } /// @@ -170,13 +219,17 @@ public class UserSettings : AggregateRoot /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// Whether PDF books are rendered as page images for the user, or not. + /// Whether the styles of the book content are preserved when it is rendered for the user, or not. /// An representing either a successful update, or an error. public Result 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 ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; IsThemeCachingEnabled = isThemeCachingEnabled; ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing; + ShouldRenderPdfAsImages = shouldRenderPdfAsImages; + ShouldPreserveBookStyles = shouldPreserveBookStyles; return Result.Updated; } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 809b7ce3..39fc1f8a 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -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; /// -/// Contains all services of the Infrastructure layer. +/// Utility class for registering the services of the Infrastructure layer into the Dependency Injection container. /// [ExcludeFromCodeCoverage] public static class InfrastructureLayerServices { /// - /// Extension method for adding the Infrastructure layer services to the DI container. + /// Registers the services of the Infrastucture layer into the Dependency Injection container. /// /// The service collection to add the services to. - /// The configuration manager used to read the application configuration. + /// The configuration used to read the application configuration. /// The updated . 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 concreteTypes = Assembly.GetExecutingAssembly() .GetTypes() .Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition); @@ -84,13 +87,13 @@ public static class InfrastructureLayerServices services.AddScoped(); services.AddScoped(); - // authorization + // Authorization. services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); - // media library scanning + // Media library scanning. services.AddSingleton(); services.AddSingleton(); services.AddHostedService(); @@ -106,15 +109,21 @@ public static class InfrastructureLayerServices services.AddSingleton(); - // 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(); - // 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(); + services.AddSingleton(); + services.AddSingleton(); + + // Plugins: load the plugin assemblies from the plugins directory, register their services and provide the plugin manager. string pluginsDirectorySetting = configuration.GetSection(PluginsSettingsDto.SECTION_NAME)["Directory"] ?? "plugins"; string pluginsDirectory = Path.Combine(AppContext.BaseDirectory, pluginsDirectorySetting); PluginLoadResultDto pluginLoadResult = PluginLoader.LoadPlugins(pluginsDirectory, services); - services.AddSingleton(new PluginManager(pluginLoadResult.Plugins)); + services.AddSingleton(new PluginManager(pluginLoadResult.Plugins, pluginLoadResult.LoadContexts)); services.AddScoped(); services.AddScoped(); services.AddScoped(); @@ -125,7 +134,7 @@ public static class InfrastructureLayerServices serviceProvider.GetRequiredService>())); services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); - // 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(); services.AddHostedService(); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs index 94c232c0..fe8aba26 100644 --- a/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs @@ -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. /// /// The plugins that were loaded successfully. +/// +/// 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. +/// /// The errors that occurred while loading the plugins. internal sealed record PluginLoadResultDto( - IReadOnlyList Plugins, + IReadOnlyList Plugins, + IReadOnlyList LoadContexts, IReadOnlyList Errors ); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs index c82c66a9..af0d994a 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs @@ -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; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs similarity index 99% rename from src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs index 39080b78..8ce2aca8 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs @@ -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; /// /// Stores the artwork of a book into the internal media directory, under a per-book directory, and returns its relative path. diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReaderEnablementCache.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReaderEnablementCache.cs new file mode 100644 index 00000000..f2e01a85 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReaderEnablementCache.cs @@ -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; + +/// +/// 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. +/// +internal sealed class BookReaderEnablementCache : IBookReaderEnablementCache +{ + private readonly ConcurrentDictionary<(Guid LibraryId, Guid PluginId), bool> _enablements = []; + + /// + public bool? Get(Guid libraryId, Guid pluginId) + { + return _enablements.TryGetValue((libraryId, pluginId), out bool isEnabled) ? isEnabled : null; + } + + /// + public void Set(Guid libraryId, Guid pluginId, bool isEnabled) + { + _enablements[(libraryId, pluginId)] = isEnabled; + } + + /// + public void Invalidate(Guid libraryId, Guid pluginId) + { + _enablements.TryRemove((libraryId, pluginId), out _); + } + + /// + public void InvalidateLibrary(Guid libraryId) + { + foreach ((Guid cachedLibraryId, Guid cachedPluginId) in _enablements.Keys) + if (cachedLibraryId == libraryId) + _enablements.TryRemove((cachedLibraryId, cachedPluginId), out _); + } + + /// + public void InvalidatePlugin(Guid pluginId) + { + foreach ((Guid cachedLibraryId, Guid cachedPluginId) in _enablements.Keys) + if (cachedPluginId == pluginId) + _enablements.TryRemove((cachedLibraryId, cachedPluginId), out _); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReaderRegistry.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReaderRegistry.cs new file mode 100644 index 00000000..01a8cd10 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReaderRegistry.cs @@ -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; + +/// +/// Registry of the book readers provided by the loaded plugins. +/// +internal sealed class BookReaderRegistry : IBookReaderRegistry +{ + private readonly IPluginManager _pluginManager; + private readonly IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. + /// + /// Injected manager of the plugins loaded by the host application. + /// Injected provider used to resolve the book readers registered by the plugins. + public BookReaderRegistry(IPluginManager pluginManager, IServiceProvider serviceProvider) + { + _pluginManager = pluginManager; + _serviceProvider = serviceProvider; + } + + /// + /// Gets the file extensions supported by the book readers of each loaded plugin, keyed by the Id of the plugin. + /// + /// The supported extensions of the book readers, keyed by the Id of the plugin providing them. + public IReadOnlyDictionary> GetSupportedExtensionsByPluginId() + { + Dictionary> 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 extensions = [.. _serviceProvider.GetKeyedServices(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; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingService.cs new file mode 100644 index 00000000..cdfb5059 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingService.cs @@ -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; + +/// +/// 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. +/// +/// +/// 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. +/// +internal sealed class BookReadingService : IBookReadingService +{ + private readonly ConcurrentDictionary _extractions = []; + private readonly ConcurrentDictionary _bookExtractionLocks = []; + private readonly IServiceProvider _serviceProvider; + private readonly IPluginManager _pluginManager; + private readonly IBookReaderEnablementCache _enablementCache; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _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? _pluginIdsByReaderKey; + private readonly object _readerMapSync = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected provider used to resolve the book readers registered by the plugins. + /// Injected manager of the plugins loaded by the host application. + /// Injected cache of whether the book reader of a plugin is enabled for a media library. + /// Injected factory for creating scopes in which the book reader configurations are requested. + /// Injected logger used to report the failures to open the books. + public BookReadingService(IServiceProvider serviceProvider, IPluginManager pluginManager, IBookReaderEnablementCache enablementCache, IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceProvider = serviceProvider; + _pluginManager = pluginManager; + _enablementCache = enablementCache; + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Gets the reading manifest of the book stored at . + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Cancellation token that can be used to stop the execution. + /// An containing either the reading manifest of the book, or an error. + public async Task> GetManifestAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, bool shouldRenderPdfAsImages, CancellationToken cancellationToken) + { + Result extractionResult = await GetExtractionAsync(bookId, libraryId, path, libraryType, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false); + return extractionResult.IsSuccess ? extractionResult.Value.Document.ToResponse() : extractionResult.Errors; + } + + /// + /// Gets the content of the reading section identified by of the book stored at . + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// The opaque location reference of the reading section. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Whether the styles of the section content are preserved when it is sanitized, or stripped. + /// Cancellation token that can be used to stop the execution. + /// An containing either the content of the reading section, or an error. + public async Task> GetSectionAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string locationRef, bool shouldRenderPdfAsImages, bool shouldPreserveStyles, CancellationToken cancellationToken) + { + Result 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 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)); + } + + /// + /// Gets the resource identified by of the book stored at . + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// The opaque resource key of the resource. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Cancellation token that can be used to stop the execution. + /// An containing either the resource, or an error. + public async Task> 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 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 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); + } + + /// + /// Checks whether the book stored at 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. + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// Cancellation token that can be used to stop the execution. + /// An containing either the reading availability of the book, or an error. + public async Task> 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 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); + } + + /// + /// Gets the extracted reading document of the book stored at , 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. + /// + /// The Id of the book. + /// The Id of the media library the book belongs to. + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Cancellation token that can be used to stop the execution. + /// An containing either the extracted document of the book with its section lookup, or an error. + private async Task> 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 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 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(); + } + } + + /// + /// Extracts the book stored at into its temporary directory using the provided . + /// + /// The book reader used to extract the book. + /// The Id of the book. + /// The file system path of the book. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Cancellation token that can be used to stop the execution. + /// An containing either the reading document of the book, or an error. + private async Task> 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."); + } + } + + /// + /// Resolves the book reader supporting the extension and the library type of the book stored at . + /// + /// The file system path of the book. + /// The type of the media library the book belongs to. + /// An containing either the Id of the plugin and the resolved book reader, or an error. + 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 pluginIdsByReaderKey = GetPluginIdsByReaderKey(); + if (!pluginIdsByReaderKey.TryGetValue(readerKey, out Guid pluginId)) + return Errors.Reading.NoReaderAvailable; + IBookReader? reader = _serviceProvider.GetKeyedServices(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; + } + + /// + /// Gets the mapping from a format to the Id of the plugin that reads it, built once from the plugins loaded by the host. + /// + /// The Id of the plugin reading each format, keyed by the format. + private IReadOnlyDictionary GetPluginIdsByReaderKey() + { + IReadOnlyDictionary? 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 discoveredPluginIdsByReaderKey = []; + foreach (IPlugin plugin in _pluginManager.GetPlugins().OrderBy(plugin => plugin.Name, StringComparer.OrdinalIgnoreCase)) + { + foreach (IBookReader candidateReader in _serviceProvider.GetKeyedServices(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; + } + } + + /// + /// Determines whether the book reader of the plugin identified by is enabled for the media library identified by . + /// + /// The Id of the media library whose book reader configuration is read. + /// The Id of the plugin providing the book reader. + /// Cancellation token that can be used to stop the execution. + /// An containing either whether the book reader is enabled, or an error. + private async Task> 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(); + Result 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; + } + + /// + /// Determines whether the file stored at changed since it was extracted. + /// + /// The stored extraction of the book. + /// The file system path of the book. + /// when the file changed since it was extracted, otherwise. + 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; + } + + /// + /// Gets the size and the last write time of the file stored at , in a single file system probe. + /// + /// The file system path of the file. + /// The fingerprint of the file, or the fingerprint of a missing file when it cannot be probed. + 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; + } + } + + /// + /// 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. + /// + /// The reading document of the book. + /// The reading sections of the book, keyed by their location reference. + private static IReadOnlyDictionary BuildSectionLookup(ReadingDocumentDto document) + { + Dictionary sectionsByLocationRef = []; + foreach (ReadingSpineItemDto spineItem in document.Spine) + sectionsByLocationRef.TryAdd(spineItem.LocationRef, spineItem); + return sectionsByLocationRef; + } + + /// + /// Gets the temporary directory into which the book identified by is extracted for the rendering + /// preference identified by . + /// + /// The Id of the book. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// The absolute path of the temporary directory of the book for the rendering preference. + 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"); + } + + /// + /// Resolves a package-relative path against a package root, rejecting paths that escape the root. + /// + /// The absolute path of the package root. + /// The package-relative path to resolve. + /// An containing either the absolute path, or an error. + private static Result 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; + } + + /// + /// The extracted document of a book, along with the lookup of its sections and the file fingerprint captured at extraction time. + /// + /// The reading document of the book. + /// The reading sections of the book, keyed by their location reference. + /// The size and last write time of the book file at extraction time. + private sealed record BookExtractionEntry(ReadingDocumentDto Document, IReadOnlyDictionary SectionsByLocationRef, BookFileFingerprint Fingerprint) + { + /// + /// 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. + /// + public ConcurrentDictionary ResourceProductionLocks { get; } = []; + } + + /// + /// The fingerprint of a book file, used to detect whether the file changed since it was extracted. + /// + /// The size of the file, or -1 when the file does not exist. + /// The last write time of the file, or when the file does not exist. + private readonly record struct BookFileFingerprint(long FileSize, DateTime LastWriteTimeUtc) + { + /// + /// The fingerprint of a file that does not exist or cannot be probed. + /// + public static BookFileFingerprint Missing { get; } = new(-1, DateTime.MinValue); + } + + /// + /// 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. + /// + /// The Id of the book. + /// Whether the book, when it is a PDF, was rendered as page images instead of extracting its text layer. + private sealed record ReadingCacheKey(Guid BookId, bool ShouldRenderPdfAsImages); + + /// + /// The format of a book, combining its file extension with the type of its media library. + /// + /// The lower-case file extension of the format, with its leading dot. + /// The type of the media library the format is read for. + private sealed record ReaderKey(string Extension, LibraryType LibraryType); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingCachePaths.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingCachePaths.cs new file mode 100644 index 00000000..582ca037 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingCachePaths.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; + +/// +/// Provides the location of the temporary directory into which the reading plugins extract the contents of the books. +/// +public static class ReadingCachePaths +{ + /// + /// The name of the temporary directory into which the reading plugins extract the contents of the books. + /// + public const string DIRECTORY_NAME = "reading-cache"; + + /// + /// Gets the absolute path of the temporary directory into which the reading plugins extract the contents of the books. + /// + /// The absolute path of the reading cache directory. + public static string GetRootDirectory() + { + return Path.Combine(AppContext.BaseDirectory, DIRECTORY_NAME); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingContentSanitizer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingContentSanitizer.cs new file mode 100644 index 00000000..9ca2e837 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingContentSanitizer.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Ganss.Xss; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; + +/// +/// 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. +/// +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); + + /// + /// Sanitizes the provided , returning the safe HTML content ready to be rendered by the client. + /// + /// The HTML content to sanitize. + /// Whether the style attributes of the content are preserved, or stripped. + /// The sanitized HTML content. + 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); + } + + /// + /// Creates the sanitizer configured with the tags, attributes, and schemes a reading section may use. + /// + /// Whether the style attribute is included in the allowlist of the sanitizer, or not. + /// The configured sanitizer. + 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; + } +} diff --git a/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs b/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs index d82ea794..f1347aae 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs @@ -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; /// -/// 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. /// +/// +/// 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). +/// internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProviderConfigurationStore { private readonly IUnitOfWork _unitOfWork; private readonly IPluginManager _pluginManager; private readonly IServiceProvider _serviceProvider; + private readonly IBookReaderEnablementCache _enablementCache; /// /// Initializes a new instance of the class. @@ -31,69 +42,161 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv /// Injected unit of work for interacting with the data access layer repositories. /// Injected manager of the plugins loaded by the host application. /// Injected provider used to resolve the providers registered by the plugins. - public MediaLibraryProviderConfigurationStore(IUnitOfWork unitOfWork, IPluginManager pluginManager, IServiceProvider serviceProvider) + /// Injected cache of whether the book reader of a plugin is enabled for a media library. + public MediaLibraryProviderConfigurationStore(IUnitOfWork unitOfWork, IPluginManager pluginManager, IServiceProvider serviceProvider, IBookReaderEnablementCache enablementCache) { _unitOfWork = unitOfWork; _pluginManager = pluginManager; _serviceProvider = serviceProvider; + _enablementCache = enablementCache; } - /// + /// + /// Gets the metadata provider configurations of the media library identified by . + /// + /// The Id of the media library whose metadata provider configurations are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the configurations, or an error. public async Task>> GetConfigurationsAsync(Guid libraryId, CancellationToken cancellationToken) { return await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); } - /// + /// + /// 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 . + /// + /// The Id of the media library whose provider configurations are ensured. + /// The type of the media library, used to determine the plugins whose providers apply. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. public async Task> 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 metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType); Result ensureMetadataResult = await EnsureMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false); if (ensureMetadataResult.IsFailure) return ensureMetadataResult; - return await EnsureArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false); + Result ensureArtworkResult = await EnsureArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false); + if (ensureArtworkResult.IsFailure) + return ensureArtworkResult; + return await EnsureBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false); } - /// + /// + /// Replaces the provider configurations of the media library identified by so that they match the plugins supporting the provided library type. + /// + /// The Id of the media library whose provider configurations are reconciled. + /// The type of the media library, used to determine the plugins whose providers apply. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. public async Task> 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 metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType); Result reconcileMetadataResult = await ReconcileMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false); if (reconcileMetadataResult.IsFailure) return reconcileMetadataResult; - return await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false); - } - - /// - public async Task> RemoveProviderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) - { - Result removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); - if (removeMetadataResult.IsFailure) - return removeMetadataResult; - return await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); - } - - /// - public async Task> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken) - { - Result removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false); - if (removeMetadataResult.IsFailure) - return removeMetadataResult; - return await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false); + Result reconcileArtworkResult = await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false); + if (reconcileArtworkResult.IsFailure) + return reconcileArtworkResult; + return await ReconcileBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false); } /// - /// 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 . + /// + /// The Id of the media library whose provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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 removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (removeMetadataResult.IsFailure) + return removeMetadataResult; + Result removeArtworkResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (removeArtworkResult.IsFailure) + return removeArtworkResult; + Result 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; + } + + /// + /// Deletes all the provider configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken) + { + // An uninstalled plugin can no longer serve any provider, so the configurations referencing it are deleted. + Result removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false); + if (removeMetadataResult.IsFailure) + return removeMetadataResult; + Result removeArtworkResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false); + if (removeArtworkResult.IsFailure) + return removeArtworkResult; + Result 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; + } + + /// + /// Deletes all the book reader configurations of the media library identified by . + /// + /// The Id of the media library whose book reader configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + { + Result 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; + } + + /// + /// Deletes all the book reader configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose book reader configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken) + { + Result 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; + } + + /// + /// 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. /// /// The type of the media library the providers must support. /// The Ids of the plugins providing metadata, and the Ids of the plugins providing artwork. private (IReadOnlyList metadataProviderPluginIds, IReadOnlyList 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 metadataProviderPluginIds = []; List 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(plugin.Id).Any(provider => provider.SupportedLibraryTypes.Contains(libraryType))) metadataProviderPluginIds.Add(plugin.Id); if (_serviceProvider.GetKeyedServices(plugin.Id).Any(provider => provider.SupportedLibraryTypes.Contains(libraryType))) @@ -102,6 +205,111 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv return (metadataProviderPluginIds, artworkProviderPluginIds); } + /// + /// 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. + /// + /// The type of the media library the book readers must support. + /// The Ids of the plugins providing a book reader for the library type. + private IReadOnlyList 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 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(plugin.Id).Any(reader => reader.SupportedLibraryTypes.Contains(libraryType) && reader.SupportedExtensions.Count > 0)) + bookReaderPluginIds.Add(plugin.Id); + return bookReaderPluginIds; + } + + /// + /// Replaces the book reader configurations of the media library identified by so that they match the plugins supporting the provided library type. + /// + /// The Id of the media library whose book reader configurations are reconciled. + /// The type of the media library, used to determine the plugins whose book readers apply. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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 bookReaderPluginIds = GetSupportedBookReaderPluginIds(libraryType); + Result> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + HashSet supportedPluginIds = [.. bookReaderPluginIds]; + List stalePluginIds = [.. getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !supportedPluginIds.Contains(pluginId))]; + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + HashSet 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 upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + } + return Result.Success; + } + + /// + /// 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 . + /// + /// The Id of the media library whose book reader configurations are ensured. + /// The type of the media library, used to determine the plugins whose book readers apply. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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 bookReaderPluginIds = GetSupportedBookReaderPluginIds(libraryType); + if (bookReaderPluginIds.Count == 0) + return Result.Success; + Result> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + HashSet 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 upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + } + return Result.Success; + } + /// /// 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> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return Result.Failure(getConfigurationsResult.Errors); - HashSet supportedPluginIds = metadataProviderPluginIds.ToHashSet(); - List stalePluginIds = getConfigurationsResult.Value + HashSet supportedPluginIds = [.. metadataProviderPluginIds]; + List 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 removeResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); if (removeResult.IsFailure) return Result.Failure(removeResult.Errors); } - HashSet configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet(); + HashSet 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> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return Result.Failure(getConfigurationsResult.Errors); - HashSet supportedPluginIds = artworkProviderPluginIds.ToHashSet(); - List stalePluginIds = getConfigurationsResult.Value + HashSet supportedPluginIds = [.. artworkProviderPluginIds]; + List 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 removeResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); if (removeResult.IsFailure) return Result.Failure(removeResult.Errors); } - HashSet configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet(); + HashSet 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> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return Result.Failure(getConfigurationsResult.Errors); - HashSet configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet(); + HashSet 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> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return Result.Failure(getConfigurationsResult.Errors); - HashSet configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet(); + HashSet 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(), diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index 212a07a3..19602b01 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -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(); - // 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 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(); Result> 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> 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 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 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 } /// - /// 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. /// /// The file name of the plugin assembly, without its extension. /// The derived plugin identifier. diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs index 7ce4b358..102304c9 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs @@ -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 plugins = []; + List loadContexts = []; List 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); + } + + /// + /// Determines whether the file at is a PE image (either a managed assembly or a native library), + /// by checking its DOS signature. + /// + /// The path of the file to check. + /// when the file starts with the DOS signature of a PE image, otherwise. + private static bool IsPeImage(string path) + { + try + { + using FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); + Span 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; + } } } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginManager.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginManager.cs index 487aeb13..c287fb75 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginManager.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginManager.cs @@ -14,14 +14,19 @@ namespace Lumina.Infrastructure.Core.Plugins; internal sealed class PluginManager : IPluginManager { private readonly IReadOnlyDictionary _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 _loadContexts; /// /// Initializes a new instance of the class. /// /// The plugins that were loaded successfully. - public PluginManager(IEnumerable plugins) + /// The load contexts of the loaded plugins, kept referenced for the lifetime of the host. + public PluginManager(IEnumerable plugins, IReadOnlyList loadContexts) { _pluginsById = plugins.ToDictionary(plugin => plugin.Id); + _loadContexts = loadContexts; } /// diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 1220a724..a6d6e8c9 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -16,6 +16,7 @@ + diff --git a/src/Lumina.Plugins.Contracts/Core/Reading/IBookReader.cs b/src/Lumina.Plugins.Contracts/Core/Reading/IBookReader.cs new file mode 100644 index 00000000..40b50f1d --- /dev/null +++ b/src/Lumina.Plugins.Contracts/Core/Reading/IBookReader.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.Core.Reading; + +/// +/// Contract for a plugin that decodes a book format into a normalized reading document. +/// +public interface IBookReader +{ + /// + /// Gets the file extensions supported by the reader, with the leading dot (i.e., .epub). + /// + IReadOnlyList SupportedExtensions { get; } + + /// + /// Gets the media library types the reader supports. + /// + IReadOnlyList SupportedLibraryTypes { get; } + + /// + /// Opens the book stored at , extracting its sections and resources into + /// , and returns its normalized reading document. + /// + /// The file system path of the book. + /// The directory into which the sections and resources of the book are extracted. + /// Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer. + /// Cancellation token that can be used to stop the execution. + /// The normalized reading document of the book. + Task OpenAsync(string path, string workingDirectory, bool shouldRenderPdfAsImages, CancellationToken cancellationToken); + + /// + /// Produces the bytes of the resource identified by of the book stored at , on demand. + /// A reader that extracts every resource eagerly (for example an EPUB, whose resources are read straight from the archive) can + /// simply return the bytes of the extracted file; a reader that renders resources lazily (for example a PDF whose pages are + /// rendered as images only when they are shown) produces the resource here. The media type of the resource is not returned by the + /// reader: the host already knows it from the manifest of the book, and serves the resource with that media type. + /// + /// The file system path of the book. + /// The directory into which the sections and resources of the book are extracted. + /// The opaque resource key of the resource to produce. + /// Cancellation token that can be used to stop the execution. + /// The binary data of the produced resource. + Task GetResourceAsync(string path, string workingDirectory, string resourceKey, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index a854cc7c..27275cf9 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -25,23 +25,23 @@ using System.Threading.RateLimiting; namespace Lumina.Presentation.Api.Common.DependencyInjection; /// -/// Contains all services of the Presentation API layer. +/// Utility class for registering the services of the Presentation Api layer into the Dependency Injection container. /// [ExcludeFromCodeCoverage] public static class PresentationApiLayerServices { /// - /// Registers the services of the Presentation API layer into the dependency injection container. + /// Registers the services of the Presentation Api layer into the Dependency Injection container. /// /// The service collection to add the services to. - /// Application configuration properties. + /// The configuration used to read the application configuration. /// The updated . public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services, IConfiguration configuration) { - services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting + services.AddMemoryCache(); // Used for the tracking involved in authentication rate limiting. services.AddProblemDetails(); - // the readiness health check verifies that the database can be reached, and is probed by container orchestrators and load balancers + // The readiness health check verifies that the database can be reached, and is probed by container orchestrators and load balancers. services.AddHealthChecks() .AddCheck("database", HealthStatus.Unhealthy, ["ready"]); @@ -49,10 +49,10 @@ public static class PresentationApiLayerServices { jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); jsonOptions.SerializerOptions.MaxDepth = 256; - jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures + jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // Needed because file system API responses can have very nested structures. }); - // TODO: also implement account locking after a number of failed login attempts + // TODO: also implement account locking after a number of failed login attempts. services.AddRateLimiter(rateLimiterOptions => { rateLimiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests; @@ -68,16 +68,16 @@ public static class PresentationApiLayerServices "Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}", clientIp, onRejectedContext.HttpContext.Request.Path, - onRejectedContext.Lease.IsAcquired); // when False, the request was rejected because it exceeded rate limits + onRejectedContext.Lease.IsAcquired); // When False, the request was rejected because it exceeded rate limits. onRejectedContext.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests; onRejectedContext.HttpContext.Response.ContentType = "application/problem+json"; - // set standard rate limit headers + // Set standard rate limit headers. if (onRejectedContext.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter)) onRejectedContext.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString(); - // set custom rate limit headers + // Set custom rate limit headers. onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Limit"] = "10"; onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0"; onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Reset"] = DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds().ToString(); @@ -95,23 +95,23 @@ public static class PresentationApiLayerServices }; rateLimiterOptions.AddPolicy("authenticationPolicy", httpContext => { - string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // first check forwarded headers, in case this is behind a reverse proxy - .FirstOrDefault()?.Split(',')[0].Trim() // take first IP, if multiple available, to avoid IP spoofing attempts - ?? httpContext.Connection.RemoteIpAddress?.ToString() // then try RemoteIpAddress - ?? "unknown"; // fallback if both are null + string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // First check forwarded headers, in case this is behind a reverse proxy. + .FirstOrDefault()?.Split(',')[0].Trim() // Take first IP, if multiple available, to avoid IP spoofing attempts, + ?? httpContext.Connection.RemoteIpAddress?.ToString() // then try RemoteIpAddress. + ?? "unknown"; // Fallback if both are null. return RateLimitPartition.GetFixedWindowLimiter( partitionKey: $"auth_{clientIp}", factory: _ => new FixedWindowRateLimiterOptions { - PermitLimit = 10, // allow 10 attempts - Window = TimeSpan.FromMinutes(15), // within 15 minute window - QueueLimit = 0, // don't queue requests - AutoReplenishment = true // automatically reset rate limiter tokens + PermitLimit = 10, // Allow 10 attempts + Window = TimeSpan.FromMinutes(15), // within 15 minute window. + QueueLimit = 0, // Don't queue requests. + AutoReplenishment = true // Automatically reset rate limiter tokens. }); }); }); - // add authentication and specify the JWT scheme to check tokens against + // Add authentication and specify the JWT scheme to check tokens against. services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(jwtBearerOptions => { @@ -128,10 +128,10 @@ public static class PresentationApiLayerServices jwtBearerOptions.Events = new JwtBearerEvents { - OnChallenge = jwtBearerChallengeContext => // event triggered when authentication is not successful for whatever reason + OnChallenge = jwtBearerChallengeContext => // Event triggered when authentication is not successful for whatever reason. { - jwtBearerChallengeContext.HandleResponse(); // prevent the default 401 response - // set the response status code to 401 Unauthorized + jwtBearerChallengeContext.HandleResponse(); // Prevent the default 401 response. + // Set the response status code to 401 Unauthorized. jwtBearerChallengeContext.Response.StatusCode = StatusCodes.Status401Unauthorized; jwtBearerChallengeContext.Response.ContentType = "application/problem+json"; @@ -139,7 +139,7 @@ public static class PresentationApiLayerServices if (!string.IsNullOrEmpty(jwtBearerChallengeContext.Error)) { errorDetails = jwtBearerChallengeContext.Error switch - { // TODO: implement translation + { // TODO: implement translation. "invalid_token" => !string.IsNullOrEmpty(jwtBearerChallengeContext.ErrorDescription) ? $"Invalid token: {jwtBearerChallengeContext.ErrorDescription}" : "The token is invalid", @@ -174,9 +174,8 @@ public static class PresentationApiLayerServices services.AddFastEndpoints(endpointDiscoveryOptions => { endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ]; - // only scan the application assembly, so that duplicate copies of it loaded into other assembly load - // contexts during the process lifetime are never scanned again; otherwise a single host can register - // every endpoint multiple times and fail with duplicate routes + // Only scan the application assembly, so that duplicate copies of it loaded into other assembly load contexts during the process lifetime are never scanned again; + // otherwise a single host can register every endpoint multiple times and fail with duplicate routes. endpointDiscoveryOptions.DisableAutoDiscovery = true; }); @@ -200,7 +199,7 @@ public static class PresentationApiLayerServices }; documentOptions.RemoveEmptyRequestSchema = true; documentOptions.ShortSchemaNames = true; - }); // for an eventual next version: + }); // For an eventual next version: //.SwaggerDocument(documentOptions => //{ // documentOptions.MaxEndpointVersion = 2; diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs index b7ef7ec7..17ad6611 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs @@ -16,7 +16,7 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Presentation.Api.Common.DependencyInjection; /// -/// Contains the OpenTelemetry services of the Presentation API layer. +/// Utility class for registering the OpenTelemetry services of the Presentation Api layer into the Dependency Injection container. /// [ExcludeFromCodeCoverage] public static class PresentationApiTelemetryServices @@ -25,10 +25,10 @@ public static class PresentationApiTelemetryServices private const string ENTITY_FRAMEWORK_CORE_METER_NAME = "Microsoft.EntityFrameworkCore"; /// - /// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container. + /// Registers the OpenTelemetry services of the Presentation Api layer into the Dependency Injection container. /// /// The service collection to add the services to. - /// Application configuration properties. + /// The configuration used to read the application configuration. /// The hosting environment of the application. /// The updated . public static IServiceCollection AddPresentationApiTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment) diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index 50657a81..364276fa 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -28,5 +28,7 @@ public static partial class ApiRoutes public const string GET_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers"; public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "/libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers/reorder"; + public const string GET_LIBRARY_BOOK_READERS = "/libraries/{libraryId}/book-readers"; + public const string SET_LIBRARY_BOOK_READER_ENABLED = "/libraries/{libraryId}/book-readers/{pluginId}/enabled"; } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs index 6c91fe79..9ff7ea86 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs @@ -14,5 +14,9 @@ public static partial class ApiRoutes public const string GET_BOOKS = "/books"; public const string GET_BOOKS_LITE = "/books/lite"; public const string ADD_BOOK = "/books"; + public const string GET_BOOK_READING_MANIFEST = "/books/{bookId}/reading/manifest"; + public const string GET_BOOK_READING_AVAILABILITY = "/books/{bookId}/reading/availability"; + public const string GET_BOOK_READING_SECTION = "/books/{bookId}/reading/sections/{locationRef}"; + public const string GET_BOOK_READING_RESOURCE = "/books/{bookId}/reading/resources/{resourceKey}"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs index 18ac473f..ff71a601 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -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; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs index 4b2c139e..47183f75 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs @@ -2,7 +2,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -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; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs index 31b17ea6..51341186 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs @@ -2,7 +2,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -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; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs new file mode 100644 index 00000000..45beb694 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; + +/// +/// API endpoint for the /books/{bookId}/reading/availability route. +/// +public class GetReadingAvailabilityEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getReadingAvailabilityQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get reading availability queries. + public GetReadingAvailabilityEndpoint(IQueryHandler> getReadingAvailabilityQueryHandler) + { + _getReadingAvailabilityQueryHandler = getReadingAvailabilityQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Checks the reading availability of the book identified by . + /// + /// The request containing the Id of the book whose reading availability is checked. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetReadingAvailabilityRequest request, CancellationToken cancellationToken) + { + Result result = await _getReadingAvailabilityQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs new file mode 100644 index 00000000..7b81fa89 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetReadingAvailabilityEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingAvailabilityEndpointSummary() + { + Summary = "Checks the reading availability of a book."; + Description = "Checks whether the book 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."; + + ExampleRequest = new GetReadingAvailabilityRequest( + BookId: Guid.NewGuid() + ); + + RequestParam(r => r.BookId, "The Id of the book whose reading availability is checked. Required."); + + ResponseParam(r => r.BookId, "The Id of the book whose reading availability is reported."); + ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to."); + ResponseParam(r => r.IsAvailable, "Whether the book can be opened for reading."); + ResponseParam(r => r.ErrorCode, "The code of the error preventing the book from being read, when it cannot be read. Can be null when the book is available."); + + Response(200, "The reading availability of the book is returned.", + example: new ReadingAvailabilityResponse( + BookId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + IsAvailable: false, + ErrorCode: "ReaderDisabled" + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/books/{bookId}/reading/availability" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/books/{bookId}/reading/availability", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the book does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "BookNotFound", + instance = "/api/v1/books/{bookId}/reading/availability", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books/{bookId}/reading/availability", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "BookIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs new file mode 100644 index 00000000..bf39836b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; + +/// +/// API endpoint for the /books/{bookId}/reading/manifest route. +/// +public class GetReadingManifestEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getReadingManifestQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get reading manifest queries. + public GetReadingManifestEndpoint(IQueryHandler> getReadingManifestQueryHandler) + { + _getReadingManifestQueryHandler = getReadingManifestQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Books.GET_BOOK_READING_MANIFEST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the reading manifest of the book identified by . + /// + /// The request containing the Id of the book whose reading manifest is retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetReadingManifestRequest request, CancellationToken cancellationToken) + { + Result result = await _getReadingManifestQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs new file mode 100644 index 00000000..4371ce0f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetReadingManifestEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingManifestEndpointSummary() + { + Summary = "Retrieves the reading manifest of a book."; + Description = "Retrieves the reading manifest of a book, containing the metadata, the table of contents, the spine, and the resources needed to render the reader."; + + ExampleRequest = new GetReadingManifestRequest( + BookId: Guid.NewGuid() + ); + + RequestParam(r => r.BookId, "The Id of the book whose reading manifest is retrieved. Required."); + + ResponseParam(r => r.Title, "The title of the book."); + ResponseParam(r => r.Author, "The author of the book, if known."); + ResponseParam(r => r.CoverResourceKey, "The resource key of the cover image of the book, if applicable."); + ResponseParam(r => r.Spine, "The ordered spine of the reading sections of the book."); + ResponseParam(r => r.ResourceKeys, "The resource keys of the resources of the book."); + ResponseParam(r => r.HasTextContent, "Whether the book has extractable text content. A scanned book, whose pages are only images, has no text content."); + + Response(200, "The reading manifest of the book is returned.", + example: new ReadingManifestResponse( + Title: "The Fellowship of the Ring", + Author: "J.R.R. Tolkien", + CoverResourceKey: "cover-image", + TableOfContents: + [ + new ReadingTocEntryResponse( + Label: "Chapter 1", + LocationRef: "chapter-1", + Children: [] + ) + ], + Spine: + [ + new ReadingSpineItemResponse( + LocationRef: "chapter-1", + Title: "Chapter 1" + ) + ], + ResourceKeys: ["cover-image"], + HasTextContent: true + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/books/{bookId}/reading/manifest" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/books/{bookId}/reading/manifest", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the book does not exist, no reader plugin supports its format, or the reader plugin is disabled.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ReaderDisabled", + instance = "/api/v1/books/{bookId}/reading/manifest", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books/{bookId}/reading/manifest", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "BookIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs new file mode 100644 index 00000000..26cf512d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; + +/// +/// API endpoint for the /books/{bookId}/reading/resources/{resourceKey} route. +/// +public class GetReadingResourceEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getReadingResourceQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get reading resource queries. + public GetReadingResourceEndpoint(IQueryHandler> getReadingResourceQueryHandler) + { + _getReadingResourceQueryHandler = getReadingResourceQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Books.GET_BOOK_READING_RESOURCE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the resource of the book identified by . + /// + /// The request containing the Id of the book and the resource key of the resource. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetReadingResourceRequest request, CancellationToken cancellationToken) + { + Result result = await _getReadingResourceQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + if (result.IsFailure) + return Problem(result.Errors); + // The media type of a resource is declared by the book itself, so it is not trusted: a resource whose declared media type could be + // rendered as an active document (for example an SVG) is served as an opaque binary download instead, and every resource is served + // with content sniffing disabled, so that the browser never executes book content as anything but what this endpoint declares. + HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff"; + return TypedResults.Bytes(result.Value.Data, GetSafeContentType(result.Value.MimeType)); + } + + /// + /// Gets the safe content type of a book resource, replacing the media types that could be rendered as active documents with an opaque binary type. + /// + /// The media type declared by the book. + /// The safe content type the resource is served with. + private static string GetSafeContentType(string mediaType) + { + // Images, audio, video, fonts, and stylesheets are inert content the reader can render; everything else (an SVG, an XML or HTML + // document, a script) is served as an opaque download, so that opening a resource URL never executes active content. + if (mediaType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) && !string.Equals(mediaType, "image/svg+xml", StringComparison.OrdinalIgnoreCase)) + return mediaType; + if (mediaType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || mediaType.StartsWith("video/", StringComparison.OrdinalIgnoreCase)) + return mediaType; + if (mediaType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) + || string.Equals(mediaType, "application/font-woff", StringComparison.OrdinalIgnoreCase) + || string.Equals(mediaType, "application/font-woff2", StringComparison.OrdinalIgnoreCase) + || string.Equals(mediaType, "application/vnd.ms-opentype", StringComparison.OrdinalIgnoreCase) + || string.Equals(mediaType, "application/x-font-ttf", StringComparison.OrdinalIgnoreCase) + || string.Equals(mediaType, "application/x-font-opentype", StringComparison.OrdinalIgnoreCase) + || string.Equals(mediaType, "text/css", StringComparison.OrdinalIgnoreCase)) + return mediaType; + return "application/octet-stream"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs new file mode 100644 index 00000000..c624beea --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetReadingResourceEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingResourceEndpointSummary() + { + Summary = "Retrieves a resource of a book, for reading."; + Description = "Retrieves the binary content of a resource of a book, such as an image or a font referenced by a reading section."; + + ExampleRequest = new GetReadingResourceRequest( + BookId: Guid.NewGuid(), + ResourceKey: "cover-image" + ); + + RequestParam(r => r.BookId, "The Id of the book whose resource is retrieved. Required."); + RequestParam(r => r.ResourceKey, "The opaque resource key of the resource. Required."); + + Response(200, "The resource of the book is returned."); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the book does not exist, no reader plugin supports its format, the reader plugin is disabled, or the resource was not found.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ResourceNotFound", + instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "BookIdCannotBeEmpty", + "ResourceKeyCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs new file mode 100644 index 00000000..d5ee709a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; + +/// +/// API endpoint for the /books/{bookId}/reading/sections/{locationRef} route. +/// +public class GetReadingSectionEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getReadingSectionQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get reading section queries. + public GetReadingSectionEndpoint(IQueryHandler> getReadingSectionQueryHandler) + { + _getReadingSectionQueryHandler = getReadingSectionQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Books.GET_BOOK_READING_SECTION); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the content of the reading section of the book identified by . + /// + /// The request containing the Id of the book and the location reference of the reading section. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetReadingSectionRequest request, CancellationToken cancellationToken) + { + Result result = await _getReadingSectionQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs new file mode 100644 index 00000000..2ede5f39 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetReadingSectionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingSectionEndpointSummary() + { + Summary = "Retrieves the content of a reading section of a book."; + Description = "Retrieves the sanitized HTML content of the reading section of a book, ready to be rendered by the client."; + + ExampleRequest = new GetReadingSectionRequest( + BookId: Guid.NewGuid(), + LocationRef: "chapter-1" + ); + + RequestParam(r => r.BookId, "The Id of the book whose reading section is retrieved. Required."); + RequestParam(r => r.LocationRef, "The opaque location reference of the reading section. Required."); + + ResponseParam(r => r.LocationRef, "The opaque location reference of the reading section."); + ResponseParam(r => r.Title, "The title of the reading section, if known."); + ResponseParam(r => r.ContentHtml, "The sanitized HTML content of the reading section."); + + Response(200, "The content of the reading section is returned.", + example: new ReadingSectionDto( + LocationRef: "chapter-1", + Title: "Chapter 1", + ContentHtml: "

Chapter 1

A long journey begins...

" + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/books/{bookId}/reading/sections/{locationRef}" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/books/{bookId}/reading/sections/{locationRef}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the book does not exist, no reader plugin supports its format, the reader plugin is disabled, or the reading section was not found.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "SectionNotFound", + instance = "/api/v1/books/{bookId}/reading/sections/{locationRef}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/books/{bookId}/reading/sections/{locationRef}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "BookIdCannotBeEmpty", + "LocationRefCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpoint.cs new file mode 100644 index 00000000..edca96f1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryBookReaders; + +/// +/// API endpoint for the /libraries/{libraryId}/book-readers route. +/// +public class GetLibraryBookReadersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryBookReadersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library book readers queries. + public GetLibraryBookReadersEndpoint(IQueryHandler>> getLibraryBookReadersQueryHandler) + { + _getLibraryBookReadersQueryHandler = getLibraryBookReadersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the book readers configured for the media library identified by . + /// + /// The request containing the Id of the media library whose book readers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryBookReadersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryBookReadersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointSummary.cs new file mode 100644 index 00000000..e6cae6df --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointSummary.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryBookReaders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryBookReadersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryBookReadersEndpointSummary() + { + Summary = "Retrieves the book readers configured for a media library."; + Description = "Retrieves the book readers configured for a media library, with their supported file extensions and enabled state."; + + ExampleRequest = new GetLibraryBookReadersRequest( + LibraryId: Guid.NewGuid() + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose book readers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader."); + ResponseParam(r => r.Name, "The display name of the book reader."); + ResponseParam(r => r.SupportedExtensions, "The file extensions supported by the book reader."); + ResponseParam(r => r.IsEnabled, "Whether the book reader is enabled for the media library."); + + Response(200, "The book readers configured for the media library are returned.", + example: new LibraryBookReaderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "EPUB Reader", + SupportedExtensions: [".epub"], + IsEnabled: true + ), + new( + PluginId: Guid.NewGuid(), + Name: "PDF Reader", + SupportedExtensions: [".pdf"], + IsEnabled: false + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/book-readers" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/book-readers", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/book-readers", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/book-readers", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs new file mode 100644 index 00000000..3ec20be4 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; + +/// +/// API endpoint for the /libraries/{libraryId}/book-readers/{pluginId}/enabled route. +/// +public class SetLibraryBookReaderEnabledEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _setLibraryBookReaderEnabledCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling set library book reader enabled commands. + public SetLibraryBookReaderEnabledEndpoint(ICommandHandler> setLibraryBookReaderEnabledCommandHandler) + { + _setLibraryBookReaderEnabledCommandHandler = setLibraryBookReaderEnabledCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED); + Version(1); + DontCatchExceptions(); + } + + /// + /// Enables or disables the book reader identified by for the media library. + /// + /// The request containing the Ids of the media library and of the book reader. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetLibraryBookReaderEnabledRequest request, CancellationToken cancellationToken) + { + Result result = await _setLibraryBookReaderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs new file mode 100644 index 00000000..149f7ea7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryBookReaderEnabledEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetLibraryBookReaderEnabledEndpointSummary() + { + Summary = "Enables or disables a book reader for a media library."; + Description = "Enables or disables the book reader of the media library identified by the request."; + + ExampleRequest = new SetLibraryBookReaderEnabledRequest( + LibraryId: Guid.NewGuid(), + PluginId: Guid.NewGuid(), + IsEnabled: true + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose book reader is enabled or disabled. Required."); + RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader. Required."); + RequestParam(r => r.IsEnabled, "Whether the book reader should be enabled for the media library. Required."); + + Response(200, "The book reader of the media library is enabled or disabled.", + example: new + { + success = true + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled" + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "PluginIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs index f66e991f..653f7a85 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs @@ -28,7 +28,9 @@ public class GetUserSettingsEndpointSummary : Summary r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Required."); RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Required."); RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required."); RequestParam(r => r.IsThemeCachingEnabled, "Whether the theme data served to this user is cached, or not. Required."); + RequestParam(r => r.ShouldRenderPdfAsImages, "Whether PDF books are rendered as page images for the user, or not. Required."); + RequestParam(r => r.ShouldPreserveBookStyles, "Whether the styles of the book content are preserved when it is rendered for the user, or not. Required."); Response(200, "The settings of the current user were successfully updated."); diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index 69c696c1dd3a26147e24db58605458176a352d10..10e5b73d76216cbbbcef5c5fb945c393830429f6 100644 GIT binary patch delta 6343 zcmZvh1yEFN7sq$u(%s$NB_%B?2r7brB2v<|#8OHuA)-i0U62k1K^jFmq>)aQ5)h?3 z6vXfDBJb-v^TF)gIluoo|K~h$pJA3~1ypq6RU2f0S3WH^ zKn;Vz@L_X=9473CdUl57Fc^bk+#38k%GeqCS%>+AL^UGQp$Fsunp;<`o~cl3PFd z!k+i~`uXvtyXKUX&u(x>vx^i)ogA%+s#3z#u5_iUOh{JWh8=CM5@qt0)miFxC)|n1 zt}EDfqTLdnj!F+`oBc-6U^ps6^Hf*Z;Mw*Xj&XuyL+(t4*6S}uJT}%1x^xla2B^M1 z@aqeP>%tA`z1fO|?>=1Yk}21^{ich7RLC5>AenOR(TbyaZjdV z!bs>&k5eLkwN?R<7pbNBC%(MR6M;S>p3V||n(J-3_fp&T9@M`;f%m&EJDL_-$(*;S z;+%U!dG$#_%N6 zf{Nv(D~&E+s(3gu-Uct(P;An?(6|)eRjr;hcVf%0_pC@OfKOGZT&wN-(tB+GiM8}p z-fz<$+%KDH0)58vhX!^fg_gs+d?fUOL0!olJT60LqAc*7!^GnVTE22=r^~}-y{o9t z6%}&o%L%%Y9fp6m3&5XYI)_B;($UN|;*wp)vZytxDUpeGIvuWteamA+3=Zn3WOv z+@Qt&aV;3zOg!?6nnKy#9R9W`Vw`ic^vAURw$XeIxVVxfqo!s~{m0c5HO-7In!STP(hj#n0u2Ygr4T3fIz` zS(7^+x^C2jR^dF|$!~X+F?+InUvP7ttaP?(LcMcq#3qixhg_?#l@}ViJbyOo&i@Z#lJP z#|tC=^Ue#N3?8L5E`AzcBXMJVQ6%RTg_~)0l;U9ga#3nTj`e#_=|~W)6TzXSow-3Y zSAz^VI90JkboOo{HbPg~8h%BsU7uJ`;Uga7ThDXaibqY6Q&WBQ zZ0T81q>bA+>1Jh$UD_a}Rm;ARv^g;6t`8=Se6N%1haw z$#VC6G!`N{HaWVzlb--f1LZS^9&pkA+!om_Q(6*=2=84&R!`%ebA}7d8`E`w#c+pS zlaCvoDQ=ILd$Pf-w)xEN&_v-|tGSAE7RE>}nhRDbSDm@|s0w;U$ih%VH>%tQa3f+% z20JConn#zym!y@_u8N8D&d14*bjG9@Fzy5Yi$3)>?^&L?{ zzdfIo=TSFNKV@ri~ss;Tf&9>Tkq$`P1wG_hIzm4jDWI&~1uO8iuCTvIxEecEx^ z#PLUad#Fr6_e*}CKs`%h?oAK>?7=ujbsC*P34Qomf{>=0svllGv_lN(uo%AkWTX3y z!oKf~`rR)(f!ayU@hQpytJdWW8s~G($Bi`GH%OH1mKgWZ%JKCWVI^noyC%&S z)*lKqsR?1P_bB_{!|tO)(Qe)Cv4mf=RTjTrn|)`CC;k?aRegJec2Hj-TFK6R1v}h{VV~=-HyQKQ7@olKi<_tIT0NG5$NOBkPWE;4%Nw^EB|AwLP+GN}MVhm0uS<4l z2RnnC-^)CSpnOa5LOkLAheJxM%MbOyF;cNBMntNj+j9x^fscsA2S4OWQFMNT(^fF+ z66%(?Sv2#`4)De2KJ_KNR3^7%$5T-JnrLcz(Nh??I)Z>tE66??t#hC|(6eDn+ccwN zcXOLEv{febJXd0@%7D5oD8jZnO-F90MN$sKd*^rkg3@3ZVYyx)ws)yp^-B}Vpi%2| z$`}rYH*F^02?grun9h-UhQ_j5Iq>k)I8$-I=2Z7@8z1o~EhR~i(N=S1-!Y2JB>4Tf zO!oOFSENJy+~LkfU-*%Dq%xqE?ed$FU5h=tB6Q{wypd<=YI`2acF~shaP$~vRj1;= z8yK71<8v@QBUHnXi;v{a{BF-L=4{#9+}o+AAeE3WBkrP)eY;-XT|&$SC#~Zgfvo)v zt9Zqf=>)qWt$F6)BEY9I;toStDh^YC7LzYG;kJsFv?jZL`kWhe&2xG6a7qe){k5Uj z2D55?nC0Kb;Alz9>UrEV^U$FXQT(feHTJ`CjJY2 z(pYAkN!4=KqQ6Z@2R8P%#*W)dZ#C%-=L?FNzU~rjX6RuaQ1i{vC_<(H7vtZGx<_gc zULh47YwrlK8e^4Tm3OZ%_Ydp*RuI7`#Mv0oTi9wec93L_Djqsc%p0FbHW}p+VVm|bSUjKd(YxTK}e%>3!OGC+_j7ZO_2ODCMc?K2dT4JXkEiI9}%@31} z{AK4mzD7?cGkMvogg;03$RS zuHPcoT+x8F5~Hj`f(636P@O6KyjGD^X)$6sD$BZWS|m1KO=|Lp?ma0E!7lUKmn^yU zWZgb!HD&47JJQupCkEIO1(6?2;uE|!LpkDjBj1KNsE9&ba^p>q34aaR%wAcjw2Z1&(?#{*CkZ!3$ zvSGd7=Y4a81S$GYa2T+nj`qHRsKSDlI(mf=FVf&@-)8yg!y|jCt9}Yw4hp`lcSlRz zUmSO>fJX*THFlAjdH?1%@k0DKjT!-ovn%jKN>-Y=&sIcw_vrRhbJ;wF z%1v_m3(3Y#>k~O)ffM%83PPOEl!(U)G_D8i%g2RA=%6wV#8wSFe#yyLe!IEX@A4C=5bsg0qFU54U#?(HR4fXR_1%R@k##DW%@OHb+K84KRh`d$ z1(%Nxyq}2pn5IuDH5s_~{GqH>LKfk&T;ZzcEvCyIhT{kohi`D+`!s#|cdl(8bydIM z@>kvMiG7SpMOd2iTzi_;NdJwxu;gPPuiL}Ip1#-nf{mZ!ihK^(U07u^tIgGF{mV<8 zr%esc&aAw;a#2n#6@xqWl$|Hum!GR^am|eU4O-vU_*@ zd_X>@uj{#u;#VswcM)6JBG**v+d39`gKN#Up9?PF?1d{F#P3QiIP|;St|9eQZC6!N zT@8Pbw62{?H2E@11P5nQfzoYRk0c{;ZQ1ZUN$}U)@rPQO$JvxuKk^|0Kc!xNCYD^# z>QzsEkL((1DRt7zmvFaJ!T(xx8I8}LPWspdN3P7PQxw0`Td;B;aB$vQWMd+7XY5%k zx4FZg*@akcyLXuHFis_FeZcEg9B43RB5J;H&qL)^W!d$Nh-=rF@U%r&n7c;b$5G8wP2bGyAH)BQRVE>~ldL8NS z^x?Q#Iq5L?QL@nBmr5PqkdKa}0&c?ES#uNP*~z zoazzfTw#q>zdWN-Xnv zD`n_RO0&jCblje7jTeBQL{rkR=saGim1Nm>;ECc+CJ}_KOZ^TP6#?jnhTFZCq?fcj-4jnruP0@@oby>JC8A(l4<>Zjs4($&{H?y{)r0Ho* zulYR=&EbEatv(ilRci5b^Sf>1vD4hV_VO||DrKElQDD4=rO@T0B@Uu^Duqg$N74GI zYVF&lqFCtm6|Swgc0u-HR2AWjWbk~n1Zlr&lu?)q7hFL;_*$nv)}lL*7t<#9Kt)Rq z{$BpW0{;<*lig}3(M{I9)_#Fh7aL|xmO3%FcM?|OLW=P_p29!ZI0_{$NSq`0Q0G3% zMBP*~i5OINuG6eGb7&^QVM-24yd7`^*K^Zkd(MR4dtm(-&ukzTY zkGe8amw#{hYUE8FM4jN>(1v4C!_ePJfX?p#DL4$wdIzXMkK5G%H;7jakj9aav*Dhm zfh7>cGNy=wlT*b#XCpns$7l>vqA@6415iTcnl%tYP-8NSIEnsb#tm{ag0E`;LacgP zFsK&bizDZu05@v@9H?X;UGkd_!$I|0fDR6eU109x>CBR~y}nc?<#?o&&& z$PMLQf*x3u)?k(poR$>5L!wA8+dm5%jn??>FdEp?1du{Lx)Xo2ROkMYWUef1B06(Ur&}(p}QHNfcj``2WZLvIXBSip8a5y7q_8!`` zr+%Pr8z2vEhQrCv%4*(2eo;B60z)h2jEJ{FEUx^NMYjShkV_Go<+PnL;x_dDf#djKU*qptbB=6 zM%sa4>>ZGS-qlm)(t+M8kj?c!E=2cERdZJ?N^qtF^ICsJm(4uD2;>%)mexq*U+a9a z6H;SS&?+w&(+RLarln|>P<+acI{_+)k#|9isr8gO4`Gp=EutG*h?+PRW*4!D&xC%o zAh(MaI7yIhPJazbMvTn}DtANMa`X$MgHGL;Q3AW6npt`f-UD!fVtm;Dn0-bITS90- z6zWF22MRY-(IF40s)PN{O&E<9jBjELh^=h?8gl`ypq$VOC)oP{8}F=7`45l)JUkVG zJ^(b3KZs^;o}IFp519Mm5Y624PMK;i=9azL3o-qgQ0(y5T&huKqhYJidC-@Aht7XWn);T+)aKJ;4-QuhPg*a^&k;N5=A z*+8J-toR=&ssa#zjs2MI|D^{of;0U9A@En;O_%_I~4pq00=-01tk1Oa0ml+1~CF@@_&S%;b6uf=3Z_dgl7Hm zDfn#=V22FwhoIrGBLPr61)x7$nQIWlYKsDqLjV_)la>A-ugDm%eh5=MjV^u@3xK3A z01l9M7_)@Z!w~$Eh=IIkj-T@XW6}N`EFK2Y*$>mj9_K@C34Lqd@9r+Jxu{s{&(B#j;!4D;(W_rDbo0h4_z0IWm9C`tl++VVES+bs z9`8IGzEon9j8SWPN8YfSa>}}cmp&x**%SRZ4U0sf*|j(m7BD{~g&-j8Sh(XH3wz_0O?RCJJ0& zycT(vu>my+|DD+Qqssjg1&I!^nj(EFjUT6^b|uhrO^FSTbcma69H)-5m>LE0r{jXT zvG3vrC6GmEY!~UdnzY@rDO0Ukim)^W-4$v%89}}LX#Y4yeU&(CN!o}t(e#c`IR6V0 z-5ab!7$e?u?PZMYR~ut{=i1lTXS{K84UP)O7i?O#>`TWP-8yd##*t>tWgw5qs4jiq z3sk>YlVoUJI4?P*S{J=zXgS6*+EhSVE!D8%QxF&>+ADSBqN#}dK<+acIi?7cYgFsx zK*Ad-HL?JnlN`V$jkMwg5uFXcE2p%(d5>-tYpc;;)46qPyCPE0*=k*8U+DTJoTHYC zH|8l`E8!Hr)!-UhjCp4}W0JHCp;X8H=|u`!U{>wU*I5B6rZ}g>!bnNVS@c8Zm;an( zj8>TX=tN5|aXq!gvMdYBjQnb9wZW#dC85&j{+-#^4Xcuzb48u+3SEF?i@osV*3g6{ zT=|$}3WnjyV1v7JnNNC029@JBJ?>h&!@v5U>7G+i`>E)uuZ=yJW+k!ue3U$|UF;LP z|3V<2EG!6J(jsqa???I?RjH_=+?|R`7=J08C?l8Bn^&`_0))Y6nlzB zP+g!gE@6|uxugWQlyt$m6q#COlraHK3eYY_;kq%*l160$9P=k#LC6Tc#3`W^lrI&X}q!L!b6let6rbRm)E-s#2vtdp#8qBr8vs4FFyWsOq>E4spV6a zq@AR!F=~uWls;xFD^f!_a$gPPX2J)&KhD-YU)P#(;4F~KixPTjIUrtFVQG@a?>NYi zmHOQ1PgWC9t|mt_l-Q|KB1pdu`kgbwldyC~l8u#i zz9@fGq3`-aM88=ou(;{m2##_`BxnAO+2Ryw+hqBRk(#-Ud(AGVLylKWzZUVPxm9EB zyLM}a!q|Aq_U=7-jZ7u7sFM9;L2`l5;)?8foYyr>thEeFn3>H=82dX0!#Rvbe}GKV z8d*L15zLXBTI4=cM)j30IT5BKVrT3_bWT!EmsVfUby1_fs+yc-c^`qZr;lmSmFuxV zc{^C0$t2a5Peztx-w!la)Z8S)&4`k^6bZy^9+8K_t9k z7~3$m({`7eJXqKoq_#J3vHu7Oy+#kd7BzZyD(FJkZ6iLCn8p4lR1`o34(ipUcQd;N0Xft&ibcSPwt1y_N(YsA5Y>)$P2sC|tn=kIb;QNmhO* zO`SG?F`OeU7LZW7JRBEXUKREkg#qWojs*Ay&ZLXxk!oJd9qBN=h$~>gPma7zUxGP4 zxnO^cO}FWC2ESBT<`sCQFH^{iD7}&`a@f~~Npzc+J~TP!{eQ-8f9^vM;AzA79el&*`9NZ%)!=4L?b!c2_*5STq zP)wFT&HTe1WrSfx_=Y z-ltA=vAvw7{H7DaEh^0PU5&KmZfYYBl;=OxbAHCMg!0Aq;{^Prmc$E}D{Lh)b#>#E;4vjeEHiVjC>PL z{r-Zb#6@4}LNcc^9PjILNvX{B9)XCqp}`b+*U*1<7W1`GquyGPIzjuT$gl)%w<-tS zz&Zu8E=h{$;QV)2tkI=EzDt;8z|Z8JS85gwwN&7cjhk&^zKbubE`QZ*b#n3ghz;ws zk+;?}QCF+8uk4p@>Cu+1Ub!(_k=r#q=VDTQyh5oBHi5Jcuf}nGEm3C5i}Y7oBY%0; z^j*q~!SrD1&0)if7NzX&UAxS-BF3IaUH!?|yo`EStpCt{WRS;WtKyl1&ZCz$it;`&y9 znjJ@6Fl$&0-2#e_>l&4>(nJVLbHXFi*7)Ox z72i~8U>tPICDuhNs;^=6kf zEhi~@b7!uF9(p6iA6Ui)a%|wVhjSv_#2bM&ZXsk#_AX}&kA9l&lNm#r`>aW zlBa9uZ)b3{?eh=*nIv3fKz_R44IXFIiqa5gU>4?M71nDANBLcZRaAIml5G?WOOC5f zaQ#Xf6Tucz%XGnLvXi3z@(X#Ld7hHdgfO$g4I70l2j-Qt6SmfF&I@@}8h!&_U|-+_ zl_$$hKDFV6`GVo$(+ZvSJqyQas&DEXABc3S{GO6#xhWOJs2NR@R@dc;`M$BO>3KW% zOL@)4TA_j=fOAL`xvQ@#Iu$3SEtq1XqARiP&9quhu1sA(tt$~KiDLiwKG4=AmreGb zlW_>|^uI0b%0>_0pvO9V^kBD>WTWv2S*#z-t!rsNyu2NlkS`?qZ+C87B7&TD zp*Tl;y*OZ7LB->Hp=|c0d-FGnnxoG%c*<1GuJjgFQ8ReC6xUxTVKP8TokI75PjYFD z1vKs_EvMUV=h0A17jftw)edg(Ozy+A)sO%fRRgewti!|B;e=lV^oxA44hJmq z062mH2{P0G=io?Cy#|oyLo&c%up_X){~mMZDV+HqX0CI#K7li3S&RT#T!YOpDpn5HYb59VlT`fQdRSu|y5(ID) z5I&88;%8ob<8fBX-$i@Tkj{(WKTda8SEvpOqv0iB(5nt$hBCzx&@K_-MObJKGflFv zf|T`8-6cMdxgOwvoRamBQ&9k~&3@w0C32b-OeMH3Tm3(q{_IpFBy;TR{gN%Mv6glg zPF^CGu7{RB$imiW@XKQ1?&jv?_=kb20V?sz_?N-e#tr*h#%t^TIWrS;(76E+BCN!K zRq%H+WiY?uZ5+(4u)-cTSWoPoKl1n+vx2(~06E(Ot6x@(jk&#()o&AsY6Q^i>$blP zZdfn3zn5c9aF9CuayZ|?5=x1^g4P+&ZozZ7@uE!- zN^!yGT5=sCUjpKG1v8s~lhA5~tXaXSCTJ_qdw{VV@Z&U?J2oEJ-&OJQU96x$Gi1;h zB^vNfT~vp;GD+co_OOTn%xnd?!EsXf;n4(NHbdn?1&Kmp3vdkDdb$<};iV6}*INJ@ zh}jaDxB-Fjf|UoXjldjj4_Jl?{ODm>R4XLh3^)*?o#96gg=oLO=9BV}V9|uqe|5IK*zZLF`Gx0sB-2XFkj_OAyKj4}`5&ILo16-VO=ciw8nOJ3tL($z1-c zWYG>mI|%n1M6n}S!Qu|6t-=Ba!fXezIZwqPfu<7@ zUS2v7zK9_xLG4b$YXKT`La8jS69pQqmnGKz_fCN{7Eov(A(YMeAXM7|@#_s>>w-d8 z?h}ObP$nP3Fe{%hm|OO!1Qds+-sYd&Na(#dZG<1T7NQO9QJMJRI4!5h909zj;L6>UeNsy_Z zcvwXGAsGCe2+^Q-Kk?8$AV5q95sDm!FZV&kfAmAex84&KZcuoD_;||=Kz8b-pPi6- zk30g#3=mh5NKo*bKb6S=;>n^V1^&ET>{SP#~ BU7Y{` diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index 0fbe47c7403d2b2182ec7e18456c5b718331f172..23530892fe8d07c09791538a4ed13cd0f1e45596 100644 GIT binary patch delta 5061 zcmY+IRa_MB--dT#=#WMhq@+8fq(P(v1nEY)JCs-?L=;%07NkQ!kVd+e?k<%QkY?#n z5dR~;gZK09$#uN4FF%s!my(A@KqD|BFl&LZV&YYNCNsuM9S4092!uuo z8D9)&!cAPgzl)OHELptT5lZ%{vT637yW^J>w_DJ<@X?V?6a8>*+tiYb?EO;~1S4;0 z+|AWKpBx!PUUeWtc3!B_5OQ_AN07r_)nctZm~0%A*HUuqLUqKm6qgm!v$BcTravP} z`A(Zh@BQ&UmPxWuTfuUT+UFletai3-+SD;~dhpRvZnmlb;BY9G#4a1KHM61;d zzYNe2i(9>5o7Y)-*YGQ~P{^c8=kqH%*-v50&qZtIjkt}6TvBiw)k+Bbh^;NZu@@cQ zaE=QVd@=CY*}U9F^r2Nf^XeC}C($LHsuEKbmKua#ZC1^_ zzpnejVKqUGfZEGvhdMShhE>c4)d`H!@K2BHlpadTS}UoxyZ@+XWy-D#+qNS;r2MF? zlr+$&n7Vpn&!O|aOf7_6j=Nf|XKT9)GkAVKD}!xw$%my7MHw0}TRb^_D#X3>b|64d zCk&}Al#g>?-<2R2`M_!ZO$-%#wTR2(sj87Z`1hKc)sXHEH|F>2jy!`sTR(DFxQ}8C zg33$Cd~!C#x`XR!tEM`*+?;Fm0%?A$*2HbJ&(;c8M*1qA`iuo>X^Kp|QavGy$g0q1 z+*&JK=%S7>^^QG;0m;WE@8dev9?PhNWIPNWGb>!ZN$^}r8DY6BpG4S|tlIk0Op1D; z;K_>{zm#WwdDg3&_s)8s=jtb$x``;Kgyv?)ez0B9T`5Kq{_(rN#?@$PpKIi}5ws;9DQoC@aNs%1K=cmetBBf6I z$QT*p=YI4uM4tjXFyim?=-bgvIIc^Io4}XHaBES#e+N(fOoBz49_@!=S_s6d%1c(6 z=5zEc5@J1AxqD3&Y>!}X!^Re>m@&6-3C51Xtm_t9)iV!C`F_c*oUvSgeE;b>W#wJt z`l9>07AF(eF9I$T->MnuGQO(F+CosZWQDBwo66p+y33ZGD@v+()REv{tqkjZ)Y{YvhUPOfL=ujlvJy8Q7YUH|R=yG6Gk zN21V~zJtNjvH{U+tBo&WxCJawHCrxt>3$Z9KCLgpTcobPxcrW@!gTPO>$)$EPi2#Pkn+!1?D#-9(L*U7 z6qS~AB7{RcPM*NI_3RxrksJMdSY%~?!7Iuquk@IhWf(^jP&njpn{@9m{XMf>FI|=odBQ+4No&EfntLP%C1!YyzSzD%r{l z3$^~YuNITT;%W0wCU-Myj_>T)(mUeLn&^*;27EAYP?_s4E~U^OHGV$|z{6|VBCCr} zenPhS)uYN8jj%YiV~Batjf=Y-Ikf48V!zYGp9d(f$MhXC4f>}=1KZ=(%a=Y-zOjN% zu_JRTBGMTDQ+#?~lc5Lt>vRW8Er8WjpH4@BCyqJx5WiQN-io^A^6BJ!X`Rh#%>yeF z@B5SrHtA1X@3WJa3{BsOf=@oJ_Z-KLNvN3U7pg+dY`@(WkHt9&1ETeIyxd+6o3&2MHb69mEN@IutV)yhr5w+ESvGMc^H!N=0t|BjnD& zytA3z-k*G&%F4wH1U=z9t~nKvH1v}5j+yhX-rh*jkikNZfKVN4LY70H;Jk@Mm?EXt zgrF|84llgpncVQF2nV-Gt$X?n-|VzENgYSOD4PB_2~|%;C8f)R?AcbgDLoLK}k~a<{a^OXO-S~7{#gNWe#(6g$(#=}Y$9WQxZ`&$Oa_hnnU&gf_6kC4l z=5S@^-Lf-CKeYT{qM+jcgH8MktCd((ylC~W+(-81ZRglHzs;WCipq#C^ekw$aKgW`p8~J;6-zu z@eym1fj7P4@if(ht|UU*!D|=8`LkvKyR}(Dc+IbLTFZ4R+^f4Gtx;=nc>Stzi$xRt zNVnu}o0PN0=5NAvdiPTL%Q%0qjVHB?9Ogm3w`z8nus7-7Kyk}aOAg&WJHVUs``9jy zEo(am2JJ%qMC)+1=KeC36^73hCsY&tVW=+A=oqp((vJekFNQD4Y#vAGAZLmBRgDPb z_>NbTTSH$H3QPf6iU`#z{Jk)we>=Hg}8TcRd$P$Q~_;4}nj zDo9U6;aBT~V)|ElHWr$Zy_&JjB8z9D`O;&yh0obaP5Xe@H!^|V#)*}K(v_U$GqYlF z&)l?6WhGIvsJgrddOv6?QFF}5HtjxX#cw&xEZIYzYmy#VO)z;|3%7B2{7-O2K3@q9ZHQGQH{9{=) z5fw(=tW{5nrVkQ|Z^=l5b@wMf>uImyy2K-Eh4Eg)F@RKrPnILURpOgr>1^8g=; zW{7TFJ}_Uo%sU-;lvKy(6{|j>O3XLg+ZSRpOE0k};ni9l9M!*B5(DFAZVwqL?KYad zNVSBQPhO`K&CREo&9L$^tOnzq%7#j;re+F$OBq17c5PtneX!Fl`XZ$?nHCB2_N{+; zz#m(rSM#7VVd?euHc?%1lvwN^hrqf0yVRl!kNqk*^0lw*UP5qy42* z@bJ@u3M=1Pba^;tmEXBgg+Vmh@zq}X_MZmgy>B;qn1Us-!)8gzeut4viEOcT;ZBM( zugyrc6m5q>mUpqZDvDx%sy5Kv*a|X+Ubso&QY))N9T&Py2BM?P@wN@k0uV>`L6l5} za0LJS-C@oiKbHQD)9^vz(mPW+e;)?sb90f7-C)sR#9f_jBH^Vaoh^4I!~KZE8Us-h zOP5!U!cT%EkDMd}yG>^*y*^$K%GWp^vmWv0<&nTsV~gR})k!h4c;6fEanrF!}jlUO+Q%_qBzA zyLoHC*|Q4jDfw4a$;aH&1pPtW{r8IfKQf_8^jJl4YY$28Dx{gXpy%_WLgyV3lHAPir3q(Clr=-nB@!cJwBXqn z{Cj#nf5b(tH=mtvj#|NJr0q75P&*RNP)gn4fgs)*fgzcC@(nf1of`TSsj?8Uz*C6u zoqlPHRRS%g1BCF5+*-jWs6^zP>vQGYaCwBVvyE#;eot1DfXq`M`>FSk3%K4-HVDdYU+(PS_VQJ32(!Df>J6TSQ?$3+5u!a<22p zo_u9@3;mYy_&tAGNw;4s$@4oJ@a>ERzd-!ce#u}BL=|PgnO4@Ug7f{HCyS(ivpO*f zUNSKoY%tIgc)^DDtL=n=ac`}MEC5g@y6T+E72=ZPZA@a^u<+Cj-@eu-XOL;Qc@XS*&yUZw_ zy>z(~$>~`-0Z&){(~gik`06*S)1pXU+2XeT z1#mIHNCVBL_cx&L9d3O39R8_3a}@KSYY+4NbmJgtIo;wF?5~)l^L3;>F`I+Q8e44D z2%*rS?kP{1B!Q~9+!fhsX_L*EUN?bYgya>(ZeINRco}pm!i^{;^BKJij$3R{d4&>b zl=u0F*xsp_%+;FH`N6W5{Fjm)j-shh-{$yv&$45G5~Cq!T)a_IKe)+@-{z02VGLPe z)vOk=nc=Aw*2QeKqSR)UxpUK6p3z5hCCG1l>6sYRJ|E>Pavl3{_^=mJ@uJY!mWFgv zJN^e(cQt=A$IihNL}jqC4lFHSD*Jn#o2@XWStGZEIx2au2=C8O#*B>!stMCANVxGs zT1D6RT7*3r&`&HVpl~gQHi`|j=!`8>eSqsAt1C1($a`_QobKwNs?0-5=5$ugVwc8v zllxiPz53Ccn!ao-Gr=SyHqu!pRGWD-yFp!7!Vjmulba3%EWRZdyAVcfCMPcLt?tzO za^^7iC{E-qmAOXHo5*~Qt~|xraEwZ;--lcF?bj}=Yw9~YnDBHon-u3<)4fvnuhv*@ z<%{X$>a0?>SM~dwN@WS)uP;w?jfR5QqqutfWudS&gdp*lT%1vq`+caSM3_duF2;rz zP!!)I{!&&=9NHx@yv}jO=P0Jl`qi7(IZeWp@D z1;Ga-K8h??Iq+xlW-${ot}QB!7EUMvEZVeJDTX0eP#sSdh7Yv3BNw)BkZd2;Qg>fZ zF<+iev7c8q)4@)^&)+bQUi!Pd4a{0Nxj4^DhvK*F7Ro-vqqbv`;9wasNW3@@@~(8y zn#<@+`ze8G{(2xgW9RQtpmNdTMcfU}Q*|f?1%v_ufgls=0AVQP{TK|nQU`ECAxQjs zKphH6WT1i}J?a52P+e$X$S?JPI9Q_V0VxpN4YzP;0F=SrQxJw6Yyeom;-CR|^e+*I zAvGKSC5hi9VaV7Y?2(W>3r;UIdnCvRSkXlW*C9g6JiD&}&!Lq#xPy>PA z3}}KdY6c9!(fGeGf321}9(g|3Akn6fVC%5bNoWEUwE*R=|112CUyKk?LkQft& zWbFYSf{|qpU=E_a=XUOcCfM-x-Zl(&pojMYieNqN4f>B>;4$d2(V#2z{kwfg_YBZ8 z|MR83+ch5c1A1T+-w)`6*z5;PK~&y=bLIoLH!o}8wmBQPZFB~2@73qQ+atUoKnol< z`VXIm{ykmf(a`O>^zHx*sWbdNPiR%0NpGC^xV#$2mQ|Y z?N$HD2BXk%KnRR##{cb8BuPFP(M;T4i^WIKttW1m$}I%FZ{qe1aS%^(Xt#kPxT}{_k9NN$oGL5j^pD3m^OJr)iPZhE+ zJuNGnx1FO`TH|uBblhfzTP8}UeVV#;H%r)+D99X{{o#!%R?p$3`0^gs8bV)5$Zg-} zTCwcbN{VB$Oi^Rh&Ude!>3bEIo!a(d&k0L6M9hw^VT!+K_L7*!^v}fuwPfAyTvnW( z?Ym38Y&2+0ngMm6r5XJNk;f@%R9eGxB`-Zw^d*LnZL16LGg;V5`^#1@CNi7uE5cM9 zb`}_sTyzA#(=>KWmb?t+)JGxTlyg?KU}vyQ6O+SYyhD#r5;G}I3d6FRBC)P=jPZMt zxx{FwNc{z4E6#D0g`j*-6)U$!Tgu={&;I^W5E{|yrE+=Qt@FsEa+cMv*LDm`k-w5h zeo0At^Yk2}d%G#!+_iK~Zd{v?bYku}!!gxfLeU6s-3cziBuWm#FW$D3xI0q#K?%VY zZ*54oPYvKc!*wX13S7Ga+|kP^UzadC2vrxp*DpwQRDMr~+0e+=_P8d&?Zrkao#*d6`3Z1|9gEFOmtc2@%FMPoDJ*!vNS=Cb{Y19 z{o}i9tVt>htKN*vviGw)9jo%4*vYr;Tn@O5j%1N-{-^9Aeon~D0(D&>b*86sogUZc zkH+U5p<0*ZvQR8<##;R!RR!k~^XR;enbC$lp1)1Em}+V0Ly;!Bdo!_%oEKcSsHls2 zZhq$uTgM0~L&9MdopeP^0{n=>T>_^3(TWHsHA+?kMM85YzVq*NOlhQv^ zKbx8P3|=t7eht>1xJP~25Na%N_eb#CE8q2Wpf!#2=BLfPWF=W%WKalOp{f8P4VPP({x0Q2=!*BhIH%)U4HqM9(blP zzpR8Qxl{(pzyJCOWEHKY1GiS(fXr{7r|*OqYgSy-lw9IwD$e1eF*K}XJVP7yriMCO z@r5atn)zy}1KPp-b)`YMDx(DAn9KrZd8nR=&HC~_t`vvnz4YsJF`z?Q>J0h^xcjId zK1V^5TcM$d7i zDL9jLSlelX?RR$I;{}LqGsIHdNYLssp?2S3$&;r9QIshD-f={RP~&KwBjPp2lArzI znrTwd1Ajh8#Cjah$RQ0)d2-dBNnK_twGBmVVz_4;P2=_K6 z+4*?!mG@%$o|p?}c+!3WW3hrXi(rj(>W!H(N~1$6(B#yy$clVoP`Z+!w~y^B4csiq zQ&W}aAo`i=n-|T;dp-&%aSTi@eY1<>^R=eR)8wYhil^8f3zfG|y};3%Ksi&{TVI_~ zW9nNkVcG%5l()-IqG?Yg3f4Z`Z!A!B&sWz^Hmw{y>+rb|dAVkBR3eDMw#hYQ&vuE% z(sIE)>e*er*P4`x6@N3us71GA)VPay?(12*8kkqGv)fm&4im@Xu2@X{!Lupqq_b(3|5#CsHLM4E<-GpW zy?^L$%u=VR+4yzMMXLoNbFZtJPbJ*rYSYyI?jl-b-=>0U@@k>t}&@ApO=T@ITWyKPUczPkGpkmFC9A4z?GhD+-tjWy@m~%kmuo+sWq)gpEH6o zU!f=$mDN<8z(!Oz#BA}Q@M|#_pN3$TawUr>^lukV676oIOIT9pC%@!wLcHE6cwFK# zZdc6{fyca7ht`F#Mb;;pR2)%5wp-_6-GLqg&(|KBLVTWlsezPt)JifW?EF@I=MWz` zL*^iAz6*$7rLhzZ2rXFaL5j4ld|}+gvK9=a0Fo3h95<>j3JT@b;ZKIXP(}8w&bV9i zZA661L@Cdq)9U?ni*W&d(W8%C6{^UE3dO>+(R?di!|PquS2YIfE`9H55#e>gZyue` z>YC~JW-%!-Dgi7?Pk5t`5dBkC*>;jX*T+Kj#}u;z#l<9KDSe{I&%{L8mwwp&@Zdic ziW?9J%G6GDxG!J~Mq1qOu>%HGIzQv5nAn@%o(kLuXnFN%3cAkIuuc>Dt>}BN?#=Up z&Ej_6>zzn;=Ds$@YCoOHSgo~h%{*I99MM84!)Vbk_@+$hj~aK`*T%-RHea{rETU|q zxz*nwPm~%Z{obxA?XWQs-EEW(`6(8%y%Qc$akU4UXxJLBV?FucnqJ%KbJ?f9rcGFo)W{YE$HWTKz z9V)r~`_9v$VxGbb_~C8gp+r9Db;wsQj6sL>Ew6u`5zXmh?w`?1hMD zU|R9amL2LohI)z;)qm#edDjd-Yt z8c65%KE=*I`{5D!p{WV%8qD=aDRFJ<=$V0?iL{Pg<_l3l+{$*<7s@_AUg_kp%0G8{ zwMP*)$*sL4yr}DW;zyAElBGO1Q9b*_WU~Al$871#pLeQ5! zNBq;3qY5opxRo_tMpmFdCu&ir9~4^jl|3lWOI{$FX7BtEbwZhQ7NmH5*dtP8mUew5 z@W%%)MOd9l{~0;T>?x&4TV{-WPT`i5ky*#GII4D~{y`rxKi!*AM2ortmSD*hZZ1He+%;SL7!)1&jG! znr7AdyGCmQ6;rqv`>_Kzm3&Y39qBoDSHDN=MGbnPBZ2rK%p6?+hmDZV#QIvv#KaAi z-sXYz%M6V+Mwdqtyz5T0avTrgiLClb3^|0p0MzNhv3`Ja;m_)(gS}D}a{%r6QXJz`Womgt0tnFjNiuVsF%NHIPSCrp;o>^BlXZ|H3pJ`X? zpS#cIG6Y{!@E2M|Kjg4IGmh^--%K_>Se$v@qp#1qEX|tKkd5edx%qP5fGM%(Q6e+E z_bJMw=qC|rO#ho$Ci4CZcTyVt5Le0*`i(N`q>0e$vD<+}_IM)qCbCgES@pFs!Y+PV zxs0GS<^6mK{d@|>;TpTLZ*cF0>M;gaEH3%GzYzP9jGA%1yg+8Z{OPfZ&Xdzp<+pd9 ztyz_IB;8^OP-(D1DP*t|)q9@)BiH@7h=FFY?CM!? z$Ph$rH^M9fDbf9D`cPQ@w{HY)fvU^R ziLY)1_`%|2BcKF=xe3q&3qChF@%~K!3{-C!PJB%hAo_25ixYoLO7T3OfIDEj?I!>M z;?;ln_Fu?L0FYqlP5`t))Di%F5I{3v0dA4}mlGe*Oj?`E0OiDwHUqc8Dnkok1>#`~ za34f>3t$O?w-xXMfolc)L6oO~?E-Cp1L)0#py#&%j-Xo+K<8}-j6wHn2OfY>UI(LJ z?SK~O@D9Kp1o*Pc_{t8_M4l34oOsqw($QFU0?uH$wG*%fakUG02%<6>YWTbK*yO00po@LnLkFP9*iU{D-T~V1q<2>4hV{ zpvU(D8enrmEa*RbNk{0N4Z2nz$z%IS+pqQkreIfYKUgvCCtVM=AFu|a%0FO4H9$JX zQzn2D?>Imz=M9j`=L4kkGan>9)eHg#;2L0v1e2kEFBqRaM4Eud8(e%o^zZHBzdZt7 zWf-^t`r~0zdBhKl#)g6GU<4fj^gxV;f|1(@APsuX2J;>}Nm-^v2JC8Hh_`fG!BzG18~X_y%m~93#zQ_YQRW zanh?^7l8hFoOF$eg`j^K2Q&o8Ss)O|MacjEQv(9g1k?Zfy$#2!OaN9C&+7m%`X7DD B#~lCw diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 2e7a659f..00422fe1 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -8,6 +8,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Middlewares; using Lumina.Presentation.Api.Common.Utilities; @@ -57,22 +58,22 @@ public class Program builder.Services.AddDataAccessLayerServices(); builder.Services.AddDomainLayerServices(); - // determine log path based on environment + // Determine log path based on environment. string logPath; if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true") { - logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path + logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // Use docker volume path. builder.WebHost.ConfigureKestrel(options => { - options.ListenAnyIP(5214); // HTTP only; also, the port is also the same port exposed in the Dockerfile + options.ListenAnyIP(5214); // HTTP only; also, the port is also the same port exposed in the Dockerfile. }); } else - logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path + logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // Use local binary path. Directory.CreateDirectory(logPath); if (!logPath.EndsWith(Path.DirectorySeparatorChar.ToString())) logPath = logPath += Path.DirectorySeparatorChar; - // set environment variable for Serilog configuration + // Set environment variable for Serilog configuration. Environment.SetEnvironmentVariable("LOG_PATH", logPath); builder.Host.UseSerilog((context, services, configuration) => @@ -85,7 +86,7 @@ public class Program app.UseSerilogRequestLogging(); - // apply any pending migrations + // Apply any pending migrations. using (IServiceScope scope = app.Services.CreateScope()) { IServiceProvider services = scope.ServiceProvider; @@ -94,8 +95,8 @@ public class Program LuminaDbContext context = services.GetRequiredService(); await context.Database.MigrateAsync(); - // enable the Write-Ahead Logging journal mode and a busy timeout, so that the Entity Framework connection and the dedicated connections - // used by the bulk data access operations of Dapper can access the database concurrently, without database locking errors + // Enable the Write-Ahead Logging journal mode and a busy timeout, so that the Entity Framework connection and the dedicated connections + // used by the bulk data access operations of Dapper can access the database concurrently, without database locking errors. SqliteConnection sqliteConnection = new(context.Database.GetDbConnection().ConnectionString); sqliteConnection.Open(); using SqliteCommand sqliteCommand = sqliteConnection.CreateCommand(); @@ -113,7 +114,7 @@ public class Program app.UseRouting(); app.UseCors("SecurePolicy"); - app.UseApiExceptionHandling(); // catches any unhandled exception and returns a ProblemDetails response + app.UseApiExceptionHandling(); // Catches any unhandled exception and returns a ProblemDetails response. //app.UseHttpsRedirection(); @@ -130,7 +131,7 @@ public class Program config.Endpoints.ShortNames = true; }); - // add API documentation (OpenApi/Scalar) + // Add API documentation (OpenApi/Scalar). app.MapOpenApi(); app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json"); // this is needed for API versioning to work correctly with Scalar app.MapScalarApiReference(scalarOptions => @@ -138,22 +139,28 @@ public class Program scalarOptions.WithTitle("Lumina API") .WithTheme(ScalarTheme.BluePlanet) .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient) - //.WithFavicon() // TODO: enable when favicon is added + //.WithFavicon() // TODO: enable when favicon is added. .WithDotNetFlag(true); }); - // add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked, - // and NOT for the health probes, which would otherwise begin a database transaction on every probe + // Add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked, + // and NOT for the health probes, which would otherwise begin a database transaction on every probe. app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware()); - // create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API + // Create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API. string mediaRootDirectoryPathSetting = app.Configuration.GetValue("MediaSettings:RootDirectory") ?? string.Empty; string mediaRootPath = Path.Combine(AppContext.BaseDirectory, mediaRootDirectoryPathSetting); if (!Directory.Exists(mediaRootPath)) Directory.CreateDirectory(mediaRootPath); - // ensure the default file system structure is present + // Wipe the temporary directory, so that it cannot grow across restarts. + string readingCachePath = ReadingCachePaths.GetRootDirectory(); + if (Directory.Exists(readingCachePath)) + Directory.Delete(readingCachePath, recursive: true); + Directory.CreateDirectory(readingCachePath); + + // Ensure the default file system structure is present. using (IServiceScope scope = app.Services.CreateScope()) { IServiceProvider services = scope.ServiceProvider; @@ -177,7 +184,7 @@ public class Program app.MapHub("/scanProgressHub"); - // the liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable + // The liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable. app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false, diff --git a/src/Lumina.Presentation.Web/Common/DTO/Plugins/LibraryBookReaderDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Plugins/LibraryBookReaderDto.cs new file mode 100644 index 00000000..3f2bbf3a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Plugins/LibraryBookReaderDto.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Plugins; + +/// +/// Data transfer object for a book reader configured for a media library. +/// +[DebuggerDisplay("Name: {Name}")] +public class LibraryBookReaderDto +{ + /// + /// Gets or sets the unique identifier of the plugin providing the book reader. + /// + public Guid PluginId { get; set; } + + /// + /// Gets or sets the display name of the book reader. + /// + public string Name { get; set; } = string.Empty; + + /// + /// Gets or sets the file extensions supported by the book reader. + /// + public List SupportedExtensions { get; set; } = []; + + /// + /// Gets or sets whether the book reader is enabled for the media library. + /// + public bool IsEnabled { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingAvailabilityDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingAvailabilityDto.cs new file mode 100644 index 00000000..65fc8887 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingAvailabilityDto.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Reading; + +/// +/// Data transfer object for the reading availability of a book. +/// +[DebuggerDisplay("BookId: {BookId}, IsAvailable: {IsAvailable}")] +public class ReadingAvailabilityDto +{ + /// + /// Gets or sets the Id of the book whose reading availability is reported. + /// + public Guid BookId { get; set; } + + /// + /// Gets or sets the Id of the media library the book belongs to. + /// + public Guid LibraryId { get; set; } + + /// + /// Gets or sets whether the book can be opened for reading. + /// + public bool IsAvailable { get; set; } + + /// + /// Gets or sets the code of the error preventing the book from being read, when it cannot be read. Can be when the book is available. + /// + public string? ErrorCode { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingManifestDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingManifestDto.cs new file mode 100644 index 00000000..43e8a1f1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingManifestDto.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Reading; + +/// +/// Data transfer object for the reading manifest of a book. +/// +[DebuggerDisplay("Title: {Title}")] +public class ReadingManifestDto +{ + /// + /// Gets or sets the title of the book. + /// + public string Title { get; set; } = string.Empty; + + /// + /// Gets or sets the author of the book, if known. + /// + public string? Author { get; set; } + + /// + /// Gets or sets the resource key of the cover image of the book, if applicable. + /// + public string? CoverResourceKey { get; set; } + + /// + /// Gets or sets the hierarchical table of contents of the book. + /// + public List TableOfContents { get; set; } = []; + + /// + /// Gets or sets the ordered spine of the reading sections of the book. + /// + public List Spine { get; set; } = []; + + /// + /// Gets or sets the resource keys of the resources of the book. + /// + public List ResourceKeys { get; set; } = []; + + /// + /// Gets or sets whether the book has extractable text content. A scanned book, whose pages are only images, has no text content. + /// + public bool HasTextContent { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingSectionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingSectionDto.cs new file mode 100644 index 00000000..f5ed6129 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingSectionDto.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Reading; + +/// +/// Data transfer object for the content of a reading section of a book. +/// +[DebuggerDisplay("LocationRef: {LocationRef}")] +public class ReadingSectionDto +{ + /// + /// Gets or sets the opaque location reference of the reading section. + /// + public string LocationRef { get; set; } = string.Empty; + + /// + /// Gets or sets the title of the reading section, if known. + /// + public string? Title { get; set; } + + /// + /// Gets or sets the sanitized HTML content of the reading section, ready to be rendered by the client. + /// + public string ContentHtml { get; set; } = string.Empty; +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingSpineItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingSpineItemDto.cs new file mode 100644 index 00000000..633f6fa3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingSpineItemDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Reading; + +/// +/// Data transfer object for an item of the spine of the reading manifest of a book. +/// +[DebuggerDisplay("LocationRef: {LocationRef}")] +public class ReadingSpineItemDto +{ + /// + /// Gets or sets the opaque location reference of the reading section. + /// + public string LocationRef { get; set; } = string.Empty; + + /// + /// Gets or sets the title of the reading section, if known. + /// + public string? Title { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingTocEntryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingTocEntryDto.cs new file mode 100644 index 00000000..7f159cef --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Reading/ReadingTocEntryDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Reading; + +/// +/// Data transfer object for an entry of the table of contents of the reading manifest of a book. +/// +[DebuggerDisplay("Label: {Label}")] +public class ReadingTocEntryDto +{ + /// + /// Gets or sets the label of the table of contents entry. + /// + public string Label { get; set; } = string.Empty; + + /// + /// Gets or sets the opaque location reference of the reading section the entry points to. + /// + public string LocationRef { get; set; } = string.Empty; + + /// + /// Gets or sets the child entries of the table of contents entry. + /// + public List Children { get; set; } = []; +} diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs index d38be3b3..01e56548 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs @@ -40,4 +40,17 @@ public class UserSettingsDto /// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. ///
public bool ShouldAggregateMetadataWhenMissing { get; set; } + + /// + /// 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. + /// + public bool ShouldRenderPdfAsImages { get; set; } + + /// + /// 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. + /// + public bool ShouldPreserveBookStyles { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 8391fee4..ddd8275a 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -9,7 +9,6 @@ using Lumina.Presentation.Web.Common.Http; using Lumina.Presentation.Web.Common.Localization; using Lumina.Presentation.Web.Common.Security; using Lumina.Presentation.Web.Common.Services; -using Lumina.Presentation.Web.Common.Validation; using Lumina.Presentation.Web.Core.Themes; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; @@ -19,7 +18,6 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization.Routing; -using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.DependencyInjection; @@ -40,13 +38,13 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Common.DependencyInjection; /// -/// Contains all services of the Presentation Web layer. +/// Utility class for registering the services of the Presentation Web layer into the Dependency Injection container. /// [ExcludeFromCodeCoverage] public static class PresentationWebLayerServices { /// - /// Registers the services of the Presentation Web layer into the dependency injection container. + /// Registers the services of the Presentation Web layer into the Dependency Injection container. /// /// The service collection to add the services to. /// The updated . @@ -58,11 +56,11 @@ public static class PresentationWebLayerServices .AddJsonOptions(jsonOptions => { jsonOptions.JsonSerializerOptions.MaxDepth = 256; - jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures + jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // Needed because file system API responses can have very nested structures. jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); - // configure the locations where the Razor view engine looks for views and layouts, since the views live under the Core directory + // Configure the locations where the Razor view engine looks for views and layouts, since the views live under the Core directory. services.Configure(razorViewEngineOptions => { razorViewEngineOptions.ViewLocationFormats.Clear(); @@ -70,17 +68,17 @@ public static class PresentationWebLayerServices razorViewEngineOptions.ViewLocationFormats.Add("/Core/Views/Shared/{0}.cshtml"); }); - // configure the JSON serialization settings used by Results.Json, so that the JSON responses of the endpoints match the MVC responses they replace + // Configure the JSON serialization settings used by Results.Json, so that the JSON responses of the endpoints match the MVC responses they replace. services.Configure(jsonOptions => { jsonOptions.SerializerOptions.MaxDepth = 256; - jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures + jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // Needed because file system API responses can have very nested structures. jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); - // register the FastEndpoints library, which replaces the MVC controllers for handling the application routes + // Register the FastEndpoints library, which replaces the MVC controllers for handling the application routes. services.AddFastEndpoints(); - // add OpenAPI document generation, so that the endpoints exposed by the web application are discoverable and their contracts are visible + // Add OpenAPI document generation, so that the endpoints exposed by the web application are discoverable and their contracts are visible. services.AddOpenApi(); services.SwaggerDocument(documentOptions => { @@ -98,9 +96,9 @@ public static class PresentationWebLayerServices documentOptions.RemoveEmptyRequestSchema = true; documentOptions.ShortSchemaNames = true; }); - // configure URL-based localization + // Configure URL-based localization. services.AddLocalization(localizationOptions => localizationOptions.ResourcesPath = "Core/Resources"); - // resolve the resources of the views that live under the Core/Views directory + // Resolve the resources of the views that live under the Core/Views directory. services.AddSingleton(); services.Configure(requestLocalizationOptions => @@ -122,57 +120,57 @@ public static class PresentationWebLayerServices requestLocalizationOptions.SupportedCultures = supportedCultures; requestLocalizationOptions.SupportedUICultures = supportedCultures; - // configure route-based culture provider + // Configure route-based culture provider. RouteDataRequestCultureProvider routeDataRequestCultureProvider = new() { RouteDataStringKey = "culture", UIRouteDataStringKey = "culture", Options = requestLocalizationOptions }; - // make the route culture provider the first one to be evaluated + // Make the route culture provider the first one to be evaluated. requestLocalizationOptions.RequestCultureProviders = [ - routeDataRequestCultureProvider, // keep route-based culture handling - new CookieRequestCultureProvider(), // but also add cookie option, so the application "remembers" the last used language the next time it's opened + routeDataRequestCultureProvider, // Keep route-based culture handling, + new CookieRequestCultureProvider(), // but also add cookie option, so the application "remembers" the last used language the next time it's opened. new AcceptLanguageHeaderRequestCultureProvider() ]; }); - // configure cookie-based authentication + // Configure cookie-based authentication. services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(cookieAuthenticationOptions => { - // basic path configuration + // Basic path configuration. cookieAuthenticationOptions.LoginPath = "/auth/login"; cookieAuthenticationOptions.LogoutPath = "/auth/logout"; cookieAuthenticationOptions.AccessDeniedPath = "/auth/access-denied"; - // cookie configuration + // Cookie configuration. cookieAuthenticationOptions.Cookie = new CookieBuilder { - Name = ".Lumina.Auth", // unique name to avoid conflicts - HttpOnly = true, // prevent JavaScript access + Name = ".Lumina.Auth", // Unique name to avoid conflicts. + HttpOnly = true, // Prevent JavaScript access. SameSite = SameSiteMode.Strict, - SecurePolicy = CookieSecurePolicy.Always, // require HTTPS - Path = "/", // make cookie available for all paths - IsEssential = true // mark as essential for GDPR + SecurePolicy = CookieSecurePolicy.Always, // Require HTTPS. + Path = "/", // Make cookie available for all paths. + IsEssential = true // Mark as essential for GDPR. }; - // security settings + // Security settings. cookieAuthenticationOptions.ExpireTimeSpan = TimeSpan.FromHours(24); // TODO: perhaps make it configurable by user? cookieAuthenticationOptions.SlidingExpiration = true; - // handle validation to support various deployment scenarios + // Handle validation to support various deployment scenarios. cookieAuthenticationOptions.Events = new CookieAuthenticationEvents { - // handle redirects to work with different base paths + // Handle redirects to work with different base paths. OnRedirectToLogin = redirectContext => { HttpContext httpContext = redirectContext.HttpContext; string culture = httpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us"; string? lastDisplayedView = httpContext.Session.GetString(HttpContextItemKeys.LAST_DISPLAYED_VIEW); - // build the login path considering reverse proxy and subfolder scenarios + // Build the login path considering reverse proxy and subfolder scenarios. string? originalHost = httpContext.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? httpContext.Request.Host.Value; string? originalScheme = httpContext.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? httpContext.Request.Scheme; string? originalPathBase = httpContext.Request.Headers["X-Forwarded-Prefix"].FirstOrDefault() ?? httpContext.Request.PathBase.Value; @@ -226,8 +224,8 @@ public static class PresentationWebLayerServices }; }); - // add authorization policies that ensure the application is initialized with the super admin account before allowing access, - // and that restrict access based on the roles and permissions retrieved from the remote API + // Add authorization policies that ensure the application is initialized with the super admin account before allowing access, + // and that restrict access based on the roles and permissions retrieved from the remote API. services.AddAuthorizationBuilder() .AddPolicy(AuthorizationPolicies.REQUIRE_INITIALIZATION, authorizationPolicyBuilder => authorizationPolicyBuilder.Requirements.Add(new InitializationRequirement())) .AddPolicy(AuthorizationPolicies.REQUIRE_ADMIN_ROLE, authorizationPolicyBuilder => @@ -241,7 +239,7 @@ public static class PresentationWebLayerServices authorizationPolicyBuilder.RequireAuthenticatedUser(); }); - // add forwarded headers middleware to handle reverse proxy scenarios + // Add forwarded headers middleware to handle reverse proxy scenarios. services.Configure(forwardedHeadersOptions => { forwardedHeadersOptions.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; @@ -249,15 +247,15 @@ public static class PresentationWebLayerServices forwardedHeadersOptions.KnownProxies.Clear(); }); - // configure session management to maintain user-specific data across requests + // Configure session management to maintain user-specific data across requests. services.AddSession(sessionOptions => { - sessionOptions.IdleTimeout = TimeSpan.FromMinutes(30); // session expires after 30 minutes of inactivity - sessionOptions.Cookie.HttpOnly = true; // prevent JavaScript access to session cookie, for security - sessionOptions.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance + sessionOptions.IdleTimeout = TimeSpan.FromMinutes(30); // Session expires after 30 minutes of inactivity. + sessionOptions.Cookie.HttpOnly = true; // Prevent JavaScript access to session cookie, for security. + sessionOptions.Cookie.IsEssential = true; // Mark session cookie as essential, for GDPR compliance. }); - // scan the current assembly for validators and register them as singletons in the DI container + // Scan the current assembly for validators and register them as singletons in the DI container. foreach (Type validatorType in typeof(Program).Assembly.GetTypes()) { if (validatorType.IsInterface || validatorType.IsAbstract || validatorType.IsGenericTypeDefinition) @@ -273,16 +271,16 @@ public static class PresentationWebLayerServices } } - // handle transient errors like network timeouts or intermittent failures + // Handle transient errors like network timeouts or intermittent failures. AsyncRetryPolicy retryPolicy = Policy .Handle() .OrInner(apiException => - apiException.HttpStatusCode != HttpStatusCode.BadRequest && // do not retry Bad Request and Forbidden responses, it's pointless + apiException.HttpStatusCode != HttpStatusCode.BadRequest && // Do not retry Bad Request and Forbidden responses, it's pointless. apiException.HttpStatusCode != HttpStatusCode.Forbidden) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); - // use a circuit breaker to prevent repeatedly calling a failing service + // Use a circuit breaker to prevent repeatedly calling a failing service. AsyncCircuitBreakerPolicy circuitBreakerPolicy = Policy .Handle() .OrInner(apiException => apiException.HttpStatusCode == HttpStatusCode.InternalServerError) @@ -290,7 +288,7 @@ public static class PresentationWebLayerServices AsyncPolicyWrap policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy); - // register the HTTP typed client used for the API interaction + // Register the HTTP typed client used for the API interaction. services.AddHttpClient() .AddHttpMessageHandler() .AddHttpMessageHandler() @@ -301,7 +299,7 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddScoped(); - // enable access to the current HTTP context in non-controller classes + // Enable access to the current HTTP context in non-controller classes. services.AddHttpContextAccessor(); services.Configure(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024); @@ -320,7 +318,7 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddSingleton(); services.AddSingleton(); - services.AddHybridCache(); // used for caching authorization roles, permissions, policies and theme data + services.AddHybridCache(); // Used for caching authorization roles, permissions, policies and theme data. return services; } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs index f6925745..d0c41d9f 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs @@ -16,7 +16,7 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Presentation.Web.Common.DependencyInjection; /// -/// Contains the OpenTelemetry services of the Presentation Web layer. +/// Utility class for registering the OpenTelemetry services of the Presentation Web layer into the Dependency Injection container. /// [ExcludeFromCodeCoverage] public static class PresentationWebTelemetryServices @@ -24,10 +24,10 @@ public static class PresentationWebTelemetryServices private const string SERVICE_NAME = "Lumina.Web"; /// - /// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container. + /// Registers the OpenTelemetry services of the Presentation Web layer into the Dependency Injection container. /// /// The service collection to add the services to. - /// Application configuration properties. + /// The configuration used to read the application configuration. /// The hosting environment of the application. /// The updated . public static IServiceCollection AddPresentationWebTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment) @@ -54,8 +54,8 @@ public static class PresentationWebTelemetryServices tracingBuilder.SetSampler(CreateSampler(traceSampleRatio)); tracingBuilder.AddSource(WebTelemetry.SOURCE_NAME); tracingBuilder.AddAspNetCoreInstrumentation(); - // the HTTP client instrumentation emits spans and metrics for the calls to the API, and injects the W3C trace context - // into their headers, so that the API continues the same trace across the two separately deployed applications + // The HTTP client instrumentation emits spans and metrics for the calls to the API, and injects the W3C trace context + // into their headers, so that the API continues the same trace across the two separately deployed applications. tracingBuilder.AddHttpClientInstrumentation(); if (isConsoleExporterEnabled) tracingBuilder.AddConsoleExporter(); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathParentRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathParentRequest.cs index c3bb5a7c..2adf85a3 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathParentRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/GetPathParentRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; /// /// Represents the request for retrieving the parent path of a file system path. /// -/// The path for which the parent path is retrieved. +/// The path for which the parent path is retrieved. Required. [DebuggerDisplay("Path: {Path}")] public record GetPathParentRequest( string? Path diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs index 78885a93..fe26fcd2 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs @@ -7,8 +7,8 @@ namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Thumbnail /// /// Represents a request for retrieving the thumbnail of a file system file. /// -/// The path of the file for which the thumbnail is retrieved. -/// The quality to use for the thumbnail. +/// The path of the file for which the thumbnail is retrieved. Required. +/// The quality to use for the thumbnail. Required. [DebuggerDisplay("Path: {Path}")] public record GetThumbnailRequest( string? Path, diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/EditLibraryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/EditLibraryRequest.cs index 93b666b7..7c84ab5c 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/EditLibraryRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/EditLibraryRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.Management; /// /// Represents the request for displaying the media library editing view. /// -/// The unique identifier of the media library to edit. +/// The unique identifier of the media library to edit. Required. [DebuggerDisplay("Id: {Id}")] public record EditLibraryRequest( Guid Id diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetArtworkProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetArtworkProvidersRequest.cs index f53a3f16..e7dc201a 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetArtworkProvidersRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetArtworkProvidersRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.Management; /// /// Represents the request for retrieving the artwork providers of a media library. /// -/// The unique identifier of the media library whose artwork providers are retrieved. +/// The unique identifier of the media library whose artwork providers are retrieved. Required. [DebuggerDisplay("LibraryId: {LibraryId}")] public record GetArtworkProvidersRequest( Guid LibraryId diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetBookReadersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetBookReadersRequest.cs new file mode 100644 index 00000000..047c2905 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetBookReadersRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents the request for retrieving the book readers of a media library. +/// +/// The unique identifier of the media library whose book readers are retrieved. Required. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetBookReadersRequest( + Guid LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetMetadataProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetMetadataProvidersRequest.cs index ca866ef0..9b206b59 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetMetadataProvidersRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetMetadataProvidersRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.Management; /// /// Represents the request for retrieving the metadata providers of a media library. /// -/// The unique identifier of the media library whose metadata providers are retrieved. +/// The unique identifier of the media library whose metadata providers are retrieved. Required. [DebuggerDisplay("LibraryId: {LibraryId}")] public record GetMetadataProvidersRequest( Guid LibraryId diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs index 79725234..d3596561 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// /// Represents a request to get a book by the specified Id. /// -/// The unique identifier of the book to retrieve. +/// The unique identifier of the book to retrieve. Required. [DebuggerDisplay("Id: {Id}")] public record GetBookRequest( Guid Id diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequest.cs index 7ec4de40..fc704c99 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// /// Represents the request for displaying the books browsing view. /// -/// The unique identifier of the media library whose books are browsed. +/// The unique identifier of the media library whose books are browsed. Optional. [DebuggerDisplay("LibraryId: {LibraryId}")] public record GetBooksViewRequest( Guid? LibraryId diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequest.cs new file mode 100644 index 00000000..2dfe972b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents a request to check the reading availability of a book. +/// +/// The unique identifier of the book whose reading availability is checked. Required. +[DebuggerDisplay("BookId: {BookId}")] +public record GetBookReadingAvailabilityRequest( + Guid BookId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequest.cs new file mode 100644 index 00000000..51bcd1ae --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents a request to get the reading manifest of a book. +/// +/// The unique identifier of the book whose reading manifest is retrieved. Required. +[DebuggerDisplay("BookId: {BookId}")] +public record GetBookReadingManifestRequest( + Guid BookId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequest.cs new file mode 100644 index 00000000..e9fc548e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents a request to get a resource of a book, for reading. +/// +/// The unique identifier of the book whose resource is retrieved. Required. +/// The opaque resource key of the resource. Required. +[DebuggerDisplay("BookId: {BookId}, ResourceKey: {ResourceKey}")] +public record GetBookReadingResourceRequest( + Guid BookId, + string ResourceKey +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequest.cs new file mode 100644 index 00000000..b26565d8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents a request to get the content of a reading section of a book. +/// +/// The unique identifier of the book whose reading section is retrieved. Required. +/// The opaque location reference of the reading section. Required. +[DebuggerDisplay("BookId: {BookId}, LocationRef: {LocationRef}")] +public record GetBookReadingSectionRequest( + Guid BookId, + string LocationRef +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequest.cs new file mode 100644 index 00000000..55a73d55 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; + +/// +/// Represents the request for displaying the reading view of a book. +/// +/// The unique identifier of the book to read. Required. +[DebuggerDisplay("BookId: {BookId}")] +public record ReadBookViewRequest( + Guid BookId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs new file mode 100644 index 00000000..4098cf1e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Plugins; + +/// +/// Represents a request to enable or disable a book reader for a media library. +/// +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public class SetBookReaderEnabledRequest +{ + /// + /// Gets or sets the Id of the media library whose book reader is enabled or disabled. Required. + /// + public Guid LibraryId { get; set; } + + /// + /// Gets or sets the unique identifier of the plugin providing the book reader. Required. + /// + public Guid PluginId { get; set; } + + /// + /// Gets or sets whether the book reader should be enabled for the media library. Required. + /// + public bool IsEnabled { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/DeleteThemeRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/DeleteThemeRequest.cs index 60f6fb80..5a1563b8 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Themes/DeleteThemeRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/DeleteThemeRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Themes; /// /// Represents a request to delete a theme. /// -/// The manifest id of the theme to delete. +/// The manifest id of the theme to delete. Required. [DebuggerDisplay("ThemeId: {ThemeId}")] public record DeleteThemeRequest( string? ThemeId diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeArchiveRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeArchiveRequest.cs index 56705036..7583598c 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeArchiveRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeArchiveRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Themes; /// /// Represents a request to download the archive of a theme. /// -/// The manifest id of the theme to download. +/// The manifest id of the theme to download. Required. [DebuggerDisplay("ThemeId: {ThemeId}")] public record GetThemeArchiveRequest( string? ThemeId diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeAssetRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeAssetRequest.cs index 6d3f040b..c157dae5 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeAssetRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeAssetRequest.cs @@ -7,8 +7,8 @@ namespace Lumina.Presentation.Web.Common.Requests.Themes; /// /// Represents a request to get an asset file of a theme. /// -/// The manifest id of the theme. -/// The asset path relative to the theme pack root. +/// The manifest id of the theme. Required. +/// The asset path relative to the theme pack root. Required. [DebuggerDisplay("ThemeId: {ThemeId}, Path: {Path}")] public record GetThemeAssetRequest( string? ThemeId, diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs index 0ded5c46..f331eef2 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Themes; /// /// Represents a request to restore a soft deleted bundled theme. /// -/// The manifest id of the bundled theme to restore. +/// The manifest id of the bundled theme to restore. Required. [DebuggerDisplay("ThemeId: {ThemeId}")] public record RestoreThemeRequest( string? ThemeId diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/SetCurrentThemeRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/SetCurrentThemeRequest.cs index 81c7c2ac..9c947c52 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Themes/SetCurrentThemeRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/SetCurrentThemeRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.Requests.Themes; /// /// Represents a request to set the currently active theme. /// -/// The manifest id of the theme to activate. +/// The manifest id of the theme to activate. Required. [DebuggerDisplay("ThemeId: {ThemeId}")] public record SetCurrentThemeRequest( string? ThemeId diff --git a/src/Lumina.Presentation.Web/Common/Requests/Tools/SetLanguageRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Tools/SetLanguageRequest.cs index 2db72ecc..fd8201aa 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Tools/SetLanguageRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Tools/SetLanguageRequest.cs @@ -7,8 +7,8 @@ namespace Lumina.Presentation.Web.Common.Requests.Tools; /// /// Represents the request for setting the culture used by the application. /// -/// The new culture to set. -/// The URL to return to, after setting the new culture. +/// The new culture to set. Required. +/// The URL to return to, after setting the new culture. Optional. [DebuggerDisplay("NewCulture: {NewCulture}, ReturnUrl: {ReturnUrl}")] public record SetLanguageRequest( string? NewCulture, diff --git a/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/Authentication/LoginViewRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/Authentication/LoginViewRequest.cs index a9dda6d5..6fa27d41 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/Authentication/LoginViewRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/Authentication/LoginViewRequest.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication /// /// Represents the request for displaying the account login view. /// -/// The URL to return to, after login. +/// The URL to return to, after login. Optional. [DebuggerDisplay("ReturnUrl: {ReturnUrl}")] public record LoginViewRequest( string? ReturnUrl = null diff --git a/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/LoginRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/LoginRequest.cs index bca229e8..de0d572e 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/LoginRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/UsersManagement/LoginRequest.cs @@ -10,7 +10,7 @@ namespace Lumina.Presentation.Web.Common.Requests.UsersManagement; /// The username of the account to authenticate. Required. /// The password of the account to authenticate. Required. /// The TOTP (Time-Based One-Time Password) of the account to authenticate. Optional. -/// The URL to return to, after login. +/// The URL to return to, after login. Optional. [DebuggerDisplay("Username: {Username}")] public record LoginRequest( string? Username = null, diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs index c3aa70eb..e1363258 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs @@ -11,5 +11,9 @@ public static partial class ApiRoutes public static class Books { public const string GET_BOOKS_LITE = "books/lite"; + public const string GET_BOOK_READING_MANIFEST = "books/{bookId}/reading/manifest"; + public const string GET_BOOK_READING_AVAILABILITY = "books/{bookId}/reading/availability"; + public const string GET_BOOK_READING_SECTION = "books/{bookId}/reading/sections/{locationRef}"; + public const string GET_BOOK_READING_RESOURCE = "books/{bookId}/reading/resources/{resourceKey}"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs index 91b14c52..63f358f4 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs @@ -27,5 +27,7 @@ public static partial class ApiRoutes public const string GET_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers"; public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers/reorder"; + public const string GET_LIBRARY_BOOK_READERS = "libraries/{libraryId}/book-readers"; + public const string SET_LIBRARY_BOOK_READER_ENABLED = "libraries/{libraryId}/book-readers/{pluginId}/enabled"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs index 1b5c58c2..9d52a31e 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs @@ -13,5 +13,10 @@ public static partial class WebRoutes public const string INDEX = "{culture}/library/written-content-library/books-library/books"; public const string GET_LIBRARY_ITEMS = "{culture}/library/written-content-library/books-library/books/api-get-library-items"; public const string EDIT_BOOK = "{culture}/library/written-content-library/books-library/books/{id}"; + public const string READ = "{culture}/library/written-content-library/books-library/books/{bookId}/read"; + public const string GET_READING_MANIFEST = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest"; + public const string GET_READING_AVAILABILITY = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability"; + public const string GET_READING_SECTION = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-section"; + public const string GET_READING_RESOURCE = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-resource"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs index 7159d3af..dd582a50 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs @@ -28,5 +28,7 @@ public static partial class WebRoutes public const string GET_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-get-artwork-providers/{libraryId}"; public const string SET_ARTWORK_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-artwork-provider-enabled"; public const string REORDER_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-reorder-artwork-providers"; + public const string GET_BOOK_READERS = "{culture}/libraries/manage/api-get-book-readers/{libraryId}"; + public const string SET_BOOK_READER_ENABLED = "{culture}/libraries/manage/api-set-book-reader-enabled"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs index 22a50431..5a313421 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs @@ -22,7 +22,11 @@ public class DeleteRoleEndpointSummary : Summary r.RoleId, "The unique identifier of the role to delete."); + RequestParam(r => r.RoleId, "The unique identifier of the role to delete. Required."); + + ExampleRequest = new DeleteRoleRequest( + RoleId: Guid.NewGuid() + ); Response(200, "The role is deleted.", example: new SuccessResponse(true)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs index 759f99f4..eab2dd9a 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointSummary.cs @@ -23,7 +23,11 @@ public class GetRolePermissionsEndpointSummary : Summary r.RoleId, "The unique identifier of the role whose permissions are retrieved."); + RequestParam(r => r.RoleId, "The unique identifier of the role whose permissions are retrieved. Required."); + + ExampleRequest = new GetRolePermissionsRequest( + RoleId: Guid.NewGuid() + ); Response(200, "The permissions of the role are returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointSummary.cs index 1c69055e..99f5e3c5 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointSummary.cs @@ -22,7 +22,11 @@ public class DeleteThemeEndpointSummary : Summary r.ThemeId, "The manifest id of the theme to delete."); + RequestParam(r => r.ThemeId, "The manifest id of the theme to delete. Required."); + + ExampleRequest = new DeleteThemeRequest( + ThemeId: "neon-grid" + ); Response(200, "The theme was successfully deleted.", example: new SuccessResponse(true)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointSummary.cs index 112f6b51..41f6f04b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointSummary.cs @@ -21,7 +21,11 @@ public class DownloadThemeEndpointSummary : Summary r.ThemeId, "The manifest id of the theme to download."); + RequestParam(r => r.ThemeId, "The manifest id of the theme to download. Required."); + + ExampleRequest = new GetThemeArchiveRequest( + ThemeId: "lumina-default" + ); Response(200, "The ZIP archive of the theme is returned.", "application/zip"); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs index e7811d5d..3a86b213 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs @@ -22,7 +22,11 @@ public class SetCurrentThemeEndpointSummary : Summary r.ThemeId, "The manifest id of the theme to activate."); + RequestParam(r => r.ThemeId, "The manifest id of the theme to activate. Required."); + + ExampleRequest = new SetCurrentThemeRequest( + ThemeId: "lumina-default" + ); Response(200, "The theme was successfully activated.", example: new SuccessResponse(true)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs index d9646c0e..de546114 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointSummary.cs @@ -23,7 +23,11 @@ public class GetUserPermissionsEndpointSummary : Summary r.UserId, "The unique identifier of the user for whom to get the authorization permissions."); + RequestParam(r => r.UserId, "The unique identifier of the user for whom to get the authorization permissions. Required."); + + ExampleRequest = new GetUserPermissionsRequest( + UserId: Guid.NewGuid() + ); Response(200, "The permissions of the user are returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs index 4711f3e7..16b2f206 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs @@ -23,7 +23,11 @@ public class GetUserRoleEndpointSummary : Summary r.UserId, "The unique identifier of the user for whom to get the authorization role."); + RequestParam(r => r.UserId, "The unique identifier of the user for whom to get the authorization role. Required."); + + ExampleRequest = new GetUserRoleRequest( + UserId: Guid.NewGuid() + ); Response(200, "The role of the user is returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs index acdde3fd..39adb453 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs @@ -23,8 +23,13 @@ public class GetDirectoriesEndpointSummary : Summary r.Path, "The file system path for which to get the directories."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + RequestParam(r => r.Path, "The file system path for which to get the directories. Required."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + + ExampleRequest = new GetDirectoriesRequest( + Path: "/media/movies/", + IncludeHiddenElements: true + ); Response(200, "The directories of the file system path are returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs index b1f4bbb7..db6da811 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs @@ -23,8 +23,13 @@ public class GetFilesEndpointSummary : Summary r.Path, "The file system path for which to get the files."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + RequestParam(r => r.Path, "The file system path for which to get the files. Required."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + + ExampleRequest = new GetFilesRequest( + Path: "/media/movies/", + IncludeHiddenElements: true + ); Response(200, "The files of the file system path are returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs index da341087..abe588aa 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs @@ -23,8 +23,13 @@ public class GetTreeFilesEndpointSummary : Summary r.Path, "The file system path for which to get the tree files."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not."); + RequestParam(r => r.Path, "The file system path for which to get the tree files. Required."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + + ExampleRequest = new GetTreeFilesRequest( + Path: "/media/movies/", + IncludeHiddenElements: true + ); Response(200, "The file system tree of the file system path is returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs index 6868b07c..edb14f0e 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs @@ -21,8 +21,13 @@ public class CheckPathExistsEndpointSummary : Summary r.Path, "The file system path to check the existence of."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden elements in the search results, or not."); + RequestParam(r => r.Path, "The file system path to check the existence of. Required."); + RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden elements in the search results, or not. Optional."); + + ExampleRequest = new CheckPathExistsRequest( + Path: "/media/movies/", + IncludeHiddenElements: true + ); Response(200, "Whether the file system path exists is returned.", example: new { success = true, data = new { exists = true } }); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs index 8403b28e..712724c9 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointSummary.cs @@ -22,8 +22,12 @@ public class GetPathParentEndpointSummary : Summary r.Path, "The path for which the parent path is retrieved."); + RequestParam(r => r.Path, "The path for which the parent path is retrieved. Required."); - Response(200, "The path segments of the parent path are returned.", example: new { success = true, data = new { pathSegments = new PathSegmentDto[] { } } }); + ExampleRequest = new GetPathParentRequest( + Path: "/media/movies/" + ); + + Response(200, "The path segments of the parent path are returned.", example: new { success = true, data = new { pathSegments = Array.Empty() } }); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs index 19ffc881..06fd4cdd 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointSummary.cs @@ -22,7 +22,11 @@ public class GetPathRootEndpointSummary : Summary r.Path, "The file system path for which to get the root."); + RequestParam(r => r.Path, "The file system path for which to get the root. Required."); + + ExampleRequest = new GetPathRootRequest( + Path: "/media/movies/" + ); Response(200, "The root of the file system path is returned.", example: new { success = true, data = new { root = new PathSegmentDto() } }); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs index 79708895..318d4d22 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointSummary.cs @@ -22,8 +22,12 @@ public class SplitPathEndpointSummary : Summary r.Path, "The file system path for which to get the path segments."); + RequestParam(r => r.Path, "The file system path for which to get the path segments. Required."); - Response(200, "The path segments of the file system path are returned.", example: new { success = true, data = new { pathSegments = new PathSegmentDto[] { } } }); + ExampleRequest = new SplitPathRequest( + Path: "/media/movies/" + ); + + Response(200, "The path segments of the file system path are returned.", example: new { success = true, data = new { pathSegments = Array.Empty() } }); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs index d27cf78d..4a5793ed 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointSummary.cs @@ -21,7 +21,11 @@ public class ValidatePathEndpointSummary : Summary r.Path, "The file system path to validate."); + RequestParam(r => r.Path, "The file system path to validate. Required."); + + ExampleRequest = new ValidatePathRequest( + Path: "/media/movies/" + ); Response(200, "Whether the file system path is valid is returned.", example: new { success = true, data = new { isValid = true } }); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs index eca5a54c..94a6443b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs @@ -22,8 +22,13 @@ public class CancelLibraryScanEndpointSummary : Summary r.LibraryId, "The unique identifier of the media library whose scan is cancelled."); - RequestParam(r => r.ScanId, "The Id of the scan to cancel."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library whose scan is cancelled. Required."); + RequestParam(r => r.ScanId, "The Id of the scan to cancel. Required."); + + ExampleRequest = new CancelLibraryScanRequest( + LibraryId: Guid.NewGuid(), + ScanId: Guid.NewGuid() + ); Response(200, "The scan of the media library is cancelled.", example: new SuccessResponse(true)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs index 7b5d012d..bc8a86fd 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs @@ -22,7 +22,11 @@ public class DeleteLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library to delete."); + RequestParam(r => r.Id, "The unique identifier of the media library to delete. Required."); + + ExampleRequest = new DeleteLibraryRequest( + Id: Guid.NewGuid() + ); Response(200, "The media library is deleted.", example: new SuccessResponse(true)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs index b4db6b5e..6a7acc2d 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs @@ -21,7 +21,11 @@ public class EditLibraryViewEndpointSummary : Summary r.Id, "The unique identifier of the media library to edit."); + RequestParam(r => r.Id, "The unique identifier of the media library to edit. Required."); + + ExampleRequest = new EditLibraryRequest( + Id: Guid.NewGuid() + ); Response(200, "The view for editing the media library is rendered."); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointSummary.cs index 33e85d64..3bc963e8 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointSummary.cs @@ -23,7 +23,11 @@ public class GetArtworkProvidersEndpointSummary : Summary r.LibraryId, "The unique identifier of the media library whose artwork providers are retrieved."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library whose artwork providers are retrieved. Required."); + + ExampleRequest = new GetArtworkProvidersRequest( + LibraryId: Guid.NewGuid() + ); Response(200, "The artwork providers of the media library are returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpoint.cs new file mode 100644 index 00000000..7a244f8e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetBookReaders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-book-readers/{libraryId} route. +/// +public class GetBookReadersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetBookReadersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_BOOK_READERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the book readers of a media library. + /// + /// The request containing the Id of the media library whose book readers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBookReadersRequest request, CancellationToken cancellationToken) + { + LibraryBookReaderDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointSummary.cs new file mode 100644 index 00000000..4673ac07 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetBookReaders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetBookReadersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetBookReadersEndpointSummary() + { + Summary = "Retrieves the book readers of a media library."; + Description = "Retrieves the book readers of the media library identified by the request, with their supported file extensions and enabled state."; + RequestParam(r => r.LibraryId, "The Id of the media library whose book readers are retrieved. Required."); + + ExampleRequest = new GetBookReadersRequest( + LibraryId: Guid.NewGuid() + ); + + Response(200, "The book readers of the media library are returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs index 78d45f76..4ea5c5d7 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs @@ -23,7 +23,11 @@ public class GetMetadataProvidersEndpointSummary : Summary r.LibraryId, "The unique identifier of the media library whose metadata providers are retrieved."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library whose metadata providers are retrieved. Required."); + + ExampleRequest = new GetMetadataProvidersRequest( + LibraryId: Guid.NewGuid() + ); Response(200, "The metadata providers of the media library are returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs index 20c24430..5d29c1fc 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs @@ -23,7 +23,11 @@ public class ScanLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library to scan."); + RequestParam(r => r.Id, "The unique identifier of the media library to scan. Required."); + + ExampleRequest = new ScanLibraryRequest( + Id: Guid.NewGuid() + ); Response(200, "The scan of the media library is started.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs new file mode 100644 index 00000000..423d5292 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-set-book-reader-enabled route. +/// +public class SetBookReaderEnabledEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public SetBookReaderEnabledEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.LibraryManagement.SET_BOOK_READER_ENABLED); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + EnableAntiforgery(); + } + + /// + /// Enables or disables a book reader of a media library. + /// + /// The request containing the Ids of the media library and of the plugin, and whether the book reader is enabled. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetBookReaderEnabledRequest request, CancellationToken cancellationToken) + { + await _apiHttpClient.PutAsync(ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs new file mode 100644 index 00000000..b8bd8a76 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetBookReaderEnabledEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetBookReaderEnabledEndpointSummary() + { + Summary = "Enables or disables a book reader of a media library."; + Description = "Enables or disables the book reader of the media library identified by the request."; + RequestParam(r => r.LibraryId, "The Id of the media library whose book reader is enabled or disabled. Required."); + RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader. Required."); + RequestParam(r => r.IsEnabled, "Whether the book reader should be enabled for the media library, or not. Required."); + + ExampleRequest = new SetBookReaderEnabledRequest + { + LibraryId = Guid.NewGuid(), + PluginId = Guid.NewGuid(), + IsEnabled = true + }; + + Response(200, "The book reader of the media library is enabled or disabled.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs index f9024029..99d323d5 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs @@ -21,7 +21,11 @@ public class EditBookViewEndpointSummary : Summary r.Id, "The unique identifier of the book to edit."); + RequestParam(r => r.Id, "The unique identifier of the book to edit. Required."); + + ExampleRequest = new GetBookRequest( + Id: Guid.NewGuid() + ); Response(200, "The view for editing the book is rendered."); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs index 6a7bea8d..785fc1b5 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs @@ -2,7 +2,9 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Common; using Lumina.Presentation.Web.Common.Requests.Libraries; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -22,14 +24,26 @@ public class GetLibraryItemsEndpointSummary : Summary r.LibraryId, "The Id of the media library whose books are retrieved."); - RequestParam(r => r.CurrentPage, "Optional. The page of results to retrieve."); - RequestParam(r => r.PerPage, "Optional. The maximum number of books to retrieve per page."); - RequestParam(r => r.SearchTerm, "Optional. The search term used to filter results."); - RequestParam(r => r.FilterAlphaKey, "Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker."); - RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not."); - RequestParam(r => r.SortBy, "Optional. The name of the field by which to sort the results."); - RequestParam(r => r.SortOrder, "Optional. The direction in which to sort the results."); + RequestParam(r => r.LibraryId, "The Id of the media library whose books are retrieved. Required."); + RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); + RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional."); + RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); + RequestParam(r => r.FilterAlphaKey, "The alpha key used to filter the results by the first character of their title, for the alpha picker. Optional."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not. Optional."); + RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional."); + RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); + + ExampleRequest = new GetBooksLiteRequest + { + LibraryId = Guid.NewGuid(), + CurrentPage = 1, + PerPage = 48, + SearchTerm = "fellowship", + FilterAlphaKey = "f", + ShouldIgnoreThePrefixForAlphaPicker = true, + SortBy = "title", + SortOrder = SortOrder.Ascending + }; Response(200, "The lightweight details of the books of the media library are returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs index d384431e..9874ba4b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -12,6 +12,7 @@ using Lumina.Presentation.Web.Core.Themes; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Localization; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -85,6 +86,8 @@ public class BooksIndexViewEndpoint : BaseEndpoint ["libraryId"] = library.Id?.ToString() ?? request.LibraryId.Value.ToString(), ["itemsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS) ?? string.Empty, ["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty, + ["readUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) }) ?? string.Empty, + ["availabilityUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) }) ?? string.Empty, ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) } }; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs index cd6b461f..a7dd2636 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs @@ -21,7 +21,11 @@ public class BooksIndexViewEndpointSummary : Summary r.LibraryId, "Optional. The unique identifier of the media library whose books are browsed."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library whose books are browsed. Optional."); + + ExampleRequest = new GetBooksViewRequest( + LibraryId: Guid.NewGuid() + ); Response(200, "The view for browsing the books of the media library is rendered."); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs new file mode 100644 index 00000000..11655081 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Reading; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability route. +/// +public class GetReadingAvailabilityEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetReadingAvailabilityEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.GET_READING_AVAILABILITY); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Checks the reading availability of a book. + /// + /// The request containing the Id of the book whose reading availability is checked. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBookReadingAvailabilityRequest request, CancellationToken cancellationToken) + { + ReadingAvailabilityDto response = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), cancellationToken).ConfigureAwait(false); + return Results.Json(new { success = response.IsAvailable, errorCode = response.ErrorCode, libraryId = response.LibraryId }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs new file mode 100644 index 00000000..97322053 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetReadingAvailabilityEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingAvailabilityEndpointSummary() + { + Summary = "Checks the reading availability of a book."; + Description = "Checks whether the book 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."; + RequestParam(r => r.BookId, "The Id of the book whose reading availability is checked. Required."); + + ExampleRequest = new GetBookReadingAvailabilityRequest( + BookId: Guid.NewGuid() + ); + + Response(200, "The reading availability of the book is returned.", + example: new + { + success = false, + errorCode = "ReaderDisabled", + libraryId = Guid.NewGuid() + }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs new file mode 100644 index 00000000..7f154d9e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Reading; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest route. +/// +public class GetReadingManifestEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetReadingManifestEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.GET_READING_MANIFEST); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Retrieves the reading manifest of a book. + /// + /// The request containing the Id of the book whose reading manifest is retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBookReadingManifestRequest request, CancellationToken cancellationToken) + { + try + { + ReadingManifestDto response = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + catch (ApiException apiException) + { + // When the book has no available reader or its reader is disabled, the manifest cannot be produced at all; the reader view + // distinguishes this case from a generic failure and warns the user, so it is reported with a distinct error code instead of + // being flattened to a generic "NotFound" by the exception handling middleware. + if (apiException.ProblemDetails?.Detail is "NoReaderAvailable" or "ReaderDisabled") + return Results.Json(new { success = false, errorCode = apiException.ProblemDetails.Detail }); + throw; + } + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs new file mode 100644 index 00000000..9a853dae --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetReadingManifestEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingManifestEndpointSummary() + { + Summary = "Retrieves the reading manifest of a book."; + Description = "Retrieves the reading manifest of a book, containing the metadata, the table of contents, the spine, and the resources needed to render the reader."; + RequestParam(r => r.BookId, "The Id of the book whose reading manifest is retrieved. Required."); + + ExampleRequest = new GetBookReadingManifestRequest( + BookId: Guid.NewGuid() + ); + + Response(200, "The reading manifest of the book is returned."); + + Response(200, "The book cannot be read because no book reader is available for its format, or its book reader is disabled for the library.", "application/json", + example: new + { + success = false, + errorCode = "ReaderDisabled" + }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs new file mode 100644 index 00000000..1ff7295e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-resource route. +/// +public class GetReadingResourceEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetReadingResourceEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.GET_READING_RESOURCE); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Retrieves a resource of a book, for reading. + /// + /// The request containing the Id of the book and the resource key of the resource. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBookReadingResourceRequest request, CancellationToken cancellationToken) + { + BlobDataDto response = await _apiHttpClient.GetBlobAsync(ApiRoutes.Books.GET_BOOK_READING_RESOURCE + .Replace("{bookId}", request.BookId.ToString()) + .Replace("{resourceKey}", Uri.EscapeDataString(request.ResourceKey)), cancellationToken).ConfigureAwait(false); + // The resource is served without content sniffing, so that the browser never renders book content as anything but the media type the API declared. + HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff"; + return Results.Bytes(response.Data, response.ContentType); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs new file mode 100644 index 00000000..b541cc66 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetReadingResourceEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingResourceEndpointSummary() + { + Summary = "Retrieves a resource of a book, for reading."; + Description = "Retrieves the binary content of a resource of a book, such as an image or a font referenced by a reading section."; + RequestParam(r => r.BookId, "The Id of the book whose resource is retrieved. Required."); + RequestParam(r => r.ResourceKey, "The opaque resource key of the resource. Required."); + + ExampleRequest = new GetBookReadingResourceRequest( + BookId: Guid.NewGuid(), + ResourceKey: "cover-image" + ); + + Response(200, "The resource of the book is returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs new file mode 100644 index 00000000..705a20a4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Reading; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-section route. +/// +public class GetReadingSectionEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetReadingSectionEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.GET_READING_SECTION); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Retrieves the content of a reading section of a book. + /// + /// The request containing the Id of the book and the location reference of the reading section. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBookReadingSectionRequest request, CancellationToken cancellationToken) + { + ReadingSectionDto response = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_SECTION + .Replace("{bookId}", request.BookId.ToString()) + .Replace("{locationRef}", Uri.EscapeDataString(request.LocationRef)), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs new file mode 100644 index 00000000..293f49dc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetReadingSectionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetReadingSectionEndpointSummary() + { + Summary = "Retrieves the content of a reading section of a book."; + Description = "Retrieves the sanitized HTML content of the reading section of a book, ready to be rendered by the client."; + RequestParam(r => r.BookId, "The Id of the book whose reading section is retrieved. Required."); + RequestParam(r => r.LocationRef, "The opaque location reference of the reading section. Required."); + + ExampleRequest = new GetBookReadingSectionRequest( + BookId: Guid.NewGuid(), + LocationRef: "chapter-1" + ); + + Response(200, "The content of the reading section is returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpoint.cs new file mode 100644 index 00000000..021d641a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpoint.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/read route. +/// +public class ReadViewEndpoint : BaseEndpoint +{ + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.READ); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Displays the reading view of a book. + /// + /// The request containing the Id of the book to read. + /// Cancellation token that can be used to stop the execution. + public override Task ExecuteAsync(ReadBookViewRequest request, CancellationToken cancellationToken) + { + return Task.FromResult(View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml", request)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointSummary.cs new file mode 100644 index 00000000..1cc75348 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointSummary.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ReadViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ReadViewEndpointSummary() + { + Summary = "Displays the reading view of a book."; + Description = "Displays the reading view of the book identified by the request."; + RequestParam(r => r.BookId, "The Id of the book to read. Required."); + + ExampleRequest = new ReadBookViewRequest( + BookId: Guid.NewGuid() + ); + + Response(200, "The reading view of the book is displayed."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs index 70dfcd95..c98277a1 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointSummary.cs @@ -23,7 +23,11 @@ public class GetPluginSettingsEndpointSummary : Summary r.PluginId, "The unique identifier of the plugin whose settings are retrieved."); + RequestParam(r => r.PluginId, "The unique identifier of the plugin whose settings are retrieved. Required."); + + ExampleRequest = new GetPluginSettingsRequest( + PluginId: Guid.NewGuid() + ); Response(200, "The settings and their schema of the plugin are returned.", example: new SuccessResponse(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointSummary.cs index 96cbb9e4..3467d9a9 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointSummary.cs @@ -21,8 +21,13 @@ public class ThemeAssetsEndpointSummary : Summary r.ThemeId, "The manifest id of the theme."); - RequestParam(r => r.Path, "The asset path relative to the theme pack root."); + RequestParam(r => r.ThemeId, "The manifest id of the theme. Required."); + RequestParam(r => r.Path, "The asset path relative to the theme pack root. Required."); + + ExampleRequest = new GetThemeAssetRequest( + ThemeId: "lumina-default", + Path: "assets/style.css" + ); Response(200, "The asset file of the theme is returned.", "application/octet-stream"); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointSummary.cs index 33243485..85a6466b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointSummary.cs @@ -21,8 +21,13 @@ public class SetLanguageEndpointSummary : Summary r.NewCulture, "The new culture to set."); - RequestParam(r => r.ReturnUrl, "The URL to return to, after setting the new culture."); + RequestParam(r => r.NewCulture, "The new culture to set. Required."); + RequestParam(r => r.ReturnUrl, "The URL to return to, after setting the new culture. Optional."); + + ExampleRequest = new SetLanguageRequest( + NewCulture: "en-US", + ReturnUrl: "/" + ); Response(200, "The culture preference is stored in a cookie, and the browser is redirected back."); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointSummary.cs index 612c6bda..788d168a 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointSummary.cs @@ -21,7 +21,11 @@ public class LoginViewEndpointSummary : Summary r.ReturnUrl, "The URL to return to, after login."); + RequestParam(r => r.ReturnUrl, "The URL to return to, after login. Optional."); + + ExampleRequest = new LoginViewRequest( + ReturnUrl: "/" + ); Response(200, "The account login view is rendered."); } diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx index 1fb27bc8..741a2000 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx @@ -337,9 +337,18 @@ مزوّدو البيانات الوصفية المستخدمون لإثراء عناصر هذه المكتبة، بالترتيب الذي يتم تجريبهم به. - Artwork providers + مزوّدو الأغلفة - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + مزوّدو الأغلفة المستخدمون لاسترداد أغلفة عناصر هذه المكتبة، بالترتيب الذي يتم تجريبهم به. + + + قارئات الكتب + + + الامتدادات المدعومة + + + قارئات الكتب المستخدمة لقراءة كتب هذه المكتبة. القارئة المعطّلة تتيح للمستخدم معرفة أن هناك إضافة قارئ لهذا التنسيق، لكنها معطّلة. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx index 32e91b0a..21987d97 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx @@ -337,9 +337,18 @@ Die Metadatenanbieter, die verwendet werden, um die Elemente dieser Bibliothek anzureichern, in der Reihenfolge, in der sie versucht werden. - Artwork providers + Cover-Anbieter - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + Die Cover-Anbieter, die zum Abrufen der Cover der Elemente dieser Bibliothek verwendet werden, in der Reihenfolge, in der sie ausprobiert werden. + + + Buchleser + + + Unterstützte Erweiterungen + + + Die Buchleser, die zum Lesen der Bücher dieser Bibliothek verwendet werden. Ein deaktivierter Buchleser informiert den Benutzer darüber, dass ein Leser-Plugin für das Format existiert, es aber deaktiviert ist. \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx index 00b5c77e..d47047ec 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx @@ -342,4 +342,13 @@ The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + + Book readers + + + Supported extensions + + + The book readers used to read the books of this library. A disabled book reader lets the user know that a reader plugin exists for the format, but it is disabled. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx index e1ae5061..04413872 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx @@ -337,9 +337,18 @@ Los proveedores de metadatos utilizados para enriquecer los elementos de esta biblioteca, en el orden en que se prueban. - Artwork providers + Proveedores de portadas - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + Los proveedores de portadas utilizados para recuperar las portadas de los elementos de esta biblioteca, en el orden en que se prueban. + + + Lectores de libros + + + Extensiones compatibles + + + Los lectores de libros utilizados para leer los libros de esta biblioteca. Un lector deshabilitado le indica al usuario que existe un complemento de lectura para el formato, pero que está deshabilitado. \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx index ac0f6204..ed4be993 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx @@ -337,9 +337,18 @@ Les fournisseurs de métadonnées utilisés pour enrichir les éléments de cette bibliothèque, dans l'ordre où ils sont essayés. - Artwork providers + Fournisseurs de couvertures - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + Les fournisseurs de couvertures utilisés pour récupérer les couvertures des éléments de cette bibliothèque, dans l'ordre où ils sont essayés. + + + Lecteurs de livres + + + Extensions prises en charge + + + Les lecteurs de livres utilisés pour lire les livres de cette bibliothèque. Un lecteur désactivé indique à l'utilisateur qu'un plugin de lecture existe pour le format, mais qu'il est désactivé. \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx index 01ce6fbc..46276506 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx @@ -337,9 +337,18 @@ I fornitori di metadati utilizzati per arricchire gli elementi di questa libreria, nell'ordine in cui vengono provati. - Artwork providers + Fornitori di copertine - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + I fornitori di copertine utilizzati per recuperare le copertine degli elementi di questa libreria, nell'ordine in cui vengono provati. + + + Lettori di libri + + + Estensioni supportate + + + I lettori di libri utilizzati per leggere i libri di questa libreria. Un lettore disabilitato informa l'utente che esiste un plugin di lettura per il formato, ma che è disabilitato. \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx index 168e84d4..3aa161bc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx @@ -337,9 +337,18 @@ このライブラリのアイテムを補完するために使用されるメタデータプロバイダーを、試行する順序で指定します。 - Artwork providers + 表紙プロバイダー - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + このライブラリのアイテムの表紙を取得するために使用される表紙プロバイダーを、試行する順序で指定します。 + + + 書籍リーダー + + + 対応する拡張子 + + + このライブラリの書籍を読むために使用されるリーダーです。無効なリーダーは、その形式のリーダープラグインが存在するが無効になっていることをユーザーに知らせます。 \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx index 00b5c77e..d47047ec 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx @@ -342,4 +342,13 @@ The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + + Book readers + + + Supported extensions + + + The book readers used to read the books of this library. A disabled book reader lets the user know that a reader plugin exists for the format, but it is disabled. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx index c7408932..ba6dbf11 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx @@ -337,9 +337,18 @@ Furnizorii de metadate folosiți pentru a îmbogăți elementele acestei biblioteci, în ordinea în care sunt încercați. - Artwork providers + Furnizori de coperți - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + Furnizorii de coperți folosiți pentru a recupera coperțile elementelor acestei biblioteci, în ordinea în care sunt încercați. + + + Cititori de cărți + + + Extensii acceptate + + + Cititorii de cărți folosiți pentru a citi cărțile acestei biblioteci. Un cititor dezactivat îi permite utilizatorului să știe că există un plugin de citire pentru format, dar este dezactivat. \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx index bc8e1ab8..3e9bd7f4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx @@ -337,9 +337,18 @@ Постачальники метаданих, які використовуються для збагачення елементів цієї бібліотеки, у порядку, в якому вони випробовуються. - Artwork providers + Постачальники обкладинок - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + Постачальники обкладинок, які використовуються для отримання обкладинок елементів цієї бібліотеки, у порядку, в якому вони випробовуються. + + + Читачі книг + + + Підтримувані розширення + + + Читачі книг, які використовуються для читання книг цієї бібліотеки. Вимкнений читач повідомляє користувача про те, що для цього формату існує плагін для читання, але він вимкнений. \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx index 5c281a96..e0c4f2c6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx @@ -337,9 +337,18 @@ 用于丰富此库项目内容的元数据提供程序,按其尝试顺序排列。 - Artwork providers + 封面提供程序 - The artwork providers used to retrieve the covers of the items of this library, in the order they are tried. + 用于获取此库项目封面的封面提供程序,按其尝试顺序排列。 + + + 书籍阅读器 + + + 支持的扩展名 + + + 用于阅读此库书籍的阅读器。禁用的阅读器会让用户知道该格式存在阅读器插件,但该插件已被禁用。 \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx index 50bfc618..ca9830c2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -45,4 +45,10 @@ لا توجد عناصر تطابق الفلاتر الحالية + + لا يوجد قارئ كتب متاح يمكنه فتح هذا التنسيق من الكتب. + + + قارئ الكتب الذي يفتح هذا الكتاب معطل لهذه المكتبة. قم بتمكينه في إعدادات المكتبة لقراءة الكتاب. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx index e2208b8a..2fba039b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx @@ -45,4 +45,10 @@ Keine Einträge entsprechen den aktuellen Filtern + + Es ist kein Buchleser verfügbar, der dieses Buchformat öffnen kann. + + + Der Buchleser, der dieses Buch öffnet, ist für diese Mediathek deaktiviert. Aktivieren Sie ihn in den Mediathek-Einstellungen, um das Buch zu lesen. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx index f44c8d5a..93f29cbc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx @@ -45,4 +45,10 @@ No items match the current filters + + There is no book reader available that can open this book format. + + + The book reader that opens this book is disabled for this library. Enable it in the library settings to read the book. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx index ae88931b..7af89bbb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx @@ -45,4 +45,10 @@ Ningún elemento coincide con los filtros actuales + + No hay ningún lector de libros disponible que pueda abrir este formato de libro. + + + El lector de libros que abre este libro está deshabilitado para esta biblioteca. Habilítelo en la configuración de la biblioteca para leer el libro. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx index 5797b42e..79d38825 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx @@ -45,4 +45,10 @@ Aucun élément ne correspond aux filtres actuels + + Aucun lecteur de livres n'est disponible pour ouvrir ce format de livre. + + + Le lecteur de livres qui ouvre ce livre est désactivé pour cette bibliothèque. Activez-le dans les paramètres de la bibliothèque pour lire le livre. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx index 78cd6fbe..bdf944bd 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx @@ -45,4 +45,10 @@ Nessun elemento corrisponde ai filtri correnti + + Non è disponibile nessun lettore di libri in grado di aprire questo formato di libro. + + + Il lettore di libri che apre questo libro è disabilitato per questa biblioteca. Abilitalo nelle impostazioni della biblioteca per leggere il libro. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx index 2855a774..cf1308f1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx @@ -45,4 +45,10 @@ 現在のフィルターに一致する項目はありません + + この本の形式を開けるブックリーダーがありません。 + + + この本を開くブックリーダーは、このライブラリで無効になっています。ライブラリ設定で有効にすると本を読めます。 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx index f44c8d5a..93f29cbc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx @@ -45,4 +45,10 @@ No items match the current filters + + There is no book reader available that can open this book format. + + + The book reader that opens this book is disabled for this library. Enable it in the library settings to read the book. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx index cec2e1d0..244e911c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx @@ -45,4 +45,10 @@ Niciun element nu corespunde filtrelor curente + + Nu există niciun cititor de cărți disponibil care să poată deschide acest format de carte. + + + Cititorul de cărți care deschide această carte este dezactivat pentru această bibliotecă. Activați-l în setările bibliotecii pentru a citi cartea. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx index 208e64aa..e20352f4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -45,4 +45,10 @@ Жоден елемент не відповідає поточним фільтрам + + Немає доступного читача книг, який міг би відкрити цей формат книги. + + + Читач книг, який відкриває цю книгу, вимкнено для цієї бібліотеки. Увімкніть його в налаштуваннях бібліотеки, щоб читати книгу. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx index d8e628ba..de258336 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx @@ -45,4 +45,10 @@ 没有项目符合当前筛选条件 + + 没有可用的图书阅读器能够打开此图书格式。 + + + 打开此图书的图书阅读器已在此媒体库中禁用。在媒体库设置中启用它即可阅读该图书。 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx new file mode 100644 index 00000000..b06b1dad --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + رجوع + + + فهرس المحتويات + + + السابق + + + التالي + + + حجم الخط + + + جارٍ التحميل + + + تعذر فتح الكتاب للقراءة. + + + ملف PDF هذا مستند ممسوح ضوئياً بدون طبقة نص قابلة للاستخراج. فعّل إعداد «عرض ملفات PDF كصور» لعرضه كصور للصفحات. + + + لا يوجد قارئ كتب متاح يمكنه فتح هذا التنسيق من الكتب. + + + قارئ الكتب الذي يفتح هذا الكتاب معطل لهذه المكتبة. قم بتمكينه في إعدادات المكتبة لقراءة الكتاب. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.de-DE.resx new file mode 100644 index 00000000..1fa81857 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.de-DE.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Zurück + + + Inhaltsverzeichnis + + + Zurück + + + Weiter + + + Schriftgröße + + + Wird geladen + + + Das Buch konnte nicht zum Lesen geöffnet werden. + + + Dieses PDF ist ein gescanntes Dokument ohne extrahierbare Textebene. Aktivieren Sie die Einstellung 'PDFs als Bilder rendern', um es als Seitenbilder anzuzeigen. + + + Es ist kein Buchleser verfügbar, der dieses Buchformat öffnen kann. + + + Der Buchleser, der dieses Buch öffnet, ist für diese Mediathek deaktiviert. Aktivieren Sie ihn in den Mediathek-Einstellungen, um das Buch zu lesen. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.en-US.resx new file mode 100644 index 00000000..5b40414b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.en-US.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Back + + + Table of contents + + + Previous + + + Next + + + Font size + + + Loading + + + The book could not be opened for reading. + + + This PDF is a scanned document without an extractable text layer. Enable the 'Render PDFs as images' setting to view it as page images. + + + There is no book reader available that can open this book format. + + + The book reader that opens this book is disabled for this library. Enable it in the library settings to read the book. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.es-ES.resx new file mode 100644 index 00000000..40f7aab7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.es-ES.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Atrás + + + Tabla de contenidos + + + Anterior + + + Siguiente + + + Tamaño de fuente + + + Cargando + + + No se pudo abrir el libro para su lectura. + + + Este PDF es un documento escaneado sin capa de texto extraíble. Active la opción 'Mostrar PDF como imágenes' para verlo como imágenes de página. + + + No hay ningún lector de libros disponible que pueda abrir este formato de libro. + + + El lector de libros que abre este libro está deshabilitado para esta biblioteca. Habilítelo en la configuración de la biblioteca para leer el libro. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.fr-FR.resx new file mode 100644 index 00000000..9098a476 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.fr-FR.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Retour + + + Table des matières + + + Précédent + + + Suivant + + + Taille de police + + + Chargement + + + Le livre n'a pas pu être ouvert pour la lecture. + + + Ce PDF est un document scanné sans couche de texte extractible. Activez le réglage 'Afficher les PDF en images' pour l'afficher sous forme d'images de pages. + + + Aucun lecteur de livres n'est disponible pour ouvrir ce format de livre. + + + Le lecteur de livres qui ouvre ce livre est désactivé pour cette bibliothèque. Activez-le dans les paramètres de la bibliothèque pour lire le livre. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.it-IT.resx new file mode 100644 index 00000000..23fcd04e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.it-IT.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Indietro + + + Indice + + + Precedente + + + Successivo + + + Dimensione carattere + + + Caricamento + + + Il libro non ha potuto essere aperto per la lettura. + + + Questo PDF è un documento scansionato senza livello di testo estraibile. Abilitare l'impostazione 'Visualizza i PDF come immagini' per visualizzarlo come immagini di pagina. + + + Non è disponibile nessun lettore di libri in grado di aprire questo formato di libro. + + + Il lettore di libri che apre questo libro è disabilitato per questa biblioteca. Abilitalo nelle impostazioni della biblioteca per leggere il libro. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ja-JP.resx new file mode 100644 index 00000000..57473275 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ja-JP.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 戻る + + + 目次 + + + 前へ + + + 次へ + + + 文字サイズ + + + 読み込み中 + + + 本を開いて読むことができませんでした。 + + + このPDFは、抽出可能なテキストレイヤーのないスキャン文書です。「PDFを画像として表示」設定を有効にすると、ページ画像として表示できます。 + + + この本の形式を開けるブックリーダーがありません。 + + + この本を開くブックリーダーは、このライブラリで無効になっています。ライブラリ設定で有効にすると本を読めます。 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.resx new file mode 100644 index 00000000..5b40414b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Back + + + Table of contents + + + Previous + + + Next + + + Font size + + + Loading + + + The book could not be opened for reading. + + + This PDF is a scanned document without an extractable text layer. Enable the 'Render PDFs as images' setting to view it as page images. + + + There is no book reader available that can open this book format. + + + The book reader that opens this book is disabled for this library. Enable it in the library settings to read the book. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ro-RO.resx new file mode 100644 index 00000000..9bf0bf77 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ro-RO.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Înapoi + + + Cuprins + + + Înapoi + + + Înainte + + + Dimensiune font + + + Se încarcă + + + Cartea nu a putut fi deschisă pentru citire. + + + Acest PDF este un document scanat fără un strat de text extractibil. Activați setarea 'Afișează PDF-urile ca imagini' pentru a-l afișa ca imagini de pagină. + + + Nu există niciun cititor de cărți disponibil care să poată deschide acest format de carte. + + + Cititorul de cărți care deschide această carte este dezactivat pentru această bibliotecă. Activați-l în setările bibliotecii pentru a citi cartea. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.uk-UA.resx new file mode 100644 index 00000000..5a106bed --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.uk-UA.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Назад + + + Зміст + + + Назад + + + Вперед + + + Розмір шрифту + + + Завантаження + + + Не вдалося відкрити книгу для читання. + + + Цей PDF є сканованим документом без витягуваного текстового шару. Увімкніть налаштування «Відображати PDF як зображення», щоб переглядати його як зображення сторінок. + + + Немає доступного читача книг, який міг би відкрити цей формат книги. + + + Читач книг, який відкриває цю книгу, вимкнено для цієї бібліотеки. Увімкніть його в налаштуваннях бібліотеки, щоб читати книгу. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.zh-CN.resx new file mode 100644 index 00000000..a533cb42 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.zh-CN.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 返回 + + + 目录 + + + 上一页 + + + 下一页 + + + 字体大小 + + + 正在加载 + + + 无法打开此书进行阅读。 + + + 此 PDF 是扫描文档,没有可提取的文本层。启用“将 PDF 显示为图像”设置即可将其显示为页面图像。 + + + 没有可用的图书阅读器能够打开此图书格式。 + + + 打开此图书的图书阅读器已在此媒体库中禁用。在媒体库设置中启用它即可阅读该图书。 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx index 9620b02a..abc108be 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ar-SA.resx @@ -45,4 +45,16 @@ ما إذا كانت ملفات السمات التي يقدمها التطبيق مخزنة في الذاكرة المؤقتة أم لا. أوقف هذا الخيار أثناء تعديل ملفات السمات حتى تظهر التغييرات فورًا. + + عرض ملفات PDF كصور + + + ما إذا كانت كتب PDF تُعرض كصور للصفحات، مع الحفاظ على التخطيط الأصلي، ولكن مع جعل نص الصفحات غير قابل للتحديد أو البحث. هذا مفيد لملفات PDF الممسوحة ضوئياً التي لا تحتوي على نص قابل للاستخراج. + + + الحفاظ على أنماط الكتب + + + ما إذا كان يتم الحفاظ على التنسيق الأصلي لمحتوى الكتاب عند قراءته. يؤدي تفعيله إلى الاحتفاظ بمظهر الكتاب (الخطوط والألوان والمحاذاة)، لكن أنماط الكتب يمكنها تحميل موارد من خوادم خارجية، وقد تتمكن تلك الخوادم من مراقبة ذلك. عطّله لإزالة الأنماط. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx index 27cc8d7e..deed41dc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx @@ -45,4 +45,16 @@ Gibt an, ob die von der Anwendung bereitgestellten Themendateien zwischengespeichert werden. Deaktivieren Sie diese Option beim Bearbeiten von Themendateien, damit die Änderungen sofort erscheinen. + + PDFs als Bilder rendern + + + Ob PDF-Bücher als Seitenbilder gerendert werden, wodurch das ursprüngliche Layout erhalten bleibt, der Text der Seiten aber nicht auswählbar oder durchsuchbar ist. Dies ist nützlich für gescannte PDFs ohne extrahierbaren Text. + + + Buchstile beibehalten + + + Legt fest, ob die ursprüngliche Formatierung des Buchinhalts beibehalten wird, wenn Sie ein Buch lesen. Wenn die Option aktiviert ist, bleibt das Aussehen des Buches erhalten (Schriftarten, Farben, Ausrichtung). Buchstile können jedoch Ressourcen von externen Servern laden, die diese Server beobachten könnten. Deaktivieren Sie die Option, um die Stile zu entfernen. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx index ddbebf83..8dfc2097 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx @@ -45,4 +45,16 @@ Whether the theme files served by the application are cached. Turn this off while editing theme files so the changes appear immediately. + + Render PDFs as images + + + Whether PDF books are rendered as page images, preserving the original layout, but making the text of the pages not selectable or searchable. This is useful for scanned PDFs that have no extractable text. + + + Preserve book styles + + + Whether the original styling of book content is preserved when you read a book. Enabling it keeps the look of the book (fonts, colors, alignment), but book styles can load resources from external servers, which those servers could observe; disable it to strip the styles. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx index c8cf3d03..5ab824ba 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx @@ -45,4 +45,16 @@ Controla si los archivos de temas servidos por la aplicación se almacenan en caché. Desactívelo mientras edita archivos de temas para que los cambios aparezcan inmediatamente. + + Mostrar PDF como imágenes + + + Si los libros PDF se muestran como imágenes de página, conservando el diseño original, pero haciendo que el texto de las páginas no sea seleccionable ni buscable. Es útil para PDF escaneados sin texto extraíble. + + + Conservar los estilos de los libros + + + Indica si se conserva el estilo original del contenido de los libros al leer un libro. Activarlo mantiene el aspecto del libro (fuentes, colores, alineación), pero los estilos de los libros pueden cargar recursos de servidores externos, que esos servidores podrían observar. Desactívelo para eliminar los estilos. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx index 28e517f3..23c50cd9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx @@ -45,4 +45,16 @@ Contrôle si les fichiers de thèmes servis par l'application sont mis en cache. Désactivez-le pendant la modification des fichiers de thèmes afin que les changements apparaissent immédiatement. + + Afficher les PDF en images + + + Si les livres PDF sont rendus sous forme d'images de pages, en conservant la mise en page d'origine, mais en rendant le texte des pages non sélectionnable et non recherchable. Utile pour les PDF scannés sans texte extractible. + + + Conserver les styles des livres + + + Indique si le style d'origine du contenu des livres est conservé lorsque vous lisez un livre. L'activer préserve l'aspect du livre (polices, couleurs, alignement), mais les styles des livres peuvent charger des ressources depuis des serveurs externes, que ces serveurs pourraient observer. Désactivez-le pour supprimer les styles. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx index 1bdbba85..124a3da1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx @@ -45,4 +45,16 @@ Controlla se i file dei temi serviti dall'applicazione vengono memorizzati nella cache. Disattivalo mentre modifichi i file dei temi affinché le modifiche appaiano immediatamente. + + Visualizza i PDF come immagini + + + Se i libri PDF vengono visualizzati come immagini delle pagine, preservando il layout originale, ma rendendo il testo delle pagine non selezionabile o ricercabile. Utile per PDF scansionati senza testo estraibile. + + + Conserva gli stili dei libri + + + Indica se lo stile originale del contenuto dei libri viene conservato quando leggi un libro. Attivarlo mantiene l'aspetto del libro (font, colori, allineamento), ma gli stili dei libri possono caricare risorse da server esterni, che tali server potrebbero osservare. Disattivalo per rimuovere gli stili. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx index 571e3f31..60f5846d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx @@ -45,4 +45,16 @@ アプリケーションが提供するテーマファイルをキャッシュするかどうかを制御します。テーマファイルを編集している間はオフにして、変更がすぐに反映されるようにします。 + + PDFを画像として表示 + + + PDFの書籍をページ画像として表示するかどうか。元のレイアウトは保たれますが、ページのテキストは選択や検索ができなくなります。抽出可能なテキストのないスキャンされたPDFに役立ちます。 + + + 本のスタイルを保持 + + + 本を読むときに、本のコンテンツの元のスタイルを保持するかどうか。有効にすると本の見た目(フォント、色、配置)が維持されますが、本のスタイルは外部サーバーからリソースを読み込むことができ、そのサーバーがアクセスを監視できる可能性があります。無効にするとスタイルが削除されます。 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx index ddbebf83..8dfc2097 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx @@ -45,4 +45,16 @@ Whether the theme files served by the application are cached. Turn this off while editing theme files so the changes appear immediately. + + Render PDFs as images + + + Whether PDF books are rendered as page images, preserving the original layout, but making the text of the pages not selectable or searchable. This is useful for scanned PDFs that have no extractable text. + + + Preserve book styles + + + Whether the original styling of book content is preserved when you read a book. Enabling it keeps the look of the book (fonts, colors, alignment), but book styles can load resources from external servers, which those servers could observe; disable it to strip the styles. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx index 517cf9b8..09e79027 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx @@ -45,4 +45,16 @@ Controlează dacă fișierele temelor servite de aplicație sunt puse în cache. Dezactivați această opțiune în timp ce editați fișierele temelor, pentru ca modificările să apară imediat. + + Afișează PDF-urile ca imagini + + + Dacă cărțile PDF sunt afișate ca imagini ale paginilor, păstrând aspectul original, dar făcând textul paginilor neselectabil și necăutabil. Util pentru PDF-urile scanate fără text extractibil. + + + Păstrează stilurile cărților + + + Dacă stilul original al conținutului cărții este păstrat atunci când citiți o carte. Activarea păstrează aspectul cărții (fonturi, culori, aliniere), dar stilurile cărților pot încărca resurse de pe servere externe, pe care acele servere le-ar putea observa. Dezactivați-l pentru a elimina stilurile. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx index f54cb6b9..7886c0d2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.uk-UA.resx @@ -45,4 +45,16 @@ Визначає, чи кешуються файли тем, що надаються застосунком. Вимкніть цю опцію під час редагування файлів тем, щоб зміни відображалися одразу. + + Відображати PDF як зображення + + + Чи відображаються книги PDF як зображення сторінок, зберігаючи оригінальний макет, але роблячи текст сторінок невибірним і недоступним для пошуку. Корисно для сканованих PDF без витягуваного тексту. + + + Зберігати стилі книг + + + Визначає, чи зберігається оригінальне оформлення вмісту книги під час її читання. Увімкнення зберігає вигляд книги (шрифти, кольори, вирівнювання), але стилі книг можуть завантажувати ресурси із зовнішніх серверів, і ті сервери можуть це спостерігати. Вимкніть, щоб прибрати стилі. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx index b0882e8a..3800fb71 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx @@ -45,4 +45,16 @@ 控制应用程序提供的主题文件是否缓存。编辑主题文件时请关闭此选项,以便更改立即生效。 + + 将 PDF 显示为图像 + + + 是否将 PDF 书籍渲染为页面图像,保留原始版式,但页面文本不可选择或搜索。适用于没有可提取文本的扫描 PDF。 + + + 保留书籍样式 + + + 阅读书籍时是否保留书籍内容的原始样式。启用后保留书籍的外观(字体、颜色、对齐方式),但书籍样式可以从外部服务器加载资源,这些服务器可能观察到该行为。禁用可去除样式。 + diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml index 5e5e88cd..c7bde254 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml @@ -238,6 +238,22 @@ @_localizer["DescriptionArtworkProviders"] +

@_localizer["BookReaders"]

+
+ + + + + + + + + + + +
@_localizer["Name"]@_localizer["SupportedExtensions"]@_localizer["Enabled"]
+ @_localizer["DescriptionBookReaders"] +
}
@@ -522,6 +538,49 @@ } }; + const bookReadersTable = document.getElementById('book-readers-table'); + const bookReadersTbody = bookReadersTable ? bookReadersTable.querySelector('tbody') : null; + + // loads the book readers configured for the library, when editing an existing library + async function loadBookReadersAsync() { + if (!id || !bookReadersTbody) return; + const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_BOOK_READERS, new { libraryId = default(Guid) })' + .replace('/@(default(Guid))', `/${id}`); // libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side + const response = await callApiGetAsync(url); + if (response && response.length > 0) { + bookReadersTbody.innerHTML = response.map(reader => renderBookReaderRow(reader)).join(''); + } + } + + // renders a book reader row of the library + function renderBookReaderRow(reader) { + const extensions = (reader.supportedExtensions || []).join(', '); + return ` + + ${reader.name} + ${extensions} + + + + `; + } + + // on book reader enabled checkbox change, persists the new state + async function handleBookReaderEnabledChangeAsync(e) { + if (e.target.matches('.book-reader-enabled')) { + const row = e.target.closest('tr'); + const pluginId = row.getAttribute('data-reader-plugin-id'); + const isEnabled = e.target.checked; + const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_BOOK_READER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled }); + if (!result.success) { + e.target.checked = !isEnabled; + } + } + }; + // add listeners form.addEventListener('keypress', handleEnterKey); form.addEventListener('submit', handleSubmit); @@ -539,6 +598,9 @@ artworkProvidersTbody.addEventListener('click', handleArtworkProviderReorderAsync); artworkProvidersTbody.addEventListener('change', handleArtworkProviderEnabledChangeAsync); } + if (bookReadersTbody) { + bookReadersTbody.addEventListener('change', handleBookReaderEnabledChangeAsync); + } // register cleanup for these listeners cleanupFunctions.push(() => { @@ -558,12 +620,16 @@ artworkProvidersTbody.removeEventListener('click', handleArtworkProviderReorderAsync); artworkProvidersTbody.removeEventListener('change', handleArtworkProviderEnabledChangeAsync); } + if (bookReadersTbody) { + bookReadersTbody.removeEventListener('change', handleBookReaderEnabledChangeAsync); + } }); - // load the metadata and artwork providers when editing an existing library + // load the metadata and artwork providers and book readers when editing an existing library if (id) { loadMetadataProvidersAsync(); loadArtworkProvidersAsync(); + loadBookReadersAsync(); } // store all cleanups for this view on window object using the scriptId diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml index 13f8356f..8104c62a 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml @@ -7,7 +7,7 @@ @using Microsoft.AspNetCore.Mvc.Localization @{ - // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler + // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. var scriptId = ScriptIdentifierHelper.GenerateScriptId(); } @@ -18,8 +18,8 @@
- -
+ +

@(Model.Title ?? string.Empty)

@@ -48,12 +48,14 @@ @section Scripts { +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml index 7f1b46d8..74328465 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml @@ -7,7 +7,7 @@ @using Microsoft.AspNetCore.Mvc.Localization @{ - // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler + // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. var scriptId = ScriptIdentifierHelper.GenerateScriptId(); } @@ -16,8 +16,8 @@ @model UserSettingsDto -
-
+
+
@@ -28,7 +28,7 @@
- +
: @@ -41,7 +41,7 @@
@_localizer["DescriptionEnablePagination"]
- +
@@ -65,7 +65,7 @@
@_localizer["DescriptionShouldIgnoreThePrefixForAlphaPicker"]
- +
: @@ -78,6 +78,32 @@
@_localizer["DescriptionEnableThemeCaching"]
+ +
+
+ : +
+
+ +
+ @_localizer["DescriptionShouldRenderPdfAsImages"] +
+ +
+
+ : +
+
+ +
+ @_localizer["DescriptionShouldPreserveBookStyles"] +
@@ -88,7 +114,7 @@ @section Scripts { "; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false); + + // Assert + Assert.DoesNotContain("script", result, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("alert", result, StringComparison.OrdinalIgnoreCase); + Assert.Contains("Hello", result, StringComparison.Ordinal); + } + + [Fact] + public void Sanitize_WhenHtmlContainsInlineEventHandler_ShouldStripTheHandler() + { + // Arrange + string html = "

Hello

"; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false); + + // Assert + Assert.DoesNotContain("onclick", result, StringComparison.OrdinalIgnoreCase); + Assert.Contains("Hello", result, StringComparison.Ordinal); + } + + [Fact] + public void Sanitize_WhenHtmlContainsJavascriptUrl_ShouldStripTheReference() + { + // Arrange + string html = "Link"; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false); + + // Assert + Assert.DoesNotContain("javascript", result, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Sanitize_WhenHtmlContainsIframe_ShouldStripTheIframe() + { + // Arrange + string html = "

Hello

"; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false); + + // Assert + Assert.DoesNotContain("iframe", result, StringComparison.OrdinalIgnoreCase); + Assert.Contains("Hello", result, StringComparison.Ordinal); + } + + [Fact] + public void Sanitize_WhenHtmlContainsDataLuminaResourceMarker_ShouldKeepTheMarker() + { + // Arrange + string html = $"\"Page\""; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false); + + // Assert + Assert.Contains(ReadingContentSanitizer.RESOURCE_ATTRIBUTE, result, StringComparison.Ordinal); + Assert.Contains("page:1", result, StringComparison.Ordinal); + } + + [Fact] + public void Sanitize_WhenHtmlContainsPlainContent_ShouldKeepTheContent() + { + // Arrange + string html = "

Chapter 1

Some text.

"; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false); + + // Assert + Assert.Contains("Chapter 1", result, StringComparison.Ordinal); + Assert.Contains("Some text.", result, StringComparison.Ordinal); + } + + [Fact] + public void Sanitize_WhenShouldPreserveStylesIsTrue_ShouldKeepTheStyleAttribute() + { + // Arrange + string html = "

Hello

"; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: true); + + // Assert + Assert.Contains("style", result, StringComparison.OrdinalIgnoreCase); + Assert.Contains("Hello", result, StringComparison.Ordinal); + } + + [Fact] + public void Sanitize_WhenShouldPreserveStylesIsFalse_ShouldStripTheStyleAttribute() + { + // Arrange + string html = "

Hello

"; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false); + + // Assert + Assert.DoesNotContain("style", result, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("color:red", result, StringComparison.OrdinalIgnoreCase); + Assert.Contains("Hello", result, StringComparison.Ordinal); + } + + [Theory] + [InlineData(true)] // preserve styles + [InlineData(false)] // strip styles + public void Sanitize_WhenHtmlContainsActiveContent_ShouldStripItRegardlessOfTheStylePreference(bool shouldPreserveStyles) + { + // Arrange + string html = "

Hello

World

"; + + // Act + string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles); + + // Assert + Assert.DoesNotContain("script", result, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("alert", result, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("onclick", result, StringComparison.OrdinalIgnoreCase); + Assert.Contains("Hello", result, StringComparison.Ordinal); + Assert.Contains("World", result, StringComparison.Ordinal); + } + + [Theory] + [InlineData(null)] // null input + [InlineData("")] // empty input + [InlineData(" ")] // whitespace input + public void Sanitize_WhenInputIsBlank_ShouldReturnEmptyString(string? html) + { + // Act + string result = ReadingContentSanitizer.Sanitize(html!, shouldPreserveStyles: false); + + // Assert + Assert.Equal(string.Empty, result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs index ff19d273..9d3f049e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -1,14 +1,16 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== 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.Application.Common.Infrastructure.Reading; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.Plugins; using Lumina.Plugins.Contracts.Core.Metadata; using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Contracts.Core.Reading; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using System; @@ -30,9 +32,12 @@ public class MediaLibraryProviderConfigurationStoreTests private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository; private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository; + private readonly ILibraryBookReaderConfigurationRepository _mockBookReaderConfigurationRepository; private readonly IPluginManager _mockPluginManager; + private readonly IBookReaderEnablementCache _mockEnablementCache; private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationFixture = new(); private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationFixture = new(); + private readonly LibraryBookReaderConfigurationEntityFixture _bookReaderConfigurationFixture = new(); /// /// Initializes a new instance of the class. @@ -42,10 +47,13 @@ public class MediaLibraryProviderConfigurationStoreTests _mockUnitOfWork = Substitute.For(); _mockMetadataConfigurationRepository = Substitute.For(); _mockArtworkConfigurationRepository = Substitute.For(); + _mockBookReaderConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository); _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository); + _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockBookReaderConfigurationRepository); _mockPluginManager = Substitute.For(); _mockPluginManager.GetPlugins().Returns([]); + _mockEnablementCache = Substitute.For(); } [Fact] @@ -77,8 +85,8 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta"); _mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]); MediaLibraryProviderConfigurationStore sut = CreateSut( - (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null), - (betaPluginId, CreateMetadataProvider(LibraryType.Book), CreateArtworkProvider(LibraryType.Book))); + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), CreateArtworkProvider(LibraryType.Book), null)); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) @@ -112,7 +120,7 @@ public class MediaLibraryProviderConfigurationStoreTests Guid pluginId = Guid.NewGuid(); IPlugin plugin = CreatePlugin(pluginId, "Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); - MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null)); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 4); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); @@ -133,7 +141,7 @@ public class MediaLibraryProviderConfigurationStoreTests Guid pluginId = Guid.NewGuid(); IPlugin plugin = CreatePlugin(pluginId, "Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); - MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Movie), null)); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Movie), null, null)); // Act Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); @@ -152,7 +160,7 @@ public class MediaLibraryProviderConfigurationStoreTests Guid pluginId = Guid.NewGuid(); IPlugin plugin = CreatePlugin(pluginId, "Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); - MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null)); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Error.Failure(description: "Failed to read configurations")); @@ -174,13 +182,15 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta"); _mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]); MediaLibraryProviderConfigurationStore sut = CreateSut( - (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null), - (betaPluginId, CreateMetadataProvider(LibraryType.EBook), null)); + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, alphaPluginId, 1); _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); _mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) .Returns(Result.Deleted); _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) @@ -198,6 +208,7 @@ public class MediaLibraryProviderConfigurationStoreTests Arg.Any()); await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync( Arg.Is(configuration => configuration.PluginId == alphaPluginId), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -209,6 +220,8 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Deleted); _mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); MediaLibraryProviderConfigurationStore sut = CreateSut(); // Act @@ -218,6 +231,8 @@ public class MediaLibraryProviderConfigurationStoreTests Assert.False(result.IsFailure); await _mockMetadataConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); } [Fact] @@ -229,6 +244,8 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Deleted); _mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) .Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); MediaLibraryProviderConfigurationStore sut = CreateSut(); // Act @@ -238,24 +255,505 @@ public class MediaLibraryProviderConfigurationStoreTests Assert.False(result.IsFailure); await _mockMetadataConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any()); await _mockArtworkConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any()); + _mockEnablementCache.Received(1).InvalidatePlugin(pluginId); + } + + [Fact] + public async Task RemoveProviderConfigurationsForLibraryAsync_WhenDeletingMetadataFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task RemoveProviderConfigurationsForLibraryAsync_WhenDeletingArtworkFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task RemoveProviderConfigurationsAsync_WhenDeletingMetadataFails_ShouldReturnError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByPluginIdAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByPluginIdAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any()); + } + + [Fact] + public async Task RemoveProviderConfigurationsAsync_WhenDeletingArtworkFails_ShouldReturnError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByPluginIdAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any()); + } + + [Fact] + public async Task EnsureBookReaderConfigurationsAsync_WhenBookReaderSupportsTheLibraryType_ShouldAddDisabledConfiguration() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == pluginId && !configuration.IsEnabled), + Arg.Any()); + } + + [Fact] + public async Task EnsureBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldNotAddAnotherOne() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: pluginId); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + + // Act + Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureBookReaderConfigurationsAsync_WhenNoBookReaderSupportsTheLibraryType_ShouldNotAddConfiguration() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Movie, ".epub"))); + + // Act + Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureBookReaderConfigurationsAsync_WhenReaderDeclaresNoExtension_ShouldNotAddConfiguration() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, supportedExtension: null))); + + // Act + Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task EnsureBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task ReconcileBookReaderConfigurationsAsync_WhenCalled_ShouldRemoveStaleAndAddTheSupportedBookReaders() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha Reader"); + IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta Reader"); + _mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf")), + (betaPluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: alphaPluginId); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) + .Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { alphaPluginId })), Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && !configuration.IsEnabled), + Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId), Arg.Any()); + } + + [Fact] + public async Task ReconcileBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task ReconcileBookReaderConfigurationsAsync_WhenDeletingStaleConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + Guid stalePluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + LibraryBookReaderConfigurationEntity staleConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: stalePluginId); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([staleConfiguration])); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + + // Act + Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task ReconcileBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenCalled_ShouldDeleteTheConfigurationsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); + } + + [Fact] + public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenDeletionFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task RemoveBookReaderConfigurationsAsync_WhenCalled_ShouldDeleteTheConfigurationsOfThePlugin() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any()); + _mockEnablementCache.Received(1).InvalidatePlugin(pluginId); + } + + [Fact] + public async Task RemoveBookReaderConfigurationsAsync_WhenDeletionFails_ShouldReturnError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenArtworkConfigurationsAreStale_ShouldDeleteAndAddThem() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha"); + IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta"); + _mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, null, CreateArtworkProvider(LibraryType.Book), null), + (betaPluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); + LibraryArtworkProviderConfigurationEntity existingArtworkConfiguration = _artworkConfigurationFixture.Create(libraryId, alphaPluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingArtworkConfiguration])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { alphaPluginId })), Arg.Any()); + await _mockArtworkConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 2 && !configuration.IsEnabled), + Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleArtworkConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha"); + _mockPluginManager.GetPlugins().Returns([alphaPlugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((alphaPluginId, null, CreateArtworkProvider(LibraryType.Movie), null)); + LibraryArtworkProviderConfigurationEntity staleArtworkConfiguration = _artworkConfigurationFixture.Create(libraryId, alphaPluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([staleArtworkConfiguration])); + _mockArtworkConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenArtworkConfigurationAlreadyExists_ShouldNotAddAnotherOne() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null)); + LibraryArtworkProviderConfigurationEntity existingConfiguration = _artworkConfigurationFixture.Create(libraryId, pluginId, 3); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenArtworkUpsertFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); } /// - /// Creates the store under test wired to the mocked dependencies, optionally registering the providers of the loaded plugins. + /// Creates the store under test wired to the mocked dependencies, optionally registering the providers and book readers of the loaded plugins. /// - /// The providers registered by the loaded plugins, keyed by their plugin, when any. + /// The providers and book readers registered by the loaded plugins, keyed by their plugin, when any. /// The created store. - private MediaLibraryProviderConfigurationStore CreateSut(params (Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider)[] pluginProviders) + private MediaLibraryProviderConfigurationStore CreateSut(params (Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider, IBookReader? bookReader)[] pluginServices) { ServiceCollection services = new(); - foreach ((Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider) in pluginProviders) + foreach ((Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider, IBookReader? bookReader) in pluginServices) { if (metadataProvider is not null) services.AddKeyedSingleton(pluginId, (_, _) => metadataProvider); if (artworkProvider is not null) services.AddKeyedSingleton(pluginId, (_, _) => artworkProvider); + if (bookReader is not null) + services.AddKeyedSingleton(pluginId, (_, _) => bookReader); } - return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider()); + return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider(), _mockEnablementCache); } /// @@ -295,4 +793,19 @@ public class MediaLibraryProviderConfigurationStoreTests provider.SupportedLibraryTypes.Returns([supportedLibraryType]); return provider; } + + /// + /// Creates a mocked book reader supporting the provided library type and file extension. + /// + /// The library type supported by the reader. + /// The file extension supported by the reader, or for none. + /// The created book reader mock. + private static IBookReader CreateBookReader(LibraryType supportedLibraryType, string? supportedExtension = ".epub") + { + IBookReader reader = Substitute.For(); + reader.SupportedLibraryTypes.Returns([supportedLibraryType]); + reader.SupportedExtensions.Returns(supportedExtension is null ? [] : [supportedExtension]); + return reader; + } } + diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index 632e3235..864eb16e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -71,6 +71,8 @@ public class PluginDetectionSyncJobTests .Returns(Result.Deleted); _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); + _mockProviderConfigurationStore.EnsureBookReaderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Success); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); _mockServiceProvider.GetService(typeof(IMediaLibraryProviderConfigurationStore)).Returns(_mockProviderConfigurationStore); @@ -222,6 +224,7 @@ public class PluginDetectionSyncJobTests // Assert await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any()); + await _mockProviderConfigurationStore.Received(1).EnsureBookReaderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs index e4a40ccd..840be123 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs @@ -50,6 +50,24 @@ public class PluginLoaderTests Assert.Contains("invalid.dll", error.ErrorMessage); } + [Fact] + public void LoadPlugins_WhenDirectoryContainsNativeLibrary_ShouldSkipItSilently() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + // A native library (like pdfium.dll) is a valid PE image starting with the DOS signature, but it is not a managed assembly. + temporaryPluginDirectory.CreateFile("native.dll", "MZ\u0001\u0000\u0000\u0000garbage native library content"); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + Assert.Empty(result.Plugins); + Assert.Empty(result.Errors); + Assert.Empty(result.LoadContexts); + } + [Fact] public void LoadPlugins_WhenDirectoryContainsAssemblyWithoutPluginDescriptors_ShouldReturnNoPluginsAndNoErrors() { @@ -85,6 +103,104 @@ public class PluginLoaderTests Assert.Contains(services, descriptor => descriptor.ImplementationInstance as string == "plugin-services-registered"); } + [Fact] + public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldRetainTheLoadContextOfThePlugin() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + Assert.Single(result.Plugins); + // A collectible load context is only kept alive by a direct reference to the context object itself, so the context of every loaded plugin is retained + // for the lifetime of the host, keeping the plugin assemblies from being unloaded by the garbage collector. + Assert.Single(result.LoadContexts); + } + + [Fact] + public void LoadPlugins_WhenDirectoryContainsManagedDependencyAssemblyAlongsideAPlugin_ShouldSkipTheDependencyAndLoadOnlyThePlugin() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); + // A plugin ships its managed dependencies into the plugins directory (like PdfPig.dll and SkiaSharp.dll next to the PDF plugin). A managed dependency is a valid + // assembly that does not reference the plugin contracts, so it is not a plugin and must be skipped without reflecting over its types, which would otherwise surface + // spurious load errors for a file that is not a plugin. + temporaryPluginDirectory.CopyDll(GetDependencyAssemblyPath()); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + IPlugin loadedPlugin = Assert.Single(result.Plugins); + Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id); + Assert.Equal("Test Plugin", loadedPlugin.Name); + Assert.Empty(result.Errors); + Assert.Single(result.LoadContexts); + } + + [Fact] + public void LoadPlugins_WhenDirectoryContainsFileShorterThanDosSignature_ShouldRecordInvalidAssemblyError() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + // A single-character file is not long enough to carry the two-byte DOS signature "MZ", so it is not a PE image. + temporaryPluginDirectory.CreateFile("tiny.dll", "M"); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + Assert.Empty(result.Plugins); + PluginLoadErrorDto error = Assert.Single(result.Errors); + Assert.Equal("tiny", error.AssemblyName); + Assert.Contains("tiny.dll", error.ErrorMessage); + } + + [Fact] + public void LoadPlugins_WhenDirectoryContainsFileWithWrongDosSignature_ShouldRecordInvalidAssemblyError() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + // The file starts with the wrong DOS signature, so it is not a PE image at all. + temporaryPluginDirectory.CreateFile("notpe.dll", "XY\u0000\u0000\u0000some content that is not a PE image"); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + Assert.Empty(result.Plugins); + PluginLoadErrorDto error = Assert.Single(result.Errors); + Assert.Equal("notpe", error.AssemblyName); + Assert.Contains("notpe.dll", error.ErrorMessage); + } + + [Fact] + public void LoadPlugins_WhenDirectoryContainsLockedNativeLibrary_ShouldNotThrowAndRecordError() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + string nativePath = temporaryPluginDirectory.CreateFileReturningPath("locked.dll", "MZ\u0000\u0000\u0000locked native library content"); + using FileStream lockStream = new(nativePath, FileMode.Open, FileAccess.Read, FileShare.None); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + Assert.Empty(result.Plugins); + // The file cannot be read to verify its PE signature, so it is reported as not loadable rather than crashing the loader. + PluginLoadErrorDto error = Assert.Single(result.Errors); + Assert.Equal("locked", error.AssemblyName); + } + /// /// Gets the path of the Lumina.TestPlugin assembly from the test output directory. /// The assembly is referenced by the test project but no type from it is used, so it is not loaded @@ -96,6 +212,18 @@ public class PluginLoaderTests return Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"); } + /// + /// Gets the path of a managed dependency assembly from the test output directory, standing in for the managed dependencies + /// a plugin ships next to itself (like PdfPig.dll and SkiaSharp.dll next to the PDF plugin). The Microsoft.AspNetCore.SignalR.Core + /// assembly is used because it does not reference the plugin contracts assembly, and reflecting over its types inside a plugin load + /// context throws, which reproduces the spurious load errors the loader used to record for dependency assemblies. + /// + /// The path of the managed dependency assembly. + private static string GetDependencyAssemblyPath() + { + return Path.Combine(AppContext.BaseDirectory, "Microsoft.AspNetCore.SignalR.Core.dll"); + } + /// /// Test helper managing a temporary plugins directory, deleted when the test finishes. /// @@ -116,6 +244,13 @@ public class PluginLoaderTests File.WriteAllText(System.IO.Path.Combine(Path, fileName), content); } + public string CreateFileReturningPath(string fileName, string content) + { + string filePath = System.IO.Path.Combine(Path, fileName); + File.WriteAllText(filePath, content); + return filePath; + } + public void CopyDll(string sourceDllPath) { File.Copy(sourceDllPath, System.IO.Path.Combine(Path, System.IO.Path.GetFileName(sourceDllPath))); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs index e20be5f7..72be6539 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs @@ -5,7 +5,6 @@ using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; #endregion namespace Lumina.Infrastructure.UnitTests.Core.Plugins; @@ -22,7 +21,7 @@ public class PluginManagerTests // Arrange IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin"); IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin"); - PluginManager sut = new([firstPlugin, secondPlugin]); + PluginManager sut = new([firstPlugin, secondPlugin], []); // Act IReadOnlyList result = sut.GetPlugins(); @@ -37,7 +36,7 @@ public class PluginManagerTests public void GetPlugins_WhenNoPluginsWereLoaded_ShouldReturnEmptyList() { // Arrange - PluginManager sut = new([]); + PluginManager sut = new([], []); // Act IReadOnlyList result = sut.GetPlugins(); @@ -52,7 +51,7 @@ public class PluginManagerTests // Arrange Guid pluginId = Guid.NewGuid(); IPlugin expectedPlugin = CreatePlugin(pluginId, "Expected Plugin"); - PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")]); + PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")], []); // Act IPlugin? result = sut.GetPlugin(pluginId); @@ -65,7 +64,7 @@ public class PluginManagerTests public void GetPlugin_WhenPluginWithIdWasNotLoaded_ShouldReturnNull() { // Arrange - PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")]); + PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")], []); // Act IPlugin? result = sut.GetPlugin(Guid.NewGuid()); diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Reading/IBookReaderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Reading/IBookReaderGenericTests.cs new file mode 100644 index 00000000..144c40ad --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Reading/IBookReaderGenericTests.cs @@ -0,0 +1,152 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Reading; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.UnitTests.Core.Reading; + +/// +/// Contains unit tests for the interface. +/// +[ExcludeFromCodeCoverage] +public class IBookReaderGenericTests +{ + private readonly ReadingDocumentDtoFixture _readingDocumentDtoFixture = new(); + + [Fact] + public async Task OpenAsync_WhenCalled_ShouldForwardArgumentsToTheReaderImplementation() + { + // Arrange + string path = "/books/test.epub"; + string workingDirectory = "/tmp/reading-cache"; + bool shouldRenderPdfAsImages = true; + CancellationToken cancellationToken = CancellationToken.None; + ReadingDocumentDto expectedDocument = _readingDocumentDtoFixture.Create(); + TestBookReader reader = new(expectedDocument, [1, 2, 3]); + + // Act + ReadingDocumentDto result = await reader.OpenAsync(path, workingDirectory, shouldRenderPdfAsImages, cancellationToken); + + // Assert + Assert.Equal(expectedDocument, result); + Assert.Equal(path, reader.ReceivedPath); + Assert.Equal(workingDirectory, reader.ReceivedWorkingDirectory); + Assert.Equal(shouldRenderPdfAsImages, reader.ReceivedShouldRenderPdfAsImages); + Assert.Equal(cancellationToken, reader.ReceivedCancellationToken); + } + + [Fact] + public async Task GetResourceAsync_WhenCalled_ShouldForwardArgumentsToTheReaderImplementation() + { + // Arrange + string path = "/books/test.epub"; + string workingDirectory = "/tmp/reading-cache"; + string resourceKey = "resources/cover.png"; + CancellationToken cancellationToken = CancellationToken.None; + byte[] expectedResource = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + TestBookReader reader = new(_readingDocumentDtoFixture.Create(), expectedResource); + + // Act + byte[] result = await reader.GetResourceAsync(path, workingDirectory, resourceKey, cancellationToken); + + // Assert + Assert.Equal(expectedResource, result); + Assert.Equal(path, reader.ReceivedResourcePath); + Assert.Equal(workingDirectory, reader.ReceivedResourceWorkingDirectory); + Assert.Equal(resourceKey, reader.ReceivedResourceKey); + Assert.Equal(cancellationToken, reader.ReceivedResourceCancellationToken); + } + + /// + /// Test double for the book reader interface that records the forwarded arguments. + /// + [ExcludeFromCodeCoverage] + private sealed class TestBookReader : IBookReader + { + private readonly ReadingDocumentDto _document; + private readonly byte[] _resource; + + /// + /// Gets the path that was forwarded to the OpenAsync implementation. + /// + public string? ReceivedPath { get; private set; } + + /// + /// Gets the working directory that was forwarded to the OpenAsync implementation. + /// + public string? ReceivedWorkingDirectory { get; private set; } + + /// + /// Gets the rendering preference that was forwarded to the OpenAsync implementation. + /// + public bool ReceivedShouldRenderPdfAsImages { get; private set; } + + /// + /// Gets the cancellation token that was forwarded to the OpenAsync implementation. + /// + public CancellationToken ReceivedCancellationToken { get; private set; } + + /// + /// Gets the path that was forwarded to the GetResourceAsync implementation. + /// + public string? ReceivedResourcePath { get; private set; } + + /// + /// Gets the working directory that was forwarded to the GetResourceAsync implementation. + /// + public string? ReceivedResourceWorkingDirectory { get; private set; } + + /// + /// Gets the resource key that was forwarded to the GetResourceAsync implementation. + /// + public string? ReceivedResourceKey { get; private set; } + + /// + /// Gets the cancellation token that was forwarded to the GetResourceAsync implementation. + /// + public CancellationToken ReceivedResourceCancellationToken { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The document returned by the OpenAsync implementation. + /// The resource data returned by the GetResourceAsync implementation. + public TestBookReader(ReadingDocumentDto document, byte[] resource) + { + _document = document; + _resource = resource; + } + + /// + public IReadOnlyList SupportedExtensions => [".epub"]; + + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.EBook]; + + /// + public Task OpenAsync(string path, string workingDirectory, bool shouldRenderPdfAsImages, CancellationToken cancellationToken) + { + ReceivedPath = path; + ReceivedWorkingDirectory = workingDirectory; + ReceivedShouldRenderPdfAsImages = shouldRenderPdfAsImages; + ReceivedCancellationToken = cancellationToken; + return Task.FromResult(_document); + } + + /// + public Task GetResourceAsync(string path, string workingDirectory, string resourceKey, CancellationToken cancellationToken) + { + ReceivedResourcePath = path; + ReceivedResourceWorkingDirectory = workingDirectory; + ReceivedResourceKey = resourceKey; + ReceivedResourceCancellationToken = cancellationToken; + return Task.FromResult(_resource); + } + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Common/DependencyInjection/EpubServicesTests.cs b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Common/DependencyInjection/EpubServicesTests.cs new file mode 100644 index 00000000..b927f545 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Common/DependencyInjection/EpubServicesTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Reading; +using Lumina.Plugins.Epub.Common.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Epub.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EpubServicesTests +{ + [Fact] + public void AddEpubReader_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddEpubReader(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddEpubReader_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddEpubReader(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddEpubReader_WhenCalled_ShouldRegisterTheBookReaderForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddEpubReader(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetKeyedService(pluginId)); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/Epub/EpubDocumentParserTests.cs b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/Epub/EpubDocumentParserTests.cs new file mode 100644 index 00000000..db0d339b --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/Epub/EpubDocumentParserTests.cs @@ -0,0 +1,635 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Plugins.Epub.Core.Epub; +using Lumina.Plugins.Epub.Fixtures.Core.Epub; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +#endregion + +namespace Lumina.Plugins.Epub.UnitTests.Core.Epub; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EpubDocumentParserTests : IDisposable +{ + private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-epub-tests-{Guid.NewGuid():N}"); + private readonly string _epubPath; + + /// + /// Initializes a new instance of the class. + /// + public EpubDocumentParserTests() + { + Directory.CreateDirectory(_temporaryDirectory); + _epubPath = Path.Combine(_temporaryDirectory, "minimal.epub"); + } + + [Fact] + public void Parse_WhenCalledOnValidEpub_ShouldReturnDocumentWithTitleAuthorAndSpine() + { + // Arrange + TestEpubFileFactory.CreateMinimalEpub(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Equal("Minimal EPUB Book", result.Title); + Assert.Equal("Test Author", result.Author); + Assert.Equal(2, result.Spine.Count); + Assert.Equal("chapter1", result.Spine[0].LocationRef); + Assert.Equal("chapter2", result.Spine[1].LocationRef); + Assert.True(result.HasTextContent); + } + + [Fact] + public void Parse_WhenCalledOnValidEpub_ShouldExtractResourcesAndRewriteReferences() + { + // Arrange + TestEpubFileFactory.CreateMinimalEpub(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + string expectedKey = CreateResourceKey("images/cover.png"); + KeyValuePair resource = Assert.Single(result.Resources); + Assert.Equal(expectedKey, resource.Key); + Assert.Equal("image/png", resource.Value.MimeType); + Assert.True(File.Exists(Path.Combine(workingDirectory, resource.Value.RelativeFilePath))); + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath)); + Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal); + Assert.DoesNotContain("src=\"images/cover.png\"", sectionContent, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenSectionDeclaresADoctypeAndNamedEntities_ShouldRewriteItsReferencesAndResolveTheEntities() + { + // Arrange + TestEpubFileFactory.CreateEpubWithDoctypeAndNamedEntities(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + ReadingSpineItemDto spineItem = Assert.Single(result.Spine); + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath)); + string expectedKey = CreateResourceKey("images/cover.png"); + // The DTD declaration was tolerated and the named character references resolved, so the section was rewritten instead of + // being served "as-is": the internal image reference became the resource marker and the non-breaking spaces were decoded. + Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal); + Assert.DoesNotContain("src=\"images/cover.png\"", sectionContent, StringComparison.Ordinal); + Assert.DoesNotContain(" EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + InvalidDataException exception = Assert.Throws(act); + Assert.Contains("OPF", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenEpubHasNoSpine_ShouldThrowInvalidDataException() + { + // Arrange + TestEpubFileFactory.CreateEpubWithoutSpine(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + InvalidDataException exception = Assert.Throws(act); + Assert.Contains("reading sections", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenEpubHasTraversalHref_ShouldSkipTheBrokenItemAndKeepTheRest() + { + // Arrange + TestEpubFileFactory.CreateEpubWithTraversalHref(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + // The broken manifest item is skipped, while the resolvable section is still parsed. + Assert.Equal("Traversal Href", result.Title); + ReadingSpineItemDto spineItem = Assert.Single(result.Spine); + Assert.Equal("chapter2", spineItem.LocationRef); + } + + [Fact] + public void Parse_WhenSectionIsNotWellFormedXml_ShouldServeTheSectionAsIs() + { + // Arrange + TestEpubFileFactory.CreateEpubWithBrokenSection(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + ReadingSpineItemDto spineItem = Assert.Single(result.Spine); + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath)); + Assert.Contains("Not well formed", sectionContent, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenEpub2HasNcxToc_ShouldBuildTableOfContentsFromTheNcxDocument() + { + // Arrange + TestEpubFileFactory.CreateEpubWithNcxToc(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Equal("EPUB 2 Book", result.Title); + // The NCX entries: Chapter One (with its nested Part One), Chapter Two, the anchor-less entry whose target is + // missing, and the entry with a blank label and no content source. + Assert.Equal(4, result.TableOfContents.Count); + ReadingTocEntryDto firstEntry = result.TableOfContents[0]; + Assert.Equal("NCX Chapter One", firstEntry.Label); + Assert.Equal("chapter1", firstEntry.LocationRef); + ReadingTocEntryDto childEntry = Assert.Single(firstEntry.Children); + Assert.Equal("NCX Part One", childEntry.Label); + Assert.Equal("chapter1", childEntry.LocationRef); + Assert.Equal("NCX Chapter Two", result.TableOfContents[1].Label); + Assert.Equal("chapter2", result.TableOfContents[1].LocationRef); + // A navigation point without a label and pointing at an unknown file yields a non-navigable entry. + Assert.Equal(string.Empty, result.TableOfContents[2].Label); + Assert.Equal(string.Empty, result.TableOfContents[2].LocationRef); + // A navigation point with a blank label and no content source also yields a non-navigable entry. + Assert.Equal(string.Empty, result.TableOfContents[3].Label); + Assert.Equal(string.Empty, result.TableOfContents[3].LocationRef); + Assert.Equal("NCX Chapter One", result.Spine[0].Title); + Assert.Equal("NCX Chapter Two", result.Spine[1].Title); + // The cover is declared with an EPUB 2 meta element, and is still exposed. + Assert.Equal(CreateResourceKey("images/cover.png"), result.CoverResourceKey); + } + + [Fact] + public void Parse_WhenEpub2HasNcxTocAndNoNavigationDocument_ShouldUseTheNcxDocument() + { + // Arrange + TestEpubFileFactory.CreateEpubWithNcxToc(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + // No EPUB 3 navigation document is present, so every named entry comes from the NCX document. + Assert.Equal("NCX Chapter One", result.TableOfContents[0].Label); + Assert.Equal("NCX Chapter Two", result.TableOfContents[1].Label); + } + + [Fact] + public void Parse_WhenManifestCarriesVariedMediaTypes_ShouldExtractOnlyTheUsableResources() + { + // Arrange + TestEpubFileFactory.CreateEpubWithVariedMediaTypes(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + // The font, audio, video, and CSS items are extracted as resources; the script is not a resource the reader serves. + Assert.Equal(6, result.Resources.Count); + Assert.Contains(result.Resources, resource => resource.Value.MimeType == "font/woff2"); + Assert.Contains(result.Resources, resource => resource.Value.MimeType == "application/vnd.ms-opentype"); + Assert.Contains(result.Resources, resource => resource.Value.MimeType == "application/x-font-ttf"); + Assert.Contains(result.Resources, resource => resource.Value.MimeType == "audio/mpeg"); + Assert.Contains(result.Resources, resource => resource.Value.MimeType == "video/mp4"); + Assert.DoesNotContain(result.Resources, resource => resource.Value.MimeType == "application/javascript"); + Assert.Contains(result.Resources, resource => resource.Value.MimeType == "text/css"); + // The section is the only spine item, so the document still reads. + Assert.Single(result.Spine); + } + + [Fact] + public void Parse_WhenContainerDocumentIsMalformed_ShouldThrowInvalidDataException() + { + // Arrange + TestEpubFileFactory.CreateEpubWithMalformedContainer(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + InvalidDataException exception = Assert.Throws(act); + Assert.Contains("OPF", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenNavigationDocumentHasNoTocNav_ShouldReturnEmptyTableOfContents() + { + // Arrange + TestEpubFileFactory.CreateEpubWithNonTocNav(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Empty(result.TableOfContents); + Assert.Single(result.Spine); + } + + [Fact] + public void Parse_WhenEpubHasNoTitle_ShouldUseTheFileNameAsTheTitle() + { + // Arrange + TestEpubFileFactory.CreateEpubWithoutTitle(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Equal("minimal", result.Title); + Assert.Null(result.Author); + } + + [Fact] + public void Parse_WhenManifestContainsBrokenItems_ShouldSkipThemAndKeepTheValidSections() + { + // Arrange + TestEpubFileFactory.CreateEpubWithBrokenManifest(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + // The two valid spine items are kept, and the reference to the unknown Id is dropped. + Assert.Equal(2, result.Spine.Count); + Assert.Equal("chapter1", result.Spine[0].LocationRef); + Assert.Equal("chapter2", result.Spine[1].LocationRef); + // The plain item (no properties) is not extracted as a resource because it is not a spine section and not a usable media type. + Assert.Empty(result.Resources); + } + + [Fact] + public void Parse_WhenArchiveHasTooManyEntries_ShouldThrowInvalidDataException() + { + // Arrange + TestEpubFileFactory.CreateEpubWithTooManyEntries(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + InvalidDataException exception = Assert.Throws(act); + Assert.Contains("too many entries", exception.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Parse_WhenArchiveExpandsBeyondTheLimit_ShouldThrowInvalidDataException() + { + // Arrange + TestEpubFileFactory.CreateEpubWithTooLargeExpandedSize(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + InvalidDataException exception = Assert.Throws(act); + Assert.Contains("too large", exception.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Parse_WhenRootfileHasNoFullPath_ShouldThrowInvalidDataException() + { + // Arrange + TestEpubFileFactory.CreateEpubWithRootfileWithoutPath(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + InvalidDataException exception = Assert.Throws(act); + Assert.Contains("OPF", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenArchiveFilesAreMissing_ShouldSkipTheBrokenItemsAndKeepTheReadableSection() + { + // Arrange + TestEpubFileFactory.CreateEpubWithMissingArchiveFiles(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + // The section whose file is missing from the archive is skipped, while the readable one is kept. + Assert.Single(result.Spine); + Assert.Equal("chapter1", result.Spine[0].LocationRef); + // The resource whose file is missing from the archive is not extracted. + Assert.Empty(result.Resources); + } + + [Fact] + public void Parse_WhenTwoItemsShareAHref_ShouldExtractTheResourceOnce() + { + // Arrange + TestEpubFileFactory.CreateEpubWithDuplicateResource(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + string expectedKey = CreateResourceKey("images/cover.png"); + KeyValuePair resource = Assert.Single(result.Resources); + Assert.Equal(expectedKey, resource.Key); + } + + [Fact] + public void Parse_WhenNavigationDocumentIsMalformed_ShouldReturnEmptyTableOfContents() + { + // Arrange + TestEpubFileFactory.CreateEpubWithMalformedNavigationDocument(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Empty(result.TableOfContents); + Assert.Single(result.Spine); + } + + [Fact] + public void Parse_WhenNcxDocumentIsMalformed_ShouldReturnEmptyTableOfContents() + { + // Arrange + TestEpubFileFactory.CreateEpubWithMalformedNcx(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Empty(result.TableOfContents); + Assert.Single(result.Spine); + } + + [Fact] + public void Parse_WhenSectionCarriesVariedReferences_ShouldRewriteOnlyTheResolvableOnes() + { + // Arrange + TestEpubFileFactory.CreateEpubWithVariedReferences(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath)); + string expectedKey = CreateResourceKey("images/cover.png"); + // The resolvable internal image is rewritten to the resource marker; the fragment variant resolves to the same image. + Assert.Contains($"data-lumina-resource=\"{expectedKey}\"", sectionContent, StringComparison.Ordinal); + Assert.Equal(2, CountOccurrences(sectionContent, "data-lumina-resource")); + // The same-page anchor, data URI, absolute links, mailto, and broken path keep their original value. + Assert.Contains("href=\"#part\"", sectionContent, StringComparison.Ordinal); + Assert.Contains("data:image/png;base64,AAAA", sectionContent, StringComparison.Ordinal); + Assert.Contains("href=\"http://example.com\"", sectionContent, StringComparison.Ordinal); + Assert.Contains("href=\"https://example.com\"", sectionContent, StringComparison.Ordinal); + Assert.Contains("href=\"mailto:a@b.com\"", sectionContent, StringComparison.Ordinal); + Assert.Contains("href=\"tel:+123\"", sectionContent, StringComparison.Ordinal); + Assert.Contains("src=\"missing/image.png\"", sectionContent, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenEpubHasNoMetadataElement_ShouldUseTheFileNameAsTheTitleAndLeaveAuthorNull() + { + // Arrange + TestEpubFileFactory.CreateEpubWithoutMetadataElement(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Equal("minimal", result.Title); + Assert.Null(result.Author); + Assert.Single(result.Spine); + } + + [Fact] + public void Parse_WhenOpfFileIsMissing_ShouldThrowInvalidDataException() + { + // Arrange + TestEpubFileFactory.CreateEpubWithMissingOpf(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void Parse_WhenOpfSitsAtTheArchiveRoot_ShouldResolveSectionsRelativeToIt() + { + // Arrange + TestEpubFileFactory.CreateEpubWithRootLevelOpf(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Equal("Root Level OPF", result.Title); + ReadingSpineItemDto spineItem = Assert.Single(result.Spine); + Assert.Equal("chapter1", spineItem.LocationRef); + } + + [Fact] + public void Parse_WhenResourceHrefEscapesTheArchive_ShouldSkipTheResource() + { + // Arrange + TestEpubFileFactory.CreateEpubWithEscapingResourceHref(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + Assert.Equal("Escaping Resource", result.Title); + Assert.Empty(result.Resources); + Assert.Single(result.Spine); + } + + [Fact] + public void Parse_WhenResourceExceedsTheSizeCap_ShouldThrowInvalidDataException() + { + // Arrange + TestEpubFileFactory.CreateEpubWithOversizedResource(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + InvalidDataException exception = Assert.Throws(act); + Assert.Contains("too large", exception.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Parse_WhenEntriesFitPerEntryCapsButActualExpandedBytesExceedTheTotalCap_ShouldThrowInvalidDataException() + { + // Arrange + // The entries each declare a tiny uncompressed size and each actual one is under its per-entry cap, so only the budget + // that counts the bytes actually read while the entries are streamed can reject the archive. + TestEpubFileFactory.CreateEpubWithUnderPerEntryCapsButOversizedExpandedSize(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // The declared sizes stay well under the 256 MB cap, so the declared-size quick guard in ValidateArchive cannot be + // what rejects the archive; the rejection can only come from counting the bytes actually read. + long declaredTotalBytes; + using (FileStream fileStream = File.OpenRead(_epubPath)) + using (ZipArchive zipArchive = new(fileStream, ZipArchiveMode.Read)) + declaredTotalBytes = zipArchive.Entries.Sum(entry => entry.Length); + Assert.True(declaredTotalBytes <= 256 * 1024 * 1024); + + // Act + Action act = () => EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + // The total-expanded message is specific to the archive-wide cap, unlike the per-entry "too large" message. + InvalidDataException exception = Assert.Throws(act); + Assert.Contains("expanded EPUB archive", exception.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Parse_WhenManifestItemHasNoMediaType_ShouldSkipIt() + { + // Arrange + TestEpubFileFactory.CreateEpubWithMissingMediaType(_epubPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = EpubDocumentParser.Parse(_epubPath, workingDirectory, CancellationToken.None); + + // Assert + // A manifest item without a media type cannot be classified as an extractable resource, so it is skipped. + Assert.Empty(result.Resources); + Assert.Single(result.Spine); + } + + /// + /// Counts the occurrences of in . + /// + /// The text to search. + /// The substring to count. + /// The number of occurrences of the substring. + private static int CountOccurrences(string haystack, string needle) + { + int count = 0; + int index = 0; + while ((index = haystack.IndexOf(needle, index, StringComparison.Ordinal)) >= 0) + { + count++; + index += needle.Length; + } + return count; + } + + /// + /// Computes the resource key the parser derives from a manifest href. + /// + /// The manifest href. + /// The resource key of the href. + private static string CreateResourceKey(string href) + { + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(href)))[..32].ToLowerInvariant(); + } + + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } +} + diff --git a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubPluginTests.cs b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubPluginTests.cs new file mode 100644 index 00000000..4781aa3e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubPluginTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Reading; +using Lumina.Plugins.Epub.Core; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Epub.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EpubPluginTests +{ + private readonly EpubPlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(EpubPlugin.s_pluginId, result); + Assert.Equal(new Guid("b1e8a8e0-4f3a-4d2c-9a1e-6d3f8a9b2c3d"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("EPUB Reader", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Allows reading of EPUB format books.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedBookReader() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetKeyedService(EpubPlugin.s_pluginId)); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubReaderTests.cs b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubReaderTests.cs new file mode 100644 index 00000000..36bb5849 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Core/EpubReaderTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Epub.Core; +using Lumina.Plugins.Epub.Fixtures.Core.Epub; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Epub.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EpubReaderTests : IDisposable +{ + private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-epub-reader-{Guid.NewGuid():N}"); + private readonly string _epubPath; + private readonly EpubReader _sut = new(); + + /// + /// Initializes a new instance of the class. + /// + public EpubReaderTests() + { + Directory.CreateDirectory(_temporaryDirectory); + _epubPath = Path.Combine(_temporaryDirectory, "minimal.epub"); + TestEpubFileFactory.CreateMinimalEpub(_epubPath); + } + + [Fact] + public void SupportedExtensions_WhenAccessed_ShouldOnlyContainEpub() + { + // Assert + Assert.Equal([".epub"], _sut.SupportedExtensions); + } + + [Fact] + public void SupportedLibraryTypes_WhenAccessed_ShouldContainEBookAndBook() + { + // Assert + Assert.Equal([LibraryType.EBook, LibraryType.Book], _sut.SupportedLibraryTypes); + } + + [Fact] + public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Equal("Minimal EPUB Book", result.Title); + Assert.Equal(2, result.Spine.Count); + } + + [Fact] + public async Task GetResourceAsync_WhenResourceWasExtracted_ShouldReturnItsBytes() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + ReadingDocumentDto document = await _sut.OpenAsync(_epubPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + string resourceKey = document.Resources.Keys.Single(); + + // Act + byte[] result = await _sut.GetResourceAsync(_epubPath, workingDirectory, resourceKey, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotEmpty(result); + } + + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } +} + diff --git a/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Lumina.Plugins.Epub.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Lumina.Plugins.Epub.UnitTests.csproj new file mode 100644 index 00000000..0abab51d --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Epub.UnitTests/Lumina.Plugins.Epub.UnitTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Common/DependencyInjection/PdfServicesTests.cs b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Common/DependencyInjection/PdfServicesTests.cs new file mode 100644 index 00000000..bbf0e1e0 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Common/DependencyInjection/PdfServicesTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Reading; +using Lumina.Plugins.Pdf.Common.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Pdf.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PdfServicesTests +{ + [Fact] + public void AddPdfReader_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddPdfReader(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddPdfReader_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddPdfReader(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddPdfReader_WhenCalled_ShouldRegisterTheBookReaderForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddPdfReader(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetKeyedService(pluginId)); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/Pdf/PdfDocumentParserTests.cs b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/Pdf/PdfDocumentParserTests.cs new file mode 100644 index 00000000..849aacfb --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/Pdf/PdfDocumentParserTests.cs @@ -0,0 +1,241 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Plugins.Pdf.Core.Pdf; +using Lumina.Plugins.Pdf.Fixtures.Core.Pdf; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.Versioning; +using System.Threading; +#endregion + +namespace Lumina.Plugins.Pdf.UnitTests.Core.Pdf; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PdfDocumentParserTests : IDisposable +{ + private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-tests-{Guid.NewGuid():N}"); + private readonly string _pdfPath; + + /// + /// Initializes a new instance of the class. + /// + public PdfDocumentParserTests() + { + Directory.CreateDirectory(_temporaryDirectory); + _pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf"); + TestPdfFileFactory.CreateMinimalPdf(_pdfPath); + } + + [Fact] + public void Parse_WhenCalledOnPdfWithTextLayer_ShouldReturnDocumentWithTextSections() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Equal("minimal", result.Title); + Assert.True(result.HasTextContent); + ReadingSpineItemDto spineItem = Assert.Single(result.Spine); + Assert.Equal("page:1", spineItem.LocationRef); + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath)); + Assert.Contains("

Hello PDF Page 1

", sectionContent, StringComparison.Ordinal); + Assert.Empty(result.Resources); + } + + [Fact] + public void Parse_WhenCalledWithRenderAsImages_ShouldReturnDocumentWithImageSectionsAndNoTextContent() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(_pdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None); + + // Assert + Assert.Equal("minimal", result.Title); + Assert.False(result.HasTextContent); + ReadingSpineItemDto spineItem = Assert.Single(result.Spine); + Assert.Equal("page:1", spineItem.LocationRef); + KeyValuePair resource = Assert.Single(result.Resources); + Assert.Equal("page:1", resource.Key); + Assert.Equal("image/png", resource.Value.MimeType); + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, spineItem.RelativeSectionFilePath)); + Assert.Contains("data-lumina-resource=\"page:1\"", sectionContent, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenPdfFileDoesNotExist_ShouldThrowFileNotFoundException() + { + // Arrange + string missingPdfPath = Path.Combine(_temporaryDirectory, "missing.pdf"); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => PdfDocumentParser.Parse(missingPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [SupportedOSPlatform("windows")] + [Fact] + public void RenderResource_WhenResourceKeyDoesNotIdentifyAPage_ShouldThrowInvalidDataException() + { + // Act + Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "not-a-page", CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [SupportedOSPlatform("windows")] + [Fact] + public void RenderResource_WhenResourceKeyNamesAPageBeyondThePageCap_ShouldThrowInvalidDataException() + { + // Act + // The minimal PDF has a single page, but the key is rejected by the page cap before the document is even opened. + Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:10001", CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [SupportedOSPlatform("windows")] + [Fact] + public void RenderResource_WhenResourceKeyNamesAPageBeyondTheDocument_ShouldThrowInvalidDataException() + { + // Act + // The minimal PDF has a single page, so page 2 is rejected against the page count of the document without rendering it. + Action act = () => PdfDocumentParser.RenderResource(_pdfPath, "page:2", CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void Parse_WhenPdfHasBookmarks_ShouldBuildTableOfContentsFromTheOutline() + { + // Arrange + string outlinedPdfPath = Path.Combine(_temporaryDirectory, "outlined.pdf"); + TestPdfFileFactory.CreatePdfWithOutline(outlinedPdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(outlinedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + // PdfPig does not surface a bookmark without a title, so only the three titled top-level entries appear. + Assert.Equal(3, result.TableOfContents.Count); + ReadingTocEntryDto chapterOne = result.TableOfContents[0]; + Assert.Equal("Chapter One", chapterOne.Label); + Assert.Equal("page:1", chapterOne.LocationRef); + ReadingTocEntryDto partOne = Assert.Single(chapterOne.Children); + Assert.Equal("Part One", partOne.Label); + Assert.Equal("page:1", partOne.LocationRef); + Assert.Equal("Chapter Two", result.TableOfContents[1].Label); + Assert.Equal("page:2", result.TableOfContents[1].LocationRef); + // A bookmark pointing at a URI instead of a page yields an entry that is not navigable. + Assert.Equal("External Link", result.TableOfContents[2].Label); + Assert.Equal(string.Empty, result.TableOfContents[2].LocationRef); + } + + [Fact] + public void Parse_WhenPdfIsTooLarge_ShouldThrowInvalidDataException() + { + // Arrange + string oversizedPdfPath = Path.Combine(_temporaryDirectory, "oversized.pdf"); + // A sparse file larger than the 500 MB cap, without allocating disk space. + using (FileStream fileStream = new(oversizedPdfPath, FileMode.Create, FileAccess.Write)) + fileStream.SetLength(501L * 1024 * 1024); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + Action act = () => PdfDocumentParser.Parse(oversizedPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void Parse_WhenPdfHasABlankTextLine_ShouldSkipTheBlankLineAndKeepTheOthers() + { + // Arrange + string blankLinePdfPath = Path.Combine(_temporaryDirectory, "blankline.pdf"); + TestPdfFileFactory.CreatePdfWithBlankLine(blankLinePdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(blankLinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + string sectionContent = File.ReadAllText(Path.Combine(workingDirectory, result.Spine[0].RelativeSectionFilePath)); + Assert.Contains("

First line

", sectionContent, StringComparison.Ordinal); + Assert.Contains("

Third line

", sectionContent, StringComparison.Ordinal); + Assert.DoesNotContain("

", sectionContent, StringComparison.Ordinal); + } + + [Fact] + public void Parse_WhenPdfOutlineIsMalformed_ShouldSkipTheTableOfContentsAndKeepThePages() + { + // Arrange + string malformedOutlinePdfPath = Path.Combine(_temporaryDirectory, "malformed-outline.pdf"); + TestPdfFileFactory.CreatePdfWithMalformedOutline(malformedOutlinePdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(malformedOutlinePdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + // The malformed bookmarks are best effort: the table of contents is skipped, but the pages are still readable. + Assert.Empty(result.TableOfContents); + Assert.Single(result.Spine); + } + + [Fact] + public void Parse_WhenPdfExceedsThePageCap_ShouldStopAtTheCap() + { + // Arrange + string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages.pdf"); + TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + // The parser stops enumerating after the page cap instead of reading every page. + Assert.Equal(10_000, result.Spine.Count); + } + + [Fact] + public void ParseAsImages_WhenPdfExceedsThePageCap_ShouldStopAtTheCap() + { + // Arrange + string manyPagesPdfPath = Path.Combine(_temporaryDirectory, "many-pages-images.pdf"); + TestPdfFileFactory.CreatePdfWithMorePagesThanAllowed(manyPagesPdfPath); + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = PdfDocumentParser.Parse(manyPagesPdfPath, workingDirectory, shouldRenderPdfAsImages: true, CancellationToken.None); + + // Assert + Assert.Equal(10_000, result.Spine.Count); + Assert.Equal(10_000, result.Resources.Count); + } + + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } +} + diff --git a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfPluginTests.cs b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfPluginTests.cs new file mode 100644 index 00000000..677d7a1f --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfPluginTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Reading; +using Lumina.Plugins.Pdf.Core; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Pdf.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PdfPluginTests +{ + private readonly PdfPlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(PdfPlugin.s_pluginId, result); + Assert.Equal(new Guid("c2f9b8f0-5a4b-4e3d-8b2f-7e4a9c1d3e5f"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("PDF Reader", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Allows reading of PDF format books.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedBookReader() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetKeyedService(PdfPlugin.s_pluginId)); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfReaderTests.cs b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfReaderTests.cs new file mode 100644 index 00000000..710c45d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Core/PdfReaderTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Pdf.Core; +using Lumina.Plugins.Pdf.Fixtures.Core.Pdf; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.Versioning; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Pdf.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PdfReaderTests : IDisposable +{ + private readonly string _temporaryDirectory = Path.Combine(Path.GetTempPath(), $"lumina-pdf-reader-{Guid.NewGuid():N}"); + private readonly string _pdfPath; + private readonly PdfReader _sut = new(); + + /// + /// Initializes a new instance of the class. + /// + public PdfReaderTests() + { + Directory.CreateDirectory(_temporaryDirectory); + _pdfPath = Path.Combine(_temporaryDirectory, "minimal.pdf"); + TestPdfFileFactory.CreateMinimalPdf(_pdfPath); + } + + [Fact] + public void SupportedExtensions_WhenAccessed_ShouldOnlyContainPdf() + { + // Assert + Assert.Equal([".pdf"], _sut.SupportedExtensions); + } + + [Fact] + public void SupportedLibraryTypes_WhenAccessed_ShouldContainEBookAndBook() + { + // Assert + Assert.Equal([LibraryType.EBook, LibraryType.Book], _sut.SupportedLibraryTypes); + } + + [Fact] + public async Task OpenAsync_WhenCalled_ShouldReturnTheParsedDocument() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + ReadingDocumentDto result = await _sut.OpenAsync(_pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.Equal("minimal", result.Title); + Assert.Single(result.Spine); + } + + [SupportedOSPlatform("windows")] + [Fact] + public async Task GetResourceAsync_WhenCalledForAPage_ShouldRenderThePageImage() + { + // Arrange + string workingDirectory = Path.Combine(_temporaryDirectory, "work"); + + // Act + byte[] result = await _sut.GetResourceAsync(_pdfPath, workingDirectory, "page:1", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotEmpty(result); + } + + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectory)) + Directory.Delete(_temporaryDirectory, recursive: true); + } +} + diff --git a/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Lumina.Plugins.Pdf.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Lumina.Plugins.Pdf.UnitTests.csproj new file mode 100644 index 00000000..e5717587 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Pdf.UnitTests/Lumina.Plugins.Pdf.UnitTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 7183f83e..3d3dc530 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Fixtures.Responses.Common; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index a222d23c..77e5847c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Fixtures.Responses.Common; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs new file mode 100644 index 00000000..5aaa7e12 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -0,0 +1,147 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingAvailabilityEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetReadingAvailabilityEndpoint _sut; + private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new(); + private readonly ReadingAvailabilityResponseFixture _readingAvailabilityResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetReadingAvailabilityEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingAvailability() + { + // Arrange + GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenBookIsNotAvailable_ShouldReturnOkResultWithUnavailableReadingAvailability() + { + // Arrange + GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + Assert.False(okResult.Value.IsAvailable); + Assert.Equal("ReaderDisabled", okResult.Value.ErrorCode); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Reading.BookNotFound", problemResult.ProblemDetails.Title); + Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingAvailabilityQueryToSender() + { + // Arrange + GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingAvailabilityResponse response = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.BookId == request.BookId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From(_readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null)); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs new file mode 100644 index 00000000..7d8bdbb2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingManifestEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetReadingManifestEndpoint _sut; + private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new(); + private readonly ReadingManifestResponseFixture _readingManifestResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetReadingManifestEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingManifest() + { + // Arrange + GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Reading.BookNotFound", problemResult.ProblemDetails.Title); + Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingManifestQueryToSender() + { + // Arrange + GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingManifestResponse response = _readingManifestResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.BookId == request.BookId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From(_readingManifestResponseFixture.Create()); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs new file mode 100644 index 00000000..ec3878a6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingResourceEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetReadingResourceEndpoint _sut; + private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new(); + private readonly ReadingResourceDataDtoFixture _readingResourceDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetReadingResourceEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnBytesResultWithResourceData() + { + // Arrange + GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + FileContentHttpResult bytesResult = Assert.IsType(result); + Assert.Equal(expectedResponse.Data, bytesResult.FileContents); + Assert.Equal(expectedResponse.MimeType, bytesResult.ContentType); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Reading.ResourceNotFound", "ResourceNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Reading.ResourceNotFound", problemResult.ProblemDetails.Title); + Assert.Equal("ResourceNotFound", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingResourceQueryToSender() + { + // Arrange + GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingResourceDataDto response = _readingResourceDataDtoFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.BookId == request.BookId && query.ResourceKey == request.ResourceKey), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From(_readingResourceDataDtoFixture.Create()); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs new file mode 100644 index 00000000..b36af42e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingSectionEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetReadingSectionEndpoint _sut; + private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new(); + private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetReadingSectionEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingSection() + { + // Arrange + GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: request.LocationRef); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Reading.SectionNotFound", "SectionNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Reading.SectionNotFound", problemResult.ProblemDetails.Title); + Assert.Equal("SectionNotFound", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingSectionQueryToSender() + { + // Arrange + GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ReadingSectionDto response = _readingSectionDtoFixture.Create(locationRef: request.LocationRef); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.BookId == request.BookId && query.LocationRef == request.LocationRef), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From(_readingSectionDtoFixture.Create(locationRef: request.LocationRef)); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs new file mode 100644 index 00000000..fa0871ad --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryBookReaders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryBookReadersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryBookReadersEndpoint _sut; + private readonly GetLibraryBookReadersRequestFixture _getLibraryBookReadersRequestFixture = new(); + private readonly LibraryBookReaderResponseFixture _libraryBookReaderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryBookReadersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookReaders() + { + // Arrange + GetLibraryBookReadersRequest request = _getLibraryBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _libraryBookReaderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryBookReadersRequest request = _getLibraryBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryBookReadersQueryToSender() + { + // Arrange + GetLibraryBookReadersRequest request = _getLibraryBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList response = _libraryBookReaderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == request.LibraryId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryBookReadersRequest request = _getLibraryBookReadersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs new file mode 100644 index 00000000..757db7bc --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryBookReaderEnabledEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly SetLibraryBookReaderEnabledEndpoint _sut; + private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetLibraryBookReaderEnabledEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() + { + // Arrange + SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Success, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryBookReaderEnabledCommandToSender() + { + // Arrange + SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == request.LibraryId && + command.PluginId == request.PluginId && + command.IsEnabled == request.IsEnabled), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs new file mode 100644 index 00000000..9339fe4d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetBookReaders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookReadersEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetBookReadersEndpoint _sut; + private readonly GetBookReadersRequestFixture _requestFixture = new(); + private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetBookReadersEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithBookReaders() + { + // Arrange + GetBookReadersRequest request = _requestFixture.Create(); + LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), Arg.Any()) + .Returns(readers); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(readers.Length, jsonDocument.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestBookReadersFromApi() + { + // Arrange + GetBookReadersRequest request = _requestFixture.Create(); + LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), Arg.Any()) + .Returns(readers); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BOOK_READERS.Replace("{libraryId}", request.LibraryId.ToString()), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs new file mode 100644 index 00000000..82e2b72d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using EmptyRequest = Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetBookReaderEnabledEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly SetBookReaderEnabledEndpoint _sut; + private readonly SetBookReaderEnabledRequestFixture _requestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetBookReaderEnabledEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJson() + { + // Arrange + SetBookReaderEnabledRequest request = _requestFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new EmptyRequest()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendBookReaderEnabledChangeToApi() + { + // Arrange + SetBookReaderEnabledRequest request = _requestFixture.Create(); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new EmptyRequest()); + string expectedEndpoint = ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{pluginId}", request.PluginId.ToString()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + expectedEndpoint, + Arg.Is(payload => + payload.LibraryId == request.LibraryId && + payload.PluginId == request.PluginId && + payload.IsEnabled == request.IsEnabled), + Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs index e93f06a1..88b6c5d5 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -83,6 +83,7 @@ public class BooksIndexViewEndpointTests .Returns(expectedLibrary); _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items"); _mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.READ, Arg.Any()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read"); _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "
content
", script: ""))); @@ -101,6 +102,10 @@ public class BooksIndexViewEndpointTests string.Equals( page.PageData["itemsUrl"] as string, "http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items", + StringComparison.Ordinal) && + string.Equals( + page.PageData["readUrl"] as string, + "http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read", StringComparison.Ordinal)), Arg.Is(requestedThemeId => requestedThemeId == null), Arg.Any()); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs new file mode 100644 index 00000000..62b4b8b4 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Reading; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Reading; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingAvailabilityEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetReadingAvailabilityEndpoint _sut; + private readonly ReadingAvailabilityDtoFixture _readingAvailabilityDtoFixture = new(); + private readonly GetBookReadingAvailabilityRequestFixture _requestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetReadingAvailabilityEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenBookIsAvailable_ShouldReturnSuccessJson() + { + // Arrange + GetBookReadingAvailabilityRequest request = _requestFixture.Create(); + ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true); + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + .Returns(availability); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(availability.LibraryId, jsonDocument.RootElement.GetProperty("libraryId").GetGuid()); + } + + [Fact] + public async Task ExecuteAsync_WhenBookIsNotAvailable_ShouldReturnUnavailableJsonWithErrorCode() + { + // Arrange + GetBookReadingAvailabilityRequest request = _requestFixture.Create(); + ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled"); + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + .Returns(availability); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("ReaderDisabled", jsonDocument.RootElement.GetProperty("errorCode").GetString()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingAvailabilityFromApi() + { + // Arrange + GetBookReadingAvailabilityRequest request = new(BookId: Guid.NewGuid()); + ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true); + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + .Returns(availability); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs new file mode 100644 index 00000000..a6ca715c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -0,0 +1,131 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Reading; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Reading; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingManifestEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetReadingManifestEndpoint _sut; + private readonly GetBookReadingManifestRequestFixture _requestFixture = new(); + private readonly ReadingManifestDtoFixture _readingManifestDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetReadingManifestEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithManifest() + { + // Arrange + GetBookReadingManifestRequest request = _requestFixture.Create(); + ReadingManifestDto manifest = _readingManifestDtoFixture.Create(); + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + .Returns(manifest); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(manifest.Title, jsonDocument.RootElement.GetProperty("data").GetProperty("title").GetString()); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsNoReaderAvailable_ShouldReturnDistinctErrorCodeJson() + { + // Arrange + GetBookReadingManifestRequest request = _requestFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "NoReaderAvailable"), HttpStatusCode.NotFound)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NoReaderAvailable", jsonDocument.RootElement.GetProperty("errorCode").GetString()); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsReaderDisabled_ShouldReturnDistinctErrorCodeJson() + { + // Arrange + GetBookReadingManifestRequest request = _requestFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "ReaderDisabled"), HttpStatusCode.NotFound)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("ReaderDisabled", jsonDocument.RootElement.GetProperty("errorCode").GetString()); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsUnrelatedError_ShouldRethrow() + { + // Arrange + GetBookReadingManifestRequest request = _requestFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns>(_ => throw new ApiException(_problemDetailsDtoFixture.Create(detail: "BookNotFound"), HttpStatusCode.NotFound)); + + // Act + Func> act = () => _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await Assert.ThrowsAsync(act); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingManifestFromApi() + { + // Arrange + GetBookReadingManifestRequest request = _requestFixture.Create(); + ReadingManifestDto manifest = _readingManifestDtoFixture.Create(); + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + .Returns(manifest); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs new file mode 100644 index 00000000..21dc7f3a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingResourceEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetReadingResourceEndpoint _sut; + private readonly GetBookReadingResourceRequestFixture _requestFixture = new(); + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetReadingResourceEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnBytesResultWithResourceData() + { + // Arrange + GetBookReadingResourceRequest request = _requestFixture.Create(); + BlobDataDto blob = _blobDataDtoFixture.Create(contentType: "image/png"); + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .Returns(blob); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + FileContentHttpResult bytesResult = Assert.IsType(result); + Assert.Equal(blob.Data, bytesResult.FileContents); + Assert.Equal(blob.ContentType, bytesResult.ContentType); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingResourceFromApi() + { + // Arrange + GetBookReadingResourceRequest request = _requestFixture.Create(); + BlobDataDto blob = _blobDataDtoFixture.Create(); + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .Returns(blob); + string expectedEndpoint = ApiRoutes.Books.GET_BOOK_READING_RESOURCE + .Replace("{bookId}", request.BookId.ToString()) + .Replace("{resourceKey}", Uri.EscapeDataString(request.ResourceKey)); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs new file mode 100644 index 00000000..dd7d29cf --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Reading; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Reading; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetReadingSectionEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetReadingSectionEndpoint _sut; + private readonly GetBookReadingSectionRequestFixture _requestFixture = new(); + private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetReadingSectionEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithSection() + { + // Arrange + GetBookReadingSectionRequest request = _requestFixture.Create(); + ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: request.LocationRef); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(section); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(section.LocationRef, jsonDocument.RootElement.GetProperty("data").GetProperty("locationRef").GetString()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingSectionFromApi() + { + // Arrange + GetBookReadingSectionRequest request = _requestFixture.Create(); + ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: request.LocationRef); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(section); + string expectedEndpoint = ApiRoutes.Books.GET_BOOK_READING_SECTION + .Replace("{bookId}", request.BookId.ToString()) + .Replace("{locationRef}", Uri.EscapeDataString(request.LocationRef)); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs new file mode 100644 index 00000000..9f7ac7b5 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointTests.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.Read; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReadViewEndpointTests +{ + private readonly ReadViewEndpoint _sut = Factory.Create(); + private readonly ReadBookViewRequestFixture _requestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ReadViewEndpointTests() + { + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read"; + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnTheReadRazorView() + { + // Arrange + ReadBookViewRequest request = _requestFixture.Create(); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + Assert.IsType(result); + } +} From fb0aa431df7734903f5fff6e727627291f79345a Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 2 Sep 2026 04:46:06 -0700 Subject: [PATCH 3/4] Updates architecture diagrams with the book reading flow --- .../architecture/1 system-context-diagram.puml | 4 ++-- docs/technical/architecture/2 container-diagram.puml | 5 ++++- .../3.1 component-web-client-diagram.puml | 8 ++++++-- .../3.2 component-api-server-diagram.puml | 11 +++++++++++ 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/docs/technical/architecture/1 system-context-diagram.puml b/docs/technical/architecture/1 system-context-diagram.puml index acd64d25..7231e99d 100644 --- a/docs/technical/architecture/1 system-context-diagram.puml +++ b/docs/technical/architecture/1 system-context-diagram.puml @@ -7,11 +7,11 @@ title System Context diagram for Lumina Media Library Manager Person(user, "Home User", "A person who wants to manage and stream their personal media collection") Person(admin, "Administrator", "A person who manages the media library system") -System(lumina, "Lumina 1.1", "Allows users to organize, manage and stream their personal media content [detailed in '2 container-diagram.puml']") +System(lumina, "Lumina 1.1", "Allows users to organize, manage, stream and read their personal media content [detailed in '2 container-diagram.puml']") System_Ext(metadataProvider, "Media Metadata Services", "External services that provide media information and metadata (TMDB, TVDB, GoodReads, MusicBrainz, etc)") -Rel(user, lumina, "Views and streams media content") +Rel(user, lumina, "Views, streams and reads media content") Rel(admin, lumina, "Manages media library and system settings") Rel(lumina, metadataProvider, "Retrieves media metadata and artwork") diff --git a/docs/technical/architecture/2 container-diagram.puml b/docs/technical/architecture/2 container-diagram.puml index 26c852c8..b39ac302 100644 --- a/docs/technical/architecture/2 container-diagram.puml +++ b/docs/technical/architecture/2 container-diagram.puml @@ -10,11 +10,13 @@ Person(admin, "Administrator", "A person who manages the media library system") System_Boundary(c1, "Lumina 1.1") { Container(webapp, "Web Application Client 2.1", "ASP.NET Core MVC", "Delivers server-rendered views with dynamic client-side functionality for media management and playback [detailed in '3.1 component-web-client-diagram.puml']") - Container(api, "API Server 2.2", "ASP.NET Core", "Provides media management functionality via a REST API, processes media tasks, and manages metadata synchronization [detailed in '3.2 component-api-server-diagram.puml']") + Container(api, "API Server 2.2", "ASP.NET Core", "Provides media management functionality via a REST API, processes media tasks, manages metadata synchronization, and serves books for reading through format plugins [detailed in '3.2 component-api-server-diagram.puml']") ContainerDb(db, "Database", "SQLite", "Stores user data, media metadata, library configuration, automated jobs information, etc") Container(filestore, "Media Store", "File System", "Stores the actual media files") + + Container(readCache, "Reading Cache", "File System", "Temporary directory in the API output, wiped at startup, where the reader plugins extract the contents of the books") } System_Ext(metadata, "Media Information Services", "External services like TMDB, TVDB, GoodReads, MusicBrainz, that provide media metadata") @@ -24,6 +26,7 @@ Rel(admin, webapp, "Manages media library and system settings", "HTTPS") Rel(webapp, api, "Makes API calls to", "JSON/HTTPS") Rel(api, db, "Reads from and writes to", "SQL") Rel(api, filestore, "Reads from and writes to") +Rel(api, readCache, "Reads from and writes to", "File system") Rel(api, metadata, "Retrieves metadata from", "HTTPS") caption [Container] Lumina 1.1 diff --git a/docs/technical/architecture/3.1 component-web-client-diagram.puml b/docs/technical/architecture/3.1 component-web-client-diagram.puml index 6cac77f4..4c047f64 100644 --- a/docs/technical/architecture/3.1 component-web-client-diagram.puml +++ b/docs/technical/architecture/3.1 component-web-client-diagram.puml @@ -9,24 +9,28 @@ Container_Ext(api, "API Server 2.2", "Lumina.Presentation.Api", "Provides media Container_Boundary(wb, "Web Application 2.1") { Component(fileSystem, "File System Management", "ASP.NET MVC Controllers", "Handles file system operations including drives, directories, and files browsing") - Component(library, "Library Management", "ASP.NET MVC Controllers", "Manages media libraries and their content (books, etc)") + Component(library, "Library Management", "ASP.NET MVC Controllers", "Manages media libraries and their content (books, etc); the library edit page lets the owner enable or disable the reader plugins per library") + + Component(bookReader, "Book Reading", "FastEndpoints + JavaScript", "Serves the book reader view and proxies the reading manifest, section and resource endpoints to the API") Component(admin, "Administration", "ASP.NET MVC Controllers", "Handles system administration and configuration") Component(users, "User Management", "ASP.NET MVC Controllers", "Handles authentication and user management") - Component(clientJs, "Client-Side Logic", "JavaScript", "Handles dynamic page updates and persistent media playback") + Component(clientJs, "Client-Side Logic", "JavaScript", "Handles dynamic page updates, persistent media playback, and the book reader (table of contents, page navigation, font size)") Component(httpClient, "API HTTP Client", "C# TypedHttpClient", "Handles communication with the API server") } Rel(fileSystem, httpClient, "Uses") Rel(library, httpClient, "Uses") +Rel(bookReader, httpClient, "Uses") Rel(admin, httpClient, "Uses") Rel(users, httpClient, "Uses") Rel(httpClient, api, "Makes API calls to", "JSON/HTTPS") Rel(clientJs, fileSystem, "Makes AJAX calls to") Rel(clientJs, library, "Makes AJAX calls to") +Rel(clientJs, bookReader, "Makes AJAX calls to") Rel(clientJs, admin, "Makes AJAX calls to") Rel(clientJs, users, "Makes AJAX calls to") diff --git a/docs/technical/architecture/3.2 component-api-server-diagram.puml b/docs/technical/architecture/3.2 component-api-server-diagram.puml index e6230aea..4e800346 100644 --- a/docs/technical/architecture/3.2 component-api-server-diagram.puml +++ b/docs/technical/architecture/3.2 component-api-server-diagram.puml @@ -17,23 +17,34 @@ Container_Boundary(api, "API Server 2.2") { Component(backgroundServices, "Background Services 3.2.1", ".NET Worker Services", "Handles media scanning, metadata synchronization and other maintenance tasks [detailed in '4.1 code-media-library-scanning-diagram.puml']") + Component(bookReading, "Book Reading 3.2.2", "Application + Infrastructure services", "Resolves the reader plugin of a book, checks its per-library enablement, extracts the book into the reading cache on first access, sanitizes every section, and serves the reading manifest, sections and resources") + + Component(readerPlugins, "Book Reader Plugins", "Lumina.Plugins.Epub, Lumina.Plugins.Pdf", "Decode a book format into a normalized reading document (spine, table of contents, sections, resources), loaded into the host by the plugin loader") + Component(repositories, "Repositories", "EF Core", "Provides data access abstraction for domain entities") } ContainerDb(db, "Database", "SQLite", "Stores user data, media metadata, and system configuration") +Container(readCache, "Reading Cache", "File System", "Temporary directory in the API output, wiped at startup, where the reader plugins extract the contents of the books") + System_Ext(metadataServices, "External Metadata Services", "Provides media information (TMDB, TVDB, GoodReads, MusicBrainz, etc)") Rel(webapp, endpoints, "Makes API calls to", "JSON/HTTPS") Rel(endpoints, mediaManagement, "Uses") Rel(endpoints, userManagement, "Uses") Rel(endpoints, fileSystem, "Uses") +Rel(endpoints, bookReading, "Uses") Rel(mediaManagement, repositories, "Uses") Rel(userManagement, repositories, "Uses") Rel(fileSystem, repositories, "Uses") Rel(backgroundServices, mediaManagement, "Uses") Rel(repositories, db, "Reads from and writes to", "SQL") Rel(mediaManagement, metadataServices, "Retrieves metadata from", "HTTPS") +Rel(bookReading, readerPlugins, "Resolves and invokes") +Rel(bookReading, repositories, "Reads the per-library reader enablement") +Rel(bookReading, readCache, "Extracts into and serves from", "File system") +Rel(readerPlugins, readCache, "Extracts into", "File system") caption [Component] Lumina - API Server 2.2 (Lumina.Presentation.Api) From 2bdb2b2d19ae80675e14687fe452608d0ef1dae2 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 2 Sep 2026 05:34:17 -0700 Subject: [PATCH 4/4] Adds API and architecture documentation for the book reading feature --- README.md | 1 + docs/technical/api/Api.Book.md | 130 ++++++++++ docs/technical/api/plugins/Api.Plugins.md | 65 +++++ .../api/users-management/Api.Settings.md | 10 +- .../architecture/1 system-context-diagram.svg | 2 +- .../architecture/2 container-diagram.svg | 2 +- .../3.1 component-web-client-diagram.svg | 2 +- .../3.2 component-api-server-diagram.puml | 4 +- .../3.2 component-api-server-diagram.svg | 2 +- .../4.2 code-book-reading-diagram.puml | 243 ++++++++++++++++++ .../4.2 code-book-reading-diagram.svg | 1 + .../books/GetReadingAvailability.http | 2 + .../requests/books/GetReadingManifest.http | 2 + .../requests/books/GetReadingResource.http | 2 + .../requests/books/GetReadingSection.http | 2 + .../plugins/GetLibraryBookReaders.http | 2 + .../plugins/SetLibraryBookReaderEnabled.http | 9 + .../settings/UpdateUserSettings.http | 5 +- src/Lumina.sln | 2 + 19 files changed, 479 insertions(+), 9 deletions(-) create mode 100644 docs/technical/architecture/4.2 code-book-reading-diagram.puml create mode 100644 docs/technical/architecture/4.2 code-book-reading-diagram.svg create mode 100644 docs/technical/requests/books/GetReadingAvailability.http create mode 100644 docs/technical/requests/books/GetReadingManifest.http create mode 100644 docs/technical/requests/books/GetReadingResource.http create mode 100644 docs/technical/requests/books/GetReadingSection.http create mode 100644 docs/technical/requests/plugins/GetLibraryBookReaders.http create mode 100644 docs/technical/requests/plugins/SetLibraryBookReaderEnabled.http diff --git a/README.md b/README.md index 2bf76a5b..35eeace9 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ For those with technical curiosities, here are some goodies to browse through: 3. [3.1 Component Web Client diagram](./docs/technical/architecture/3.1%20component-web-client-diagram.svg) 4. [3.2 Component API Server diagram](./docs/technical/architecture/3.2%20component-api-server-diagram.svg) 5. [4.1 Code media library scanning diagram](./docs/technical/architecture/4.1%20code-media-library-scanning-diagram.svg) +6. [4.2 Code book reading diagram](./docs/technical/architecture/4.2%20code-book-reading-diagram.svg) - Also for Software Architects, you might want to take a look at the Architecture Decision Log, where you may find important stories from the past of Lumina's development, like [this one](./docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md), and others like it. ## Telemetry and Observability diff --git a/docs/technical/api/Api.Book.md b/docs/technical/api/Api.Book.md index c4a4e996..b5709b2e 100644 --- a/docs/technical/api/Api.Book.md +++ b/docs/technical/api/Api.Book.md @@ -14,6 +14,18 @@ - [Get Books Lite](#get-books-lite) - [Get Books Lite Request](#get-books-lite-request) - [Get Books Lite Response](#get-books-lite-response) + - [Get Reading Availability](#get-reading-availability) + - [Get Reading Availability Request](#get-reading-availability-request) + - [Get Reading Availability Response](#get-reading-availability-response) + - [Get Reading Manifest](#get-reading-manifest) + - [Get Reading Manifest Request](#get-reading-manifest-request) + - [Get Reading Manifest Response](#get-reading-manifest-response) + - [Get Reading Resource](#get-reading-resource) + - [Get Reading Resource Request](#get-reading-resource-request) + - [Get Reading Resource Response](#get-reading-resource-response) + - [Get Reading Section](#get-reading-section) + - [Get Reading Section Request](#get-reading-section-request) + - [Get Reading Section Response](#get-reading-section-response) ## Book @@ -393,3 +405,121 @@ GET api/v1/books/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage "numberOfPages": 1 } ``` + +### Get Reading Availability + +#### Get Reading Availability Request + +```js +GET api/v1/books/{bookId}/reading/availability +``` + +Reports whether the book identified by `bookId` can be opened for reading: the book reader that supports the format of the book is resolved and its enablement for the media library of the book is checked, without extracting the book. When the book cannot be read, the response carries the code of the error preventing it, so the client can tell a missing book reader apart from a disabled one. + +#### Get Reading Availability Response + +```js +200 Ok +``` + +```json +{ + "bookId": "32b336e8-dafc-4a08-9dec-9454e66dd55d", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "isAvailable": true, + "errorCode": null +} +``` + +### Get Reading Manifest + +#### Get Reading Manifest Request + +```js +GET api/v1/books/{bookId}/reading/manifest +``` + +Opens the book identified by `bookId` for reading by extracting its contents through the book reader that is enabled for its media library, and returns the reading manifest: the title and author of the book, its hierarchical table of contents, its ordered spine of reading sections, the keys of its resources, and whether it has extractable text content. A scanned book, whose pages are only images, has no text content and is displayed as page images. + +#### Get Reading Manifest Response + +```js +200 Ok +``` + +```json +{ + "title": "The Fellowship of the Ring", + "author": "J.R.R. Tolkien", + "coverResourceKey": "0f4d6e2b1c9a4f3e8d7c6b5a4f3e2d1c", + "tableOfContents": [ + { + "label": "Chapter One", + "locationRef": "chapter1", + "children": [ + { + "label": "Part One", + "locationRef": "chapter1", + "children": [] + } + ] + } + ], + "spine": [ + { + "locationRef": "chapter1", + "title": "Chapter One" + }, + { + "locationRef": "chapter2", + "title": "Chapter Two" + } + ], + "resourceKeys": [ + "0f4d6e2b1c9a4f3e8d7c6b5a4f3e2d1c" + ], + "hasTextContent": true +} +``` + +### Get Reading Section + +#### Get Reading Section Request + +```js +GET api/v1/books/{bookId}/reading/sections/{locationRef} +``` + +Returns the reading section identified by `locationRef` of the book identified by `bookId`. The section content is sanitized by the host before it is served, and its references to the resources of the book are resolved by the client through the resource endpoint. The `locationRef` of a section is taken from the spine of the reading manifest of the book. + +#### Get Reading Section Response + +```js +200 Ok +``` + +```json +{ + "locationRef": "chapter1", + "title": "Chapter One", + "contentHtml": "

Chapter One

First paragraph.

" +} +``` + +### Get Reading Resource + +#### Get Reading Resource Request + +```js +GET api/v1/books/{bookId}/reading/resources/{resourceKey} +``` + +Returns the binary resource identified by `resourceKey` of the book identified by `bookId` (for example an image, a font, or a stylesheet of the book, or a page image of a scanned PDF that is rendered on demand). The `resourceKey` of a resource is taken from the reading manifest of the book. + +#### Get Reading Resource Response + +```js +200 Ok +``` + +The response is the raw bytes of the resource, served with the `Content-Type` of the resource and with `X-Content-Type-Options: nosniff`. A resource whose declared media type could be rendered as an active document (for example an SVG) is served as an opaque binary download instead. diff --git a/docs/technical/api/plugins/Api.Plugins.md b/docs/technical/api/plugins/Api.Plugins.md index 4f4b87ce..79e8bb04 100644 --- a/docs/technical/api/plugins/Api.Plugins.md +++ b/docs/technical/api/plugins/Api.Plugins.md @@ -23,6 +23,12 @@ - [Reorder Library Metadata Providers](#reorder-library-metadata-providers) - [Reorder Library Metadata Providers Request](#reorder-library-metadata-providers-request) - [Reorder Library Metadata Providers Response](#reorder-library-metadata-providers-response) + - [Get Library Book Readers](#get-library-book-readers) + - [Get Library Book Readers Request](#get-library-book-readers-request) + - [Get Library Book Readers Response](#get-library-book-readers-response) + - [Set Library Book Reader Enabled](#set-library-book-reader-enabled) + - [Set Library Book Reader Enabled Request](#set-library-book-reader-enabled-request) + - [Set Library Book Reader Enabled Response](#set-library-book-reader-enabled-response) ## Plugins @@ -207,3 +213,62 @@ PUT api/v1/libraries/{libraryId}/metadata-providers/reorder ```js 200 Ok ``` + +### Get Library Book Readers + +#### Get Library Book Readers Request + +```js +GET api/v1/libraries/{libraryId}/book-readers +``` + +Returns the book readers available for the media library, one entry per plugin that provides a book reader, along with whether the reader is enabled for the media library. A book can be opened for reading only through a book reader that is enabled for its media library. + +#### Get Library Book Readers Response + +```js +200 Ok +``` + +```json +[ + { + "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", + "name": "EPUB Reader", + "supportedExtensions": [ + ".epub" + ], + "isEnabled": true + }, + { + "pluginId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "name": "PDF Reader", + "supportedExtensions": [ + ".pdf" + ], + "isEnabled": false + } +] +``` + +### Set Library Book Reader Enabled + +#### Set Library Book Reader Enabled Request + +```js +PUT api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled +``` + +```json +{ + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", + "isEnabled": true +} +``` + +#### Set Library Book Reader Enabled Response + +```js +200 Ok +``` diff --git a/docs/technical/api/users-management/Api.Settings.md b/docs/technical/api/users-management/Api.Settings.md index 1e3e73b4..53993dee 100644 --- a/docs/technical/api/users-management/Api.Settings.md +++ b/docs/technical/api/users-management/Api.Settings.md @@ -33,7 +33,10 @@ Returns the settings of the currently authenticated user. "isPaginationEnabled": true, "itemsPerPage": 50, "ignoreThePrefixForAlphaPicker": true, - "isThemeCachingEnabled": true + "isThemeCachingEnabled": true, + "shouldAggregateMetadataWhenMissing": true, + "shouldRenderPdfAsImages": false, + "shouldPreserveBookStyles": true } ``` @@ -52,7 +55,10 @@ Updates the settings of the currently authenticated user. "isPaginationEnabled": true, "itemsPerPage": 50, "ignoreThePrefixForAlphaPicker": true, - "isThemeCachingEnabled": true + "isThemeCachingEnabled": true, + "shouldAggregateMetadataWhenMissing": true, + "shouldRenderPdfAsImages": false, + "shouldPreserveBookStyles": true } ``` diff --git a/docs/technical/architecture/1 system-context-diagram.svg b/docs/technical/architecture/1 system-context-diagram.svg index 6b09f770..35fb094d 100644 --- a/docs/technical/architecture/1 system-context-diagram.svg +++ b/docs/technical/architecture/1 system-context-diagram.svg @@ -1 +1 @@ -System Context diagram for Lumina Media Library ManagerHome User A person who wants to manageand stream their personalmedia collectionAdministrator A person who manages themedia library systemLumina 1.1 Allows users to organize,manage and stream theirpersonal media content[detailed in '2container-diagram.puml']Media Metadata Services External services that providemedia information andmetadata (TMDB, TVDB,GoodReads, MusicBrainz, etc)Views and streams mediacontentManages media libraryand system settingsRetrieves media metadataand artworkLegend personsystemexternal personexternal system[System Context] LuminaThe system context diagram for the Lumina Media Library Manager - created with PlantUML \ No newline at end of file +System Context diagram for Lumina Media Library ManagerHome User A person who wants to manageand stream their personalmedia collectionAdministrator A person who manages themedia library systemLumina 1.1 Allows users to organize,manage, stream and read theirpersonal media content[detailed in '2container-diagram.puml']Media Metadata Services External services that providemedia information andmetadata (TMDB, TVDB,GoodReads, MusicBrainz, etc)Views, streams and reads mediacontentManages media library and systemsettingsRetrieves media metadata andartworkLegend personsystemexternal personexternal system[System Context] LuminaThe system context diagram for the Lumina Media Library Manager - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/2 container-diagram.svg b/docs/technical/architecture/2 container-diagram.svg index 6d54a096..00c22baa 100644 --- a/docs/technical/architecture/2 container-diagram.svg +++ b/docs/technical/architecture/2 container-diagram.svg @@ -1 +1 @@ -Container diagram for Lumina 1.1Lumina 1.1[System]Web Application Client 2.1[ASP.NET Core MVC] Delivers server-rendered viewswith dynamic client-sidefunctionality for mediamanagement and playback[detailed in '3.1component-web-client-diagram.puml']API Server 2.2[ASP.NET Core] Provides media managementfunctionality via a REST API,processes media tasks, andmanages metadatasynchronization [detailed in '3.2component-api-server-diagram.puml']Database[SQLite] Stores user data, mediametadata, library configuration,automated jobs information, etcMedia Store[File System] Stores the actual media filesHome User A person who wants to manageand stream their personalmedia collectionAdministrator A person who manages themedia library systemMedia InformationServices External services like TMDB,TVDB, GoodReads,MusicBrainz, that provide mediametadataUses[HTTPS]Manages media libraryand system settings[HTTPS]Makes API calls to[JSON/HTTPS]Reads from and writes to[SQL]Reads from and writes toRetrieves metadata from[HTTPS]Legend personsystemcontainerexternal personexternal systemexternal container[Container] Lumina 1.1The container diagram for the Lumina 1.1 - created with PlantUML \ No newline at end of file +Container diagram for Lumina 1.1Lumina 1.1[system]Web Application Client2.1[ASP.NET Core MVC] Delivers server-rendered viewswith dynamic client-sidefunctionality for mediamanagement and playback[detailed in '3.1component-web-client-diagram.puml']API Server 2.2[ASP.NET Core] Provides media managementfunctionality via a REST API,processes media tasks,manages metadatasynchronization, and servesbooks for reading throughformat plugins [detailed in '3.2component-api-server-diagram.puml']Database[SQLite] Stores user data, mediametadata, library configuration,automated jobs information, etcMedia Store[File System] Stores the actual media filesReading Cache[File System] Temporary directory in the APIoutput, wiped at startup, wherethe reader plugins extract thecontents of the booksHome User A person who wants to manageand stream their personalmedia collectionAdministrator A person who manages themedia library systemMedia InformationServices External services like TMDB,TVDB, GoodReads,MusicBrainz, that provide mediametadataUses[HTTPS]Manages media library and systemsettings[HTTPS]Makes API calls to[JSON/HTTPS]Reads from and writes to[SQL]Reads from and writes toReads from and writes to[File system]Retrieves metadata from[HTTPS]Legend personsystemcontainerexternal personexternal systemexternal container[Container] Lumina 1.1The container diagram for the Lumina 1.1 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/3.1 component-web-client-diagram.svg b/docs/technical/architecture/3.1 component-web-client-diagram.svg index 2468239d..1a888bea 100644 --- a/docs/technical/architecture/3.1 component-web-client-diagram.svg +++ b/docs/technical/architecture/3.1 component-web-client-diagram.svg @@ -1 +1 @@ -Component diagram for Lumina Web Application Client 2.1Web Application 2.1[Container]File System Management[ASP.NET MVC Controllers] Handles file system operationsincluding drives, directories,and files browsingLibrary Management[ASP.NET MVC Controllers] Manages media libraries andtheir content (books, etc)Administration[ASP.NET MVC Controllers] Handles system administrationand configurationUser Management[ASP.NET MVC Controllers] Handles authentication anduser managementClient-Side Logic[JavaScript] Handles dynamic page updatesand persistent media playbackAPI HTTP Client[C# TypedHttpClient] Handles communication withthe API serverAPI Server 2.2[Lumina.Presentation.Api] Provides media managementfunctionality via JSON/HTTPSAPI [detailed in '3.2component-api-server-diagram.puml']UsesUsesUsesUsesMakes API calls to[JSON/HTTPS]Makes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Component] Lumina - Web Application Client 2.1 (Lumina.Presentation.Web)The component diagram for the Lumina Web Application Client 2.1 - created with PlantUML \ No newline at end of file +Component diagram for Lumina Web Application Client 2.1Web Application 2.1[container]File System Management[ASP.NET MVC Controllers] Handles file system operationsincluding drives, directories, andfiles browsingLibrary Management[ASP.NET MVC Controllers] Manages media libraries andtheir content (books, etc); thelibrary edit page lets the ownerenable or disable the readerplugins per libraryBook Reading[FastEndpoints + JavaScript] Serves the book reader viewand proxies the readingmanifest, section and resourceendpoints to the APIAdministration[ASP.NET MVC Controllers] Handles system administrationand configurationUser Management[ASP.NET MVC Controllers] Handles authentication anduser managementClient-Side Logic[JavaScript] Handles dynamic pageupdates, persistent mediaplayback, and the book reader(table of contents, pagenavigation, font size)API HTTP Client[C# TypedHttpClient] Handles communication withthe API serverAPI Server 2.2[Lumina.Presentation.Api] Provides media managementfunctionality via JSON/HTTPSAPI [detailed in '3.2component-api-server-diagram.puml']UsesUsesUsesUsesUsesMakes API calls to[JSON/HTTPS]Makes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Component] Lumina - Web Application Client 2.1 (Lumina.Presentation.Web)The component diagram for the Lumina Web Application Client 2.1 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/3.2 component-api-server-diagram.puml b/docs/technical/architecture/3.2 component-api-server-diagram.puml index 4e800346..c1edde0a 100644 --- a/docs/technical/architecture/3.2 component-api-server-diagram.puml +++ b/docs/technical/architecture/3.2 component-api-server-diagram.puml @@ -17,9 +17,9 @@ Container_Boundary(api, "API Server 2.2") { Component(backgroundServices, "Background Services 3.2.1", ".NET Worker Services", "Handles media scanning, metadata synchronization and other maintenance tasks [detailed in '4.1 code-media-library-scanning-diagram.puml']") - Component(bookReading, "Book Reading 3.2.2", "Application + Infrastructure services", "Resolves the reader plugin of a book, checks its per-library enablement, extracts the book into the reading cache on first access, sanitizes every section, and serves the reading manifest, sections and resources") + Component(bookReading, "Book Reading 3.2.2", "Application + Infrastructure services", "Resolves the reader plugin of a book, checks its per-library enablement, extracts the book into the reading cache on first access, sanitizes every section, and serves the reading manifest, sections and resources [detailed in '4.2 code-book-reading-diagram.puml']") - Component(readerPlugins, "Book Reader Plugins", "Lumina.Plugins.Epub, Lumina.Plugins.Pdf", "Decode a book format into a normalized reading document (spine, table of contents, sections, resources), loaded into the host by the plugin loader") + Component(readerPlugins, "Book Reader Plugins", "Lumina.Plugins.Epub, Lumina.Plugins.Pdf", "Decode a book format into a normalized reading document (spine, table of contents, sections, resources), loaded into the host by the plugin loader [detailed in '4.2 code-book-reading-diagram.puml']") Component(repositories, "Repositories", "EF Core", "Provides data access abstraction for domain entities") } diff --git a/docs/technical/architecture/3.2 component-api-server-diagram.svg b/docs/technical/architecture/3.2 component-api-server-diagram.svg index 62d32557..e424f40b 100644 --- a/docs/technical/architecture/3.2 component-api-server-diagram.svg +++ b/docs/technical/architecture/3.2 component-api-server-diagram.svg @@ -1 +1 @@ -Component diagram for Lumina API Server 2.2API Server 2.2[Container]API Endpoints[FastEndpoints] Provides REST API endpointsfor media management andstreamingMedia LibraryManagement[Domain Services] Handles media librariesoperations and metadatamanagementUser Management[Domain Services] Handles user authenticationand authorizationFile System Management[Domain Services] Manages file system operationsand media accessBackground Services3.2.1[.NET Worker Services] Handles media scanning,metadata synchronization andother maintenance tasks[detailed in '4.1code-media-library-scanning-diagram.puml']Repositories[EF Core] Provides data accessabstraction for domain entitiesWeb Application Client 2.1[Lumina.Presentation.Web] Provides the user interface[detailed in '3.1component-web-client-diagram.puml']Database[SQLite] Stores user data, mediametadata, and systemconfigurationExternal MetadataServices Provides media information(TMDB, TVDB, GoodReads,MusicBrainz, etc)Makes API calls to[JSON/HTTPS]UsesUsesUsesUsesUsesUsesUsesReads from and writes to[SQL]Retrieves metadata from[HTTPS]Legend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Component] Lumina - API Server 2.2 (Lumina.Presentation.Api)The component diagram for the Lumina API Server 2.2 - created with PlantUML \ No newline at end of file +Component diagram for Lumina API Server 2.2API Server 2.2[container]API Endpoints[FastEndpoints] Provides REST API endpointsfor media management andstreamingMedia LibraryManagement[Domain Services] Handles media librariesoperations and metadatamanagementUser Management[Domain Services] Handles user authenticationand authorizationFile System Management[Domain Services] Manages file system operationsand media accessBackground Services3.2.1[.NET Worker Services] Handles media scanning,metadata synchronization andother maintenance tasks[detailed in '4.1code-media-library-scanning-diagram.puml']Book Reading 3.2.2[Application + Infrastructure services] Resolves the reader plugin of abook, checks its per-libraryenablement, extracts the bookinto the reading cache on firstaccess, sanitizes every section,and serves the readingmanifest, sections andresources [detailed in '4.2code-book-reading-diagram.puml']Book Reader Plugins[Lumina.Plugins.Epub,Lumina.Plugins.Pdf] Decode a book format into anormalized reading document(spine, table of contents,sections, resources), loadedinto the host by the pluginloader [detailed in '4.2code-book-reading-diagram.puml']Repositories[EF Core] Provides data accessabstraction for domain entitiesWeb Application Client2.1[Lumina.Presentation.Web] Provides the user interface[detailed in '3.1component-web-client-diagram.puml']Database[SQLite] Stores user data, mediametadata, and systemconfigurationReading Cache[File System] Temporary directory in the APIoutput, wiped at startup, wherethe reader plugins extract thecontents of the booksExternal MetadataServices Provides media information(TMDB, TVDB, GoodReads,MusicBrainz, etc)Makes API calls to[JSON/HTTPS]UsesUsesUsesUsesUsesUsesUsesUsesReads from and writes to[SQL]Retrieves metadata from[HTTPS]Resolves and invokesReads the per-library readerenablementExtracts into and serves from[File system]Extracts into[File system]Legend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Component] Lumina - API Server 2.2 (Lumina.Presentation.Api)The component diagram for the Lumina API Server 2.2 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/4.2 code-book-reading-diagram.puml b/docs/technical/architecture/4.2 code-book-reading-diagram.puml new file mode 100644 index 00000000..3f319d1d --- /dev/null +++ b/docs/technical/architecture/4.2 code-book-reading-diagram.puml @@ -0,0 +1,243 @@ +@startuml Book Reading and Book Reader Plugins Code +!include + +LAYOUT_WITH_LEGEND() +title Code diagram for Book Reading 3.2.2 and Book Reader Plugins + +skinparam class { + BackgroundColor White + BorderColor Black +} + +' ============================== READING HOST - APPLICATION CONTRACTS ============================== + +interface IBookReadingService { + + GetManifestAsync(bookId: Guid, libraryId: Guid, path: string, libraryType: LibraryType, shouldRenderPdfAsImages: bool, token: CancellationToken): Task> + + GetSectionAsync(bookId: Guid, libraryId: Guid, path: string, libraryType: LibraryType, locationRef: string, shouldRenderPdfAsImages: bool, shouldPreserveStyles: bool, token: CancellationToken): Task> + + GetResourceAsync(bookId: Guid, libraryId: Guid, path: string, libraryType: LibraryType, resourceKey: string, shouldRenderPdfAsImages: bool, token: CancellationToken): Task> + + GetAvailabilityAsync(bookId: Guid, libraryId: Guid, path: string, libraryType: LibraryType, token: CancellationToken): Task> +} + +interface IBookReaderRegistry { + + GetSupportedExtensionsByPluginId(): IReadOnlyDictionary> +} + +interface IBookReaderEnablementCache { + + Get(libraryId: Guid, pluginId: Guid): bool? + + Set(libraryId: Guid, pluginId: Guid, isEnabled: bool) + + Invalidate(libraryId: Guid, pluginId: Guid) + + InvalidateLibrary(libraryId: Guid) + + InvalidatePlugin(pluginId: Guid) +} + +' ============================== READING HOST - INFRASTRUCTURE ============================== + +class BookReadingService { + - _extractions: ConcurrentDictionary + - _bookExtractionLocks: ConcurrentDictionary + - _pluginIdsByReaderKey: IReadOnlyDictionary + - _enablementCache: IBookReaderEnablementCache + + GetManifestAsync(...): Task> + + GetSectionAsync(...): Task> + + GetResourceAsync(...): Task> + + GetAvailabilityAsync(...): Task> +} + +note right of BookReadingService + Serves the manifest, sections and resources of a book: + resolves the reader of the book format, checks the + per-library enablement through the cache, reuses the already + extracted document while the fingerprint of the book file is + unchanged, extracts each rendering preference (text or page + images) into its own directory under the reading cache, and + produces on-demand resources (for example a PDF page render) + once per resource file. +end note + +class BookReaderRegistry { + - _pluginManager: IPluginManager + - _serviceProvider: IServiceProvider + + GetSupportedExtensionsByPluginId(): IReadOnlyDictionary> +} + +note right of BookReaderRegistry + Reads the supported extensions live from the book readers + registered by the loaded plugins, so that a plugin update + that changes its formats never leaves stale configurations. +end note + +class BookReaderEnablementCache { + - _enablements: ConcurrentDictionary<(Guid LibraryId, Guid PluginId), bool> + + Get(libraryId: Guid, pluginId: Guid): bool? + + Set(libraryId: Guid, pluginId: Guid, isEnabled: bool) + + Invalidate(libraryId: Guid, pluginId: Guid) + + InvalidateLibrary(libraryId: Guid) + + InvalidatePlugin(pluginId: Guid) +} + +class ReadingCachePaths { + + DIRECTORY_NAME: string = reading-cache + + {static} GetRootDirectory(): string +} + +note bottom of ReadingCachePaths + The reading cache is a temporary directory in the API output, + wiped at startup, under which every book keeps one directory + per rendering preference (text and images). +end note + +class ReadingContentSanitizer { + + RESOURCE_ATTRIBUTE: string = data-lumina-resource + + {static} Sanitize(html: string, shouldPreserveStyles: bool): string +} + +note right of ReadingContentSanitizer + Sanitizes every reading section with an explicit allowlist of + inert markup, regardless of what the reader plugin produced; + whether the style attribute survives is the per-user choice. +end note + +' ============================== ENABLEMENT PERSISTENCE ============================== + +class LibraryBookReaderConfigurationEntity { + + Id: Guid + + LibraryId: Guid + + PluginId: Guid + + IsEnabled: bool +} + +interface ILibraryBookReaderConfigurationRepository { + + GetByLibraryIdAsync(libraryId: Guid, token: CancellationToken): Task>> + + GetByLibraryAndPluginIdAsync(libraryId: Guid, pluginId: Guid, token: CancellationToken): Task> + + UpsertAsync(configuration: LibraryBookReaderConfigurationEntity, token: CancellationToken): Task> + + DeleteByLibraryIdAsync(libraryId: Guid, token: CancellationToken): Task> + + DeleteByPluginIdAsync(pluginId: Guid, token: CancellationToken): Task> + + DeleteByLibraryIdAndPluginIdsAsync(libraryId: Guid, pluginIds: IEnumerable, token: CancellationToken): Task> +} + +class LibraryBookReaderConfigurationRepository + +class GetLibraryBookReadersQueryHandler { + - _unitOfWork: IUnitOfWork + - _bookReaderRegistry: IBookReaderRegistry + + HandleAsync(query: GetLibraryBookReadersQuery, token: CancellationToken): Task>> +} + +class SetLibraryBookReaderEnabledCommandHandler { + - _unitOfWork: IUnitOfWork + - _enablementCache: IBookReaderEnablementCache + + HandleAsync(command: SetLibraryBookReaderEnabledCommand, token: CancellationToken): Task> +} + +note right of SetLibraryBookReaderEnabledCommandHandler + Enables or disables the book reader of a plugin for a media + library by upserting its configuration row, then invalidates + the enablement cache so that a disabled reader stops being + served immediately. +end note + +' ============================== BOOK READER PLUGINS ============================== + +interface IBookReader { + + SupportedExtensions: IReadOnlyList + + SupportedLibraryTypes: IReadOnlyList + + OpenAsync(path: string, workingDirectory: string, shouldRenderPdfAsImages: bool, token: CancellationToken): Task + + GetResourceAsync(path: string, workingDirectory: string, resourceKey: string, token: CancellationToken): Task +} + +note top of IBookReader + Contract of a reader plugin, implemented in Lumina.Plugins.Contracts. + The plugins are host-trusted: they receive the absolute path of the + book and a working directory to extract into, while the host + sanitizes and contained-checks everything they produce before + serving it to the client. +end note + +class EpubReader { +} + +note right of EpubReader + Reads .epub books of the EBook and Book library types. + EPUB is a ZIP archive, decoded entry by entry with bounded + sizes and archive-contained paths. +end note + +class EpubDocumentParser { + + {static} Parse(epubPath: string, workingDirectory: string, token: CancellationToken): ReadingDocumentDto +} + +class PdfReader { +} + +note right of PdfReader + Reads .pdf books of the EBook and Book library types. + Each page is a reading section; the table of contents comes + from the PDF bookmarks. +end note + +class PdfDocumentParser { + + {static} Parse(pdfPath: string, workingDirectory: string, shouldRenderPdfAsImages: bool, token: CancellationToken): ReadingDocumentDto + + {static} RenderResource(pdfPath: string, resourceKey: string, token: CancellationToken): byte[] +} + +note right of PdfDocumentParser + Extracts the text layer of the pages with PdfPig, and renders + the pages as images with PDFtoImage on demand when the + render-as-images user setting is enabled; file size, page count + and rendered page area are bounded. +end note + +class EpubPlugin { + + Id: Guid + + Name: string = EPUB Reader + + RegisterServices(services: IServiceCollection) +} + +class PdfPlugin { + + Id: Guid + + Name: string = PDF Reader + + RegisterServices(services: IServiceCollection) +} + +' ============================== HOST IMPLEMENTATION RELATIONSHIPS ============================== + +IBookReadingService <|.. BookReadingService : implements +IBookReaderRegistry <|.. BookReaderRegistry : implements +IBookReaderEnablementCache <|.. BookReaderEnablementCache : implements +ILibraryBookReaderConfigurationRepository <|.. LibraryBookReaderConfigurationRepository : implements + +' ============================== READING HOST RELATIONSHIPS ============================== + +BookReadingService --> IBookReaderRegistry : finds the plugin of the book format +BookReadingService --> IBookReaderEnablementCache : checks the per-library enablement +BookReadingService --> ILibraryBookReaderConfigurationRepository : fills the cache on a miss +BookReadingService ..> IBookReader : opens and produces resources +BookReadingService ..> ReadingContentSanitizer : sanitizes section content +BookReadingService ..> ReadingCachePaths : extracts into and serves from + +BookReaderRegistry ..> IBookReader : reads the supported extensions of loaded plugins + +' ============================== ENABLEMENT MANAGEMENT RELATIONSHIPS ============================== + +GetLibraryBookReadersQueryHandler --> ILibraryBookReaderConfigurationRepository : reads configurations +GetLibraryBookReadersQueryHandler --> IBookReaderRegistry : reads supported extensions +SetLibraryBookReaderEnabledCommandHandler --> ILibraryBookReaderConfigurationRepository : upserts the configuration +SetLibraryBookReaderEnabledCommandHandler --> IBookReaderEnablementCache : invalidates the entry + +ILibraryBookReaderConfigurationRepository --> LibraryBookReaderConfigurationEntity : persists + +' ============================== BOOK READER PLUGIN RELATIONSHIPS ============================== + +EpubReader <|.. IBookReader : implements +PdfReader <|.. IBookReader : implements + +EpubReader ..> EpubDocumentParser : parses +PdfReader ..> PdfDocumentParser : parses and renders pages + +EpubPlugin ..> EpubReader : registers as a keyed IBookReader +PdfPlugin ..> PdfReader : registers as a keyed IBookReader + +caption [Code] Lumina - Book Reading 3.2.2 and Book Reader Plugins + +footer The code diagram for the Book Reading 3.2.2 and the Book Reader Plugins - created with PlantUML +@enduml diff --git a/docs/technical/architecture/4.2 code-book-reading-diagram.svg b/docs/technical/architecture/4.2 code-book-reading-diagram.svg new file mode 100644 index 00000000..e137e374 --- /dev/null +++ b/docs/technical/architecture/4.2 code-book-reading-diagram.svg @@ -0,0 +1 @@ +Code diagram for Book Reading 3.2.2 and Book Reader PluginsIBookReadingServiceGetManifestAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingManifestResponse>>GetSectionAsync(bookId: Guid,libraryId: Guid, path: string,libraryType: LibraryType,locationRef: string,shouldRenderPdfAsImages:bool, shouldPreserveStyles:bool, token:CancellationToken):Task<Result<ReadingSectionDto>>GetResourceAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,resourceKey: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,token: CancellationToken):Task<Result<ReadingAvailabilityResponse>>IBookReaderRegistryGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>IBookReaderEnablementCacheGet(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)BookReadingService_extractions:ConcurrentDictionary<ReadingCacheKey,BookExtractionEntry>_bookExtractionLocks:ConcurrentDictionary<ReadingCacheKey,SemaphoreSlim>_pluginIdsByReaderKey:IReadOnlyDictionary<ReaderKey,Guid>_enablementCache:IBookReaderEnablementCacheGetManifestAsync(...):Task<Result<ReadingManifestResponse>>GetSectionAsync(...):Task<Result<ReadingSectionDto>>GetResourceAsync(...):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(...):Task<Result<ReadingAvailabilityResponse>>Serves the manifest, sections andresources of a book:resolves the reader of the bookformat, checks theper-library enablement through thecache, reuses the alreadyextracted document while thefingerprint of the book file isunchanged, extracts eachrendering preference (text or pageimages) into its own directoryunder the reading cache, andproduces on-demand resources(for example a PDF page render)once per resource file.BookReaderRegistry_pluginManager:IPluginManager_serviceProvider:IServiceProviderGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>Reads the supported extensionslive from the book readersregistered by the loaded plugins,so that a plugin updatethat changes its formats neverleaves stale configurations.BookReaderEnablementCache_enablements:ConcurrentDictionary<(GuidLibraryId, Guid PluginId), bool>Get(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)ReadingCachePathsDIRECTORY_NAME: string =reading-cacheGetRootDirectory(): stringThe reading cache is a temporarydirectory in the API output,wiped at startup, under whichevery book keeps one directoryper rendering preference (text andimages).ReadingContentSanitizerRESOURCE_ATTRIBUTE:string = data-lumina-resourceSanitize(html: string,shouldPreserveStyles: bool):stringSanitizes every reading sectionwith an explicit allowlist ofinert markup, regardless of whatthe reader plugin produced;whether the style attributesurvives is the per-user choice.LibraryBookReaderConfigurationEntityId: GuidLibraryId: GuidPluginId: GuidIsEnabled: boolILibraryBookReaderConfigurationRepositoryGetByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>>>GetByLibraryAndPluginIdAsync(libraryId:Guid, pluginId: Guid, token:CancellationToken):Task<Result<LibraryBookReaderConfigurationEntity?>>UpsertAsync(configuration:LibraryBookReaderConfigurationEntity,token: CancellationToken):Task<Result<Updated>>DeleteByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByPluginIdAsync(pluginId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByLibraryIdAndPluginIdsAsync(libraryId:Guid, pluginIds:IEnumerable<Guid>, token:CancellationToken):Task<Result<Deleted>>LibraryBookReaderConfigurationRepositoryGetLibraryBookReadersQueryHandler_unitOfWork: IUnitOfWork_bookReaderRegistry:IBookReaderRegistryHandleAsync(query:GetLibraryBookReadersQuery,token: CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>SetLibraryBookReaderEnabledCommandHandler_unitOfWork: IUnitOfWork_enablementCache:IBookReaderEnablementCacheHandleAsync(command:SetLibraryBookReaderEnabledCommand,token: CancellationToken):Task<Result<Success>>Enables or disables the bookreader of a plugin for a medialibrary by upserting itsconfiguration row, then invalidatesthe enablement cache so that adisabled reader stops beingserved immediately.IBookReaderSupportedExtensions:IReadOnlyList<string>SupportedLibraryTypes:IReadOnlyList<LibraryType>OpenAsync(path: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<ReadingDocumentDto>GetResourceAsync(path: string,workingDirectory: string,resourceKey: string, token:CancellationToken):Task<byte[]>Contract of a reader plugin,implemented inLumina.Plugins.Contracts.The plugins are host-trusted: theyreceive the absolute path of thebook and a working directory toextract into, while the hostsanitizes and contained-checkseverything they produce beforeserving it to the client.EpubReaderReads .epub books of the EBookand Book library types.EPUB is a ZIP archive, decodedentry by entry with boundedsizes and archive-containedpaths.EpubDocumentParserParse(epubPath: string,workingDirectory: string, token:CancellationToken):ReadingDocumentDtoPdfReaderReads .pdf books of the EBookand Book library types.Each page is a reading section;the table of contents comesfrom the PDF bookmarks.PdfDocumentParserParse(pdfPath: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):ReadingDocumentDtoRenderResource(pdfPath:string, resourceKey: string,token: CancellationToken):byte[]Extracts the text layer of thepages with PdfPig, and rendersthe pages as images withPDFtoImage on demand when therender-as-images user setting isenabled; file size, page countand rendered page area arebounded.EpubPluginId: GuidName: string = EPUB ReaderRegisterServices(services:IServiceCollection)PdfPluginId: GuidName: string = PDF ReaderRegisterServices(services:IServiceCollection)implementsimplementsimplementsimplementsfinds the plugin of the book formatchecks the per-library enablementfills the cache on a missopens and produces resourcessanitizes section contentextracts into and serves fromreads the supported extensions ofloaded pluginsreads configurationsreads supported extensionsupserts the configurationinvalidates the entrypersistsimplementsimplementsparsesparses and renders pagesregisters as a keyed IBookReaderregisters as a keyed IBookReaderLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Book Reading 3.2.2 and Book Reader PluginsThe code diagram for the Book Reading 3.2.2 and the Book Reader Plugins - created with PlantUML \ No newline at end of file diff --git a/docs/technical/requests/books/GetReadingAvailability.http b/docs/technical/requests/books/GetReadingAvailability.http new file mode 100644 index 00000000..e5dcdb0e --- /dev/null +++ b/docs/technical/requests/books/GetReadingAvailability.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/books/{{$guid}}/reading/availability +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/books/GetReadingManifest.http b/docs/technical/requests/books/GetReadingManifest.http new file mode 100644 index 00000000..c5d92cab --- /dev/null +++ b/docs/technical/requests/books/GetReadingManifest.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/books/{{$guid}}/reading/manifest +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/books/GetReadingResource.http b/docs/technical/requests/books/GetReadingResource.http new file mode 100644 index 00000000..8133bb5b --- /dev/null +++ b/docs/technical/requests/books/GetReadingResource.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/books/{{$guid}}/reading/resources/0f4d6e2b1c9a4f3e8d7c6b5a4f3e2d1c +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/books/GetReadingSection.http b/docs/technical/requests/books/GetReadingSection.http new file mode 100644 index 00000000..1b382784 --- /dev/null +++ b/docs/technical/requests/books/GetReadingSection.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/books/{{$guid}}/reading/sections/chapter1 +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/plugins/GetLibraryBookReaders.http b/docs/technical/requests/plugins/GetLibraryBookReaders.http new file mode 100644 index 00000000..238914b4 --- /dev/null +++ b/docs/technical/requests/plugins/GetLibraryBookReaders.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/{{$guid}}/book-readers +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/plugins/SetLibraryBookReaderEnabled.http b/docs/technical/requests/plugins/SetLibraryBookReaderEnabled.http new file mode 100644 index 00000000..b340bd38 --- /dev/null +++ b/docs/technical/requests/plugins/SetLibraryBookReaderEnabled.http @@ -0,0 +1,9 @@ +PUT {{host}}/api/v1/libraries/{{$guid}}/book-readers/{{$guid}}/enabled +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "libraryId": "{{$guid}}", + "pluginId": "{{$guid}}", + "isEnabled": true +} diff --git a/docs/technical/requests/users-management/settings/UpdateUserSettings.http b/docs/technical/requests/users-management/settings/UpdateUserSettings.http index d6fdba14..58cb8c67 100644 --- a/docs/technical/requests/users-management/settings/UpdateUserSettings.http +++ b/docs/technical/requests/users-management/settings/UpdateUserSettings.http @@ -6,5 +6,8 @@ Content-Type: application/json "isPaginationEnabled": true, "itemsPerPage": 50, "ignoreThePrefixForAlphaPicker": true, - "isThemeCachingEnabled": true + "isThemeCachingEnabled": true, + "shouldAggregateMetadataWhenMissing": true, + "shouldRenderPdfAsImages": false, + "shouldPreserveBookStyles": true } diff --git a/src/Lumina.sln b/src/Lumina.sln index fe32066e..a06abc9f 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -182,6 +182,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture", "architectur ..\docs\technical\architecture\3.2 component-api-server-diagram.svg = ..\docs\technical\architecture\3.2 component-api-server-diagram.svg ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.puml = ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.puml ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.svg = ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.svg + ..\docs\technical\architecture\4.2 code-book-reading-diagram.puml = ..\docs\technical\architecture\4.2 code-book-reading-diagram.puml + ..\docs\technical\architecture\4.2 code-book-reading-diagram.svg = ..\docs\technical\architecture\4.2 code-book-reading-diagram.svg EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-knowledge-management", "architecture-knowledge-management", "{70B56088-6D3A-481E-9459-79AC6B16FEC1}"