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}"