Merge pull request #184 from BinaryAlley/feature/add-book-reading
Feature/add book reading
No files matched your search
@@ -14,6 +14,7 @@
|
||||
<PackageVersion Include="EntityFrameworkCore.Testing.NSubstitute" Version="10.0.0" />
|
||||
<PackageVersion Include="FastEndpoints" Version="8.2.0" />
|
||||
<PackageVersion Include="FastEndpoints.Swagger" Version="8.2.0" />
|
||||
<PackageVersion Include="HtmlSanitizer" Version="9.2.1039" />
|
||||
<PackageVersion Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.11" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Http.Features" Version="2.3.0" />
|
||||
@@ -49,6 +50,8 @@
|
||||
<PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.18.0" />
|
||||
<PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.18.0" />
|
||||
<PackageVersion Include="Otp.NET" Version="1.4.1" />
|
||||
<PackageVersion Include="PdfPig" Version="0.1.16" />
|
||||
<PackageVersion Include="PDFtoImage" Version="5.0.0" />
|
||||
<PackageVersion Include="Polly" Version="8.7.0" />
|
||||
<PackageVersion Include="QRCoder" Version="1.8.0" />
|
||||
<PackageVersion Include="Scalar.AspNetCore" Version="2.16.20" />
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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": "<section><h1>Chapter One</h1><p>First paragraph.</p></section>"
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
@@ -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
|
||||
```
|
||||
@@ -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
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="836px" preserveAspectRatio="none" style="width:466px;height:836px;background:#FFFFFF;" version="1.1" viewBox="0 0 466 836" width="466px" zoomAndPan="magnify"><defs/><g><text fill="#000000" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacing" textLength="412" x="20.25" y="24.5332">System Context diagram for Lumina Media Library Manager</text><!--entity user--><g id="elem_user"><rect fill="#08427B" height="158.5625" rx="2.5" ry="2.5" style="stroke:#073B6F;stroke-width:0.5;" width="217" x="7" y="45.6094"/><image height="48" width="48" x="91.5" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABxUlEQVR42u2YPUoEQRCFJ/QIHsErmIrJJh5ADyAYm20kmwhqaCJiqIlgYGKyoKmskZEIRhpqYGBa8gkLsjAz/VPV3cN2QcHC0Gy/rurX71WzsjFuhpxNBbCQo/0LOb99lOnsVZ5e3v/y+v5Zxmd3srZzfFgsgL2TG/n6/pG+ANj67umsGACrW5NNTtk3qEh2AGze5dTb4ujyQbICCDn5xaD1sgCgBbSCSiYFwB+KYsBaSQFQdu1ICgAq1A7ej2QAYphHm1aDAIhBhFLqcgJ4+/hUBxD6HgQBQJwN+hJr0yikkPwl1mSiGE20nFJC80HbPriSrHI6hpE0PIGKKwqpROzJq1tKNuRSDSg4pufNTT1+l9Zgo1SGRC5DvZobr2OVQQNgvkPP0yo8QqTPqIS183W0FjIitL28H6+ui8q3eb+zKUCR/GZtH1vx3VcTOU/bLExMFxDXiiSVDD5BNV1GkcnNu69K7atEJ59LAUE7BQGwmDxYCL6iT///ffACABWWFm0XOplptzL9ycYmVrbTfHCrFajbQQNoo9MKoALQvgNW43Or8XuRIs5H1LVqIXi3FBnR5fZ6B1eYGcRUjnSxqXUqkTt/AThkzS9XiLScAAAAAElFTkSuQmCC" y="55.6094"/><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="45" x="73" y="120.2188">Home</text><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="4" x="118" y="120.2188"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="36" x="122" y="120.2188">User</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="113.5" y="138.2676"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="9" x="17" y="155.877">A</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="26" y="155.877"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="44" x="30" y="155.877">person</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="74" y="155.877"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="25" x="78" y="155.877">who</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="103" y="155.877"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="36" x="107" y="155.877">wants</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="143" y="155.877"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="12" x="147" y="155.877">to</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="159" y="155.877"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="51" x="163" y="155.877">manage</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="24" x="34.5" y="173.4863">and</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="58.5" y="173.4863"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="43" x="62.5" y="173.4863">stream</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="105.5" y="173.4863"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="28" x="109.5" y="173.4863">their</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="137.5" y="173.4863"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="55" x="141.5" y="173.4863">personal</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="38" x="65" y="191.0957">media</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="103" y="191.0957"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="59" x="107" y="191.0957">collection</text></g><!--entity admin--><g id="elem_admin"><rect fill="#08427B" height="140.9531" rx="2.5" ry="2.5" style="stroke:#073B6F;stroke-width:0.5;" widtLine truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:541px;height:841px;background:#FFFFFF;" width="541px" height="841px" viewBox="0 0 541 841" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="68.996" y="24.533" fill="#000" font-size="14" textLength="396.758" font-weight="700">System Context diagram for Lumina Media Library Manager</text></g><!--entity user--><g class="entity" data-qualified-name="user" id="ent0001" data-source-line="178"><rect x="7" y="45.609" width="216.116" height="162.255" fill="#08427B" style="stroke:#073B6F;stroke-width:0.5;"/><image width="52" height="52" x="89.212" y="55.609" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAA0CAYAAADFeBvrAAAGWElEQVR4Xu2YC0xTVxjHdWabBXQ63eZ0W9S5GeYwM9PNmDgNIKIwJejAFzIVx5xOMep0AkWQN/ISHxVUUEEUQRGhVMrLElEBgSsw3iBwpRRKoRQuD6Fn57iwmHMp3EJDi/Gf/NLmy73n/L/ennO+746bqG8/7k2CFhjr0AKqYM4vnjs2OV0nfCLSiTBuDhGVShCRyfmE3w0BYetzm9Dd5nt8khF7On6fKqAFRsISm6DDHtdS0wT5VZVltU1AJJGBVhkFZFQXaOvoAo0t7aCqvhlkl9SRwXFPHhodvHhtuonzInyckUALDIcpxk5zf/OOcU3ILK6uF0tBb18fGEqStg6Q9U+d7BiHK5i/xccQH3O40ALKgpI5xkkMIirqGzq7X+K+h1QFKQZuV1MEetv9jfGxhwMtoCy7vaK9i2saRb19ctwrY6G/IftiUvo8S+81+PjKQgsow4+2Z/ZkFtYIu3qUfzK4CqsawG6vGI6OkeM0fB5loAUYMn7yavbMywnZQml7J+5t2IpOe5a1aGegxQDzMYYWYALLwOHd73YE2MNdTIqbGomeCyXgyNmEEHw+ZaAFmKCzypFlH8yjpO1duKcRKzwpL36aifMCfE6m0AJM+GC1Eystt4Lq7unF/YxY/OxysGzPuRh8TqbQAkyAWzWroVlG9cmHv7MpUk4JCSzZEaOb0NQ1J1hUVw+Fm1GFiAoh2OF+621C/dACTEB/OVirUUxKHGWVWfAc/Hw0bHQTgmcQ646giBpOqTOUkrLKwFLbs6ObENq2j57nUqo8VJHQrnkxPmv0t214sE6Yv9lnfeWLZnHfCGo4XCU1jWCvb+zoH6z9nI99RLbIVPeUbqYQWXrWfqNf+vSDitP03Eoh3PFwb0orv7we/Ooepbbi9H+sXG94QzOinpfDrxpQd/vXOW767I2e6m0fEKjB2+cXy35cWFPd0dmNex1SBVVCcPwCT6C79ZRmNHj9bHWJPHL7QWH184YW0M3gaYla2sGDvKpnsHWP/2KDh+a04K+z0Nr/sP0FXlrSk7Ji2LB11opaQFNrO2hpo4BESoF6cRsoq2sCj4pqivyjMgSwBbGAR8AUfJyRQAuogllmbutW2YXwDp2JJ05HPyQu3csigu8+IZwv84ktzpHEZ+buxlqGDlr4faqAFhjr0AJMQV2rtqEjC1UNk4z+Q9vQYSJL334Cfq0itAwc3u+/H31qQ2DsPTjGePxaptACTEDJfL3Zm21uf7XxYNA9yiU0mXK/mkpZsCNK4ALfhl+vCAO7YB4qodC9sPWmNjldpxbbBN35cO0JPfxaptACgzHTzE33GIdLPi6qJYXiNqlYSslbYaWA3orKIHDh9xbXNEqi0wrI48E80oIdTq7YxyldvOs0d4lNEN/QLoT8MyCWDOflknBzIJtaOrpQPYjuRZ/NcPMQSdo7CyqFooCoDHKp7Rk+7mEoaIGB+HS9q4G1WxSRXVJXil7vDtZ69/b2ARnV/WpbrhW1gqp6SV8FKaYgnfA7EDa3vfoBBqsBX8IxJDC5Z5UNnX43BA8+MnX5Afp4B/c1ELQAzjfbfE1OhqUUlpNiRq94VSk0H/wBeiL5eTlfbfb5A65RbdwfDi3wOvO3+Jg5h/KfovNEXZLL5eiJyu9mFJXNs/RaCTeNibhPRgnNWOeqfyAw7j56Mpog9HbWKzwt9XNz9zm4V0YJGR+65MDPKmvDB1an6hpbwQb7a5dhAzgX9ztoQh+buixzvZKSIJZ24GOqXVEpBPjWym8l7nnQhJbv5XgmZJao9DWvqoTqQpMjob/Dg3gq7lthQgcC4kLKYRGpqdofcFcAj5KluG+FCfnfzAhBZ4mm6uztRwAeJ+a47wETQttiKDcnDB9EkxSTXgBgicQsoWlrTywMv5/LxQfRJAmIagDX+ZuTUG4pCfT3B79NSGP1xiWUAdfQT0zXEKxodTixj68M1iKoWxH8PLBoZyCzhBBWJ2+GPC19gY+jEero6gG23jFhn6w7qYv7VpjQ7I0ey//mJCaW1mpWtdAMa8ugmIf1C6x8TbUMHVi4b4UJIXS3+q7Y6X7LA3aMgiuJT0Fkcr7auJ6cLz93J/OFXWCci952v12TjdgzcL9DJoRABeAsMzfThdYBXvBkVhvf2wR5fmnptV/b0FEH94hDC4x1aIGxzr9XBgujsWOPcQAAAABJRU5ErkJggg=="/><text x="72.82" y="123.911" fill="#FFF" font-size="16" textLength="44.453" font-weight="700">Home</text><text x="117.273" y="123.911" fill="#FFF" font-size="16" font-weight="700"> </text><text x="121.718" y="123.911" fill="#FFF" font-size="16" textLength="35.578" font-weight="700">User</text><text x="113.113" y="141.96" fill="#FFF" font-size="14"> </text><text x="17" y="159.569" fill="#FFF" font-size="14">A</text><text x="26.338" y="159.569" fill="#FFF" font-size="14"> </text><text x="30.228" y="159.569" fill="#FFF" font-size="14" textLength="42.807">person</text><text x="73.034" y="159.569" fill="#FFF" font-size="14"> </text><text x="76.924" y="159.569" fill="#FFF" font-size="14" textLength="25.683">who</text><text x="102.606" y="159.569" fill="#FFF" font-size="14"> </text><text x="106.496" y="159.569" fill="#FFF" font-size="14" textLength="36.572">wants</text><text x="143.068" y="159.569" fill="#FFF" font-size="14"> </text><text x="146.958" y="159.569" fill="#FFF" font-size="14" textLength="11.676">to</text><text x="158.634" y="159.569" fill="#FFF" font-size="14"> </text><text x="162.523" y="159.569" fill="#FFF" font-size="14" textLength="50.593">manage</text><text x="35.683" y="177.179" fill="#FFF" font-size="14" textLength="23.358">and</text><text x="59.041" y="177.179" fill="#FFF" font-size="14"> </text><text x="62.931" y="177.179" fill="#FFF" font-size="14" textLength="42.786">stream</text><text x="105.717" y="177.179" fill="#FFF" font-size="14"> </text><text x="109.606" y="177.179" fill="#FFF" font-size="14" textLength="27.234">their</text><text x="136.841" y="177.179" fill="#FFF" font-size="14"> </text><text x="140.73" y="177.179" fill="#FFF" font-size="14" textLength="53.703">personal</text><text x="64.865" y="194.788" fill="#FFF" font-size="14" textLength="38.131">media</text><text x="102.996" y="194.788" fill="#FFF"Line truncated
|
||||
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 21 KiB |
@@ -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
|
||||
|
||||
@@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="1257px" preserveAspectRatio="none" style="width:735px;height:1257px;background:#FFFFFF;" version="1.1" viewBox="0 0 735 1257" width="735px" zoomAndPan="magnify"><defs/><g><text fill="#000000" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacing" textLength="231" x="245" y="24.5332">Container diagram for Lumina 1.1</text><!--cluster c1--><g id="cluster_c1"><rect fill="none" height="751.5" rx="2.5" ry="2.5" style="stroke:#444444;stroke-width:1.0;stroke-dasharray:7.0,7.0;" width="483" x="7" y="297.6094"/><text fill="#444444" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="83" x="207" y="316.2188">Lumina 1.1</text><text fill="#444444" font-family="sans-serif" font-size="12" font-weight="bold" lengthAdjust="spacing" textLength="51" x="223" y="332.1914">[System]</text></g><!--entity webapp--><g id="elem_webapp"><rect fill="#438DD5" height="178.4844" rx="2.5" ry="2.5" style="stroke:#3C7FC0;stroke-width:0.5;" width="255" x="201.5" y="351.6094"/><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="34" x="230" y="378.2188">Web</text><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="4" x="264" y="378.2188"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="86" x="268" y="378.2188">Application</text><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="4" x="354" y="378.2188"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="44" x="358" y="378.2188">Client</text><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="4" x="402" y="378.2188"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="22" x="406" y="378.2188">2.1</text><text fill="#FFFFFF" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="54" x="271" y="394.1914">[ASP.NET</text><text fill="#FFFFFF" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="3" x="325" y="394.1914"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="27" x="328" y="394.1914">Core</text><text fill="#FFFFFF" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="3" x="355" y="394.1914"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="29" x="358" y="394.1914">MVC]</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="327" y="411.3613"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="51" x="231" y="428.9707">Delivers</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="282" y="428.9707"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="103" x="286" y="428.9707">server-rendered</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="389" y="428.9707"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="34" x="393" y="428.9707">views</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="24" x="255" y="446.5801">with</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="279" y="446.5801"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="52" x="283" y="446.5801">dynamic</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="335" y="446.5801"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="64" x="339" y="446.5801">client-side</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="75" x="260" y="464.1895">functionality</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="335" y="464.1895"> </text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="17" x="339" y="464.1895">for</text><text fill="#FFFFFF" font-family="sans-serif" font-size="14" lengthAdjust="sLine truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:984px;height:1323px;background:#FFFFFF;" width="984px" height="1323px" viewBox="0 0 984 1323" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="377.219" y="24.533" fill="#000" font-size="14" textLength="223.262" font-weight="700">Container diagram for Lumina 1.1</text></g><!--cluster c1--><g class="cluster" data-qualified-name="c1" id="ent0003" data-source-line="1666"><rect x="7" y="300.609" width="726" height="812.5" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="328.211" y="319.219" fill="#444" font-size="16" textLength="83.578" font-weight="700">Lumina 1.1</text><text x="345.323" y="335.191" fill="#444" font-size="12" textLength="49.354" font-weight="700">[system]</text></g><!--entity webapp--><g class="entity" data-qualified-name="c1.webapp" id="ent0004" data-source-line="71"><rect x="343.5" y="354.609" width="252.996" height="198.609" fill="#438DD5" style="stroke:#3C7FC0;stroke-width:0.5;"/><text x="382.889" y="381.219" fill="#FFF" font-size="16" textLength="33.773" font-weight="700">Web</text><text x="416.662" y="381.219" fill="#FFF" font-size="16" font-weight="700"> </text><text x="421.107" y="381.219" fill="#FFF" font-size="16" textLength="87.109" font-weight="700">Application</text><text x="508.217" y="381.219" fill="#FFF" font-size="16" font-weight="700"> </text><text x="512.662" y="381.219" fill="#FFF" font-size="16" textLength="44.445" font-weight="700">Client</text><text x="458.877" y="401.344" fill="#FFF" font-size="16" textLength="22.242" font-weight="700">2.1</text><text x="411.319" y="417.316" fill="#FFF" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="465.999" y="417.316" fill="#FFF" font-size="12" font-style="italic"> </text><text x="469.333" y="417.316" fill="#FFF" font-size="12" textLength="26.01" font-style="italic">Core</text><text x="495.343" y="417.316" fill="#FFF" font-size="12" font-style="italic"> </text><text x="498.677" y="417.316" fill="#FFF" font-size="12" textLength="30" font-style="italic">MVC]</text><text x="468.053" y="434.486" fill="#FFF" font-size="14"> </text><text x="373.522" y="452.096" fill="#FFF" font-size="14" textLength="50.565">Delivers</text><text x="424.088" y="452.096" fill="#FFF" font-size="14"> </text><text x="427.978" y="452.096" fill="#FFF" font-size="14" textLength="99.6">server-rendered</text><text x="527.577" y="452.096" fill="#FFF" font-size="14"> </text><text x="531.467" y="452.096" fill="#FFF" font-size="14" textLength="35.007">views</text><text x="396.081" y="469.705" fill="#FFF" font-size="14" textLength="24.896">with</text><text x="420.978" y="469.705" fill="#FFF" font-size="14"> </text><text x="424.867" y="469.705" fill="#FFF" font-size="14" textLength="52.131">dynamic</text><text x="476.998" y="469.705" fill="#FFF" font-size="14"> </text><text x="480.888" y="469.705" fill="#FFF" font-size="14" textLength="63.027">client-side</text><text x="401.909" y="487.314" fill="#FFF" font-size="14" textLength="73.931">functionality</text><text x="475.839" y="487.314" fill="#FFF" font-size="14"> </text><text x="479.729" y="487.314" fill="#FFF" font-size="14" textLength="16.338">for</text><text x="496.067" y="487.314" fill="#FFF" font-size="14"> </text><text x="499.957" y="487.314" fill="#FFF" font-size="14" textLength="38.131">media</text><text x="385.943" y="504.924" fill="#FFF" font-size="14" textLength="81.717">management</text><text x="467.66" y="504.924" fill="#FFF" font-size="14"> </text><text x="471.55" y="504.924" fill="#FFF" font-size="14" textLength="23.358">and</text><text x="494.908" y="504.924" fill="#FFF" font-size="14"> </text><text x="498.798" y="504.924" fill="#FFF" font-size="14" textLength="55.255">playback</text><text x="423.127" y="522.533" fill="#FFF" font-size="14" textLength="52.931">[detailed</text><text x="476.058" y="522.533" fill="#FFF" font-size="14"> </text><text x="479.948" y="522.533" fill="#FFF" font-size="14" textLength="10.896">in</text><text x="490.844" y="522.533" fill="#FFF" font-size="14"> </text><text x="494.734" y="522.533" fill="#FFF" font-size="14" textLength="22.135">'3.1</text><text x="353.5" y="540.143" fill="#FFF" font-size="14" textLength="232.996">component-web-client-diagram.puml']</text></g><!--entity api--><g class="entity" data-qualified-name="c1.api" id="ent0005" data-source-line="71"><rect x="344" y="645.609" width="252.21" height="213.703" fill="#438DD5" style="stroke:#3C7FC0;stroke-width:0.5;"/><text x="416.292" y="672.219" fill="#FFF" font-size="16" textLength="26.672" font-weight="700">API</text><text x="442.964" y="672.219" fill="#FFF" font-size="16" font-weight="700"> </text><text x="447.41" y="672.219" fill="#FFF" font-size="16" tLine truncated
|
||||
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 39 KiB |
@@ -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")
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="1076px" preserveAspectRatio="none" style="width:968px;height:1076px;background:#FFFFFF;" version="1.1" viewBox="0 0 968 1076" width="968px" zoomAndPan="magnify"><defs/><g><text fill="#000000" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacing" textLength="405" x="274.5" y="24.5332">Component diagram for Lumina Web Application Client 2.1</text><!--cluster wb--><g id="cluster_wb"><rect fill="none" height="566" rx="2.5" ry="2.5" style="stroke:#444444;stroke-width:1.0;stroke-dasharray:7.0,7.0;" width="955" x="7" y="45.6094"/><text fill="#444444" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="150" x="409.5" y="64.2188">Web Application 2.1</text><text fill="#444444" font-family="sans-serif" font-size="12" font-weight="bold" lengthAdjust="spacing" textLength="63" x="453" y="80.1914">[Container]</text></g><!--entity fileSystem--><g id="elem_fileSystem"><rect fill="#85BBF0" height="125.6563" rx="2.5" ry="2.5" style="stroke:#78A8D8;stroke-width:0.5;" width="212" x="23" y="284.6094"/><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="27" x="34" y="311.2188">File</text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="4" x="61" y="311.2188"> </text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="57" x="65" y="311.2188">System</text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="4" x="122" y="311.2188"> </text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="98" x="126" y="311.2188">Management</text><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="54" x="54.5" y="327.1914">[ASP.NET</text><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="3" x="108.5" y="327.1914"> </text><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="26" x="111.5" y="327.1914">MVC</text><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="3" x="137.5" y="327.1914"> </text><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="63" x="140.5" y="327.1914">Controllers]</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="127" y="344.3613"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="51" x="33" y="361.9707">Handles</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="84" y="361.9707"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="18" x="88" y="361.9707">file</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="106" y="361.9707"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="44" x="110" y="361.9707">system</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="154" y="361.9707"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="67" x="158" y="361.9707">operations</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="56" x="41" y="379.5801">including</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="97" y="379.5801"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="42" x="101" y="379.5801">drives,</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="143" y="379.5801"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="70" x="147" y="379.5801">directories,</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="24" x="72.5" y="397.1895">and</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="96.5" y="397.1895"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="25" x="100.5" y="397.1895">files</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdLine truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:1237px;height:1166px;background:#FFFFFF;" width="1237px" height="1166px" viewBox="0 0 1237 1166" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="418.99" y="24.533" fill="#000" font-size="14" textLength="392.021" font-weight="700">Component diagram for Lumina Web Application Client 2.1</text></g><!--cluster wb--><g class="cluster" data-qualified-name="wb" id="ent0002" data-source-line="1666"><rect x="7" y="45.609" width="1216" height="654" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="538.992" y="64.219" fill="#444" font-size="16" textLength="152.016" font-weight="700">Web Application 2.1</text><text x="583.998" y="80.191" fill="#444" font-size="12" textLength="62.004" font-weight="700">[container]</text></g><!--entity fileSystem--><g class="entity" data-qualified-name="wb.fileSystem" id="ent0003" data-source-line="78"><rect x="23" y="355.109" width="219.992" height="125.656" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="37.41" y="381.719" fill="#000" font-size="16" textLength="27.563" font-weight="700">File</text><text x="64.973" y="381.719" fill="#000" font-size="16" font-weight="700"> </text><text x="69.418" y="381.719" fill="#000" font-size="16" textLength="56.922" font-weight="700">System</text><text x="126.34" y="381.719" fill="#000" font-size="16" font-weight="700"> </text><text x="130.785" y="381.719" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="58.313" y="397.691" fill="#000" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="112.992" y="397.691" fill="#000" font-size="12" font-style="italic"> </text><text x="116.326" y="397.691" fill="#000" font-size="12" textLength="26.666" font-style="italic">MVC</text><text x="142.992" y="397.691" fill="#000" font-size="12" font-style="italic"> </text><text x="146.326" y="397.691" fill="#000" font-size="12" textLength="61.354" font-style="italic">Controllers]</text><text x="131.051" y="414.861" fill="#000" font-size="14"> </text><text x="37.672" y="432.471" fill="#000" font-size="14" textLength="51.365">Handles</text><text x="89.038" y="432.471" fill="#000" font-size="14"> </text><text x="92.927" y="432.471" fill="#000" font-size="14" textLength="17.896">file</text><text x="110.824" y="432.471" fill="#000" font-size="14"> </text><text x="114.713" y="432.471" fill="#000" font-size="14" textLength="44.338">system</text><text x="159.051" y="432.471" fill="#000" font-size="14"> </text><text x="162.941" y="432.471" fill="#000" font-size="14" textLength="65.379">operations</text><text x="33" y="450.08" fill="#000" font-size="14" textLength="55.262">including</text><text x="88.262" y="450.08" fill="#000" font-size="14"> </text><text x="92.151" y="450.08" fill="#000" font-size="14" textLength="41.234">drives,</text><text x="133.386" y="450.08" fill="#000" font-size="14"> </text><text x="137.275" y="450.08" fill="#000" font-size="14" textLength="68.469">directories,</text><text x="205.744" y="450.08" fill="#000" font-size="14"> </text><text x="209.634" y="450.08" fill="#000" font-size="14" textLength="23.358">and</text><text x="90.589" y="467.689" fill="#000" font-size="14" textLength="24.896">files</text><text x="115.486" y="467.689" fill="#000" font-size="14"> </text><text x="119.375" y="467.689" fill="#000" font-size="14" textLength="56.027">browsing</text></g><!--entity library--><g class="entity" data-qualified-name="wb.library" id="ent0004" data-source-line="78"><rect x="278.5" y="337.609" width="210.661" height="160.875" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="305.588" y="364.219" fill="#000" font-size="16" textLength="54.242" font-weight="700">Library</text><text x="359.831" y="364.219" fill="#000" font-size="16" font-weight="700"> </text><text x="364.276" y="364.219" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="309.147" y="380.191" fill="#000" font-size="12" textLength="54.68" font-style="italic">[ASP.NET</text><text x="363.827" y="380.191" fill="#000" font-size="12" font-style="italic"> </text><text x="367.161" y="380.191" fill="#000" font-size="12" textLength="26.666" font-style="italic">MVC</text><text x="393.827" y="380.191" fill="#000" font-size="12" font-style="italic"> </text><text x="397.161" y="380.191" fill="#000" font-size="12" textLength="61.354" font-style="italic">Controllers]</text><text x="381.886" y="397.361" fill="#000" font-size="14"> </text><text x="293.948" y="414.971" fill="#000" font-size="14" textLength="57.593">Manages</text><text x="351.541" y="414.971" fill="#000" font-size="14"> </text><text x="355.431" y="414.971" fill="#000" font-Line truncated
|
||||
|
Before Width: | Height: | Size: 36 KiB After Width: | Height: | Size: 36 KiB |
@@ -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 [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 [detailed in '4.2 code-book-reading-diagram.puml']")
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="1411px" preserveAspectRatio="none" style="width:922px;height:1411px;background:#FFFFFF;" version="1.1" viewBox="0 0 922 1411" width="922px" zoomAndPan="magnify"><defs/><g><text fill="#000000" font-family="sans-serif" font-size="14" font-weight="bold" lengthAdjust="spacing" textLength="321" x="293.75" y="24.5332">Component diagram for Lumina API Server 2.2</text><!--cluster api--><g id="cluster_api"><rect fill="none" height="685.5" rx="2.5" ry="2.5" style="stroke:#444444;stroke-width:1.0;stroke-dasharray:7.0,7.0;" width="696" x="7" y="249.6094"/><text fill="#444444" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="106" x="302" y="268.2188">API Server 2.2</text><text fill="#444444" font-family="sans-serif" font-size="12" font-weight="bold" lengthAdjust="spacing" textLength="63" x="323.5" y="284.1914">[Container]</text></g><!--entity endpoints--><g id="elem_endpoints"><rect fill="#85BBF0" height="125.6563" rx="2.5" ry="2.5" style="stroke:#78A8D8;stroke-width:0.5;" width="207" x="147.5" y="331.1094"/><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="26" x="196.5" y="357.7188">API</text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="4" x="222.5" y="357.7188"> </text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="79" x="226.5" y="357.7188">Endpoints</text><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="84" x="209" y="373.6914">[FastEndpoints]</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="249" y="390.8613"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="55" x="157.5" y="408.4707">Provides</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="212.5" y="408.4707"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="37" x="216.5" y="408.4707">REST</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="253.5" y="408.4707"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="21" x="257.5" y="408.4707">API</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="278.5" y="408.4707"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="62" x="282.5" y="408.4707">endpoints</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="17" x="164.5" y="426.0801">for</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="181.5" y="426.0801"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="38" x="185.5" y="426.0801">media</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="223.5" y="426.0801"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="82" x="227.5" y="426.0801">management</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="309.5" y="426.0801"> </text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="24" x="313.5" y="426.0801">and</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="62" x="220" y="443.6895">streaming</text></g><!--entity mediaManagement--><g id="elem_mediaManagement"><rect fill="#85BBF0" height="145.7813" rx="2.5" ry="2.5" style="stroke:#78A8D8;stroke-width:0.5;" width="178" x="509" y="561.6094"/><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="45" x="546.5" y="588.2188">Media</text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="4" x="591.5" y="588.2188"> </text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="54" x="595.5" y="588.2188">Library</text><text fill="#000000" font-family="sans-serif" font-size="16" font-weight="bold" lengthAdjust="spacing" textLength="98" x="549" y="608.3438">Management</text><text fill="#000000" font-family="sans-serif" font-size="12" font-style="italic" lengthAdjust="spacing" textLength="47" x="548" y="624.3164">[Domain</text><texLine truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="DESCRIPTION" style="width:1398px;height:1604px;background:#FFFFFF;" width="1398px" height="1604px" viewBox="0 0 1398 1604" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="540.664" y="24.533" fill="#000" font-size="14" textLength="310.399" font-weight="700">Component diagram for Lumina API Server 2.2</text></g><!--cluster api--><g class="cluster" data-qualified-name="api" id="ent0002" data-source-line="1666"><rect x="7" y="269.609" width="957" height="862" fill="none" style="stroke:#444;stroke-width:1;stroke-dasharray:7,7;"/><text x="431.688" y="288.219" fill="#444" font-size="16" textLength="107.625" font-weight="700">API Server 2.2</text><text x="454.498" y="304.191" fill="#444" font-size="12" textLength="62.004" font-weight="700">[container]</text></g><!--entity endpoints--><g class="entity" data-qualified-name="api.endpoints" id="ent0003" data-source-line="78"><rect x="257.5" y="351.109" width="206.758" height="125.656" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="306.215" y="377.719" fill="#000" font-size="16" textLength="26.672" font-weight="700">API</text><text x="332.887" y="377.719" fill="#000" font-size="16" font-weight="700"> </text><text x="337.332" y="377.719" fill="#000" font-size="16" textLength="78.211" font-weight="700">Endpoints</text><text x="319.189" y="393.691" fill="#000" font-size="12" textLength="83.379" font-style="italic">[FastEndpoints]</text><text x="358.934" y="410.861" fill="#000" font-size="14"> </text><text x="267.5" y="428.471" fill="#000" font-size="14" textLength="54.469">Provides</text><text x="321.969" y="428.471" fill="#000" font-size="14"> </text><text x="325.858" y="428.471" fill="#000" font-size="14" textLength="37.338">REST</text><text x="363.196" y="428.471" fill="#000" font-size="14"> </text><text x="367.086" y="428.471" fill="#000" font-size="14" textLength="22.565">API</text><text x="389.651" y="428.471" fill="#000" font-size="14"> </text><text x="393.541" y="428.471" fill="#000" font-size="14" textLength="60.717">endpoints</text><text x="275.272" y="446.08" fill="#000" font-size="14" textLength="16.338">for</text><text x="291.61" y="446.08" fill="#000" font-size="14"> </text><text x="295.5" y="446.08" fill="#000" font-size="14" textLength="38.131">media</text><text x="333.631" y="446.08" fill="#000" font-size="14"> </text><text x="337.521" y="446.08" fill="#000" font-size="14" textLength="81.717">management</text><text x="419.237" y="446.08" fill="#000" font-size="14"> </text><text x="423.127" y="446.08" fill="#000" font-size="14" textLength="23.358">and</text><text x="330.145" y="463.689" fill="#000" font-size="14" textLength="61.469">streaming</text></g><!--entity mediaManagement--><g class="entity" data-qualified-name="api.mediaManagement" id="ent0004" data-source-line="78"><rect x="504.5" y="624.109" width="174.889" height="145.781" fill="#85BBF0" style="stroke:#78A8D8;stroke-width:0.5;"/><text x="539.929" y="650.719" fill="#000" font-size="16" textLength="45.344" font-weight="700">Media</text><text x="585.272" y="650.719" fill="#000" font-size="16" font-weight="700"> </text><text x="589.718" y="650.719" fill="#000" font-size="16" textLength="54.242" font-weight="700">Library</text><text x="543.046" y="670.844" fill="#000" font-size="16" textLength="97.797" font-weight="700">Management</text><text x="543.262" y="686.816" fill="#000" font-size="12" textLength="44.684" font-style="italic">[Domain</text><text x="587.945" y="686.816" fill="#000" font-size="12" font-style="italic"> </text><text x="591.279" y="686.816" fill="#000" font-size="12" textLength="49.348" font-style="italic">Services]</text><text x="590" y="703.986" fill="#000" font-size="14"> </text><text x="518.8" y="721.596" fill="#000" font-size="14" textLength="51.365">Handles</text><text x="570.165" y="721.596" fill="#000" font-size="14"> </text><text x="574.055" y="721.596" fill="#000" font-size="14" textLength="38.131">media</text><text x="612.186" y="721.596" fill="#000" font-size="14"> </text><text x="616.075" y="721.596" fill="#000" font-size="14" textLength="49.014">libraries</text><text x="514.5" y="739.205" fill="#000" font-size="14" textLength="65.379">operations</text><text x="579.879" y="739.205" fill="#000" font-size="14"> </text><text x="583.769" y="739.205" fill="#000" font-size="14" textLength="23.358">and</text><text x="607.127" y="739.205" fill="#000" font-size="14"> </text><text x="611.017" y="739.205" fill="#000" font-size="14" textLength="58.372">metadata</text><text x="551.086" y="756.814" fill="#000" font-size="14" textLength="81.717">management</text></g><!--entity userManagement--><g class="entity" data-qualified-name="api.userManagement" id="ent0005" data-source-line="78">Line truncated
|
||||
|
Before Width: | Height: | Size: 41 KiB After Width: | Height: | Size: 52 KiB |
@@ -0,0 +1,243 @@
|
||||
@startuml Book Reading and Book Reader Plugins Code
|
||||
!include <C4/C4_Component>
|
||||
|
||||
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<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>>
|
||||
}
|
||||
|
||||
interface IBookReaderRegistry {
|
||||
+ GetSupportedExtensionsByPluginId(): IReadOnlyDictionary<Guid, IReadOnlyList<string>>
|
||||
}
|
||||
|
||||
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<ReadingCacheKey, BookExtractionEntry>
|
||||
- _bookExtractionLocks: ConcurrentDictionary<ReadingCacheKey, SemaphoreSlim>
|
||||
- _pluginIdsByReaderKey: IReadOnlyDictionary<ReaderKey, Guid>
|
||||
- _enablementCache: IBookReaderEnablementCache
|
||||
+ GetManifestAsync(...): Task<Result<ReadingManifestResponse>>
|
||||
+ GetSectionAsync(...): Task<Result<ReadingSectionDto>>
|
||||
+ GetResourceAsync(...): Task<Result<ReadingResourceDataDto>>
|
||||
+ GetAvailabilityAsync(...): Task<Result<ReadingAvailabilityResponse>>
|
||||
}
|
||||
|
||||
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<Guid, IReadOnlyList<string>>
|
||||
}
|
||||
|
||||
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<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>>
|
||||
}
|
||||
|
||||
class LibraryBookReaderConfigurationRepository
|
||||
|
||||
class GetLibraryBookReadersQueryHandler {
|
||||
- _unitOfWork: IUnitOfWork
|
||||
- _bookReaderRegistry: IBookReaderRegistry
|
||||
+ HandleAsync(query: GetLibraryBookReadersQuery, token: CancellationToken): Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>
|
||||
}
|
||||
|
||||
class SetLibraryBookReaderEnabledCommandHandler {
|
||||
- _unitOfWork: IUnitOfWork
|
||||
- _enablementCache: IBookReaderEnablementCache
|
||||
+ HandleAsync(command: SetLibraryBookReaderEnabledCommand, token: CancellationToken): Task<Result<Success>>
|
||||
}
|
||||
|
||||
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<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[]>
|
||||
}
|
||||
|
||||
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
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" data-diagram-type="CLASS" style="width:2978px;height:2599px;background:#FFFFFF;" width="2978px" height="2599px" viewBox="0 0 2978 2599" zoomAndPan="magnify" preserveAspectRatio="none" contentStyleType="text/css"><?plantuml 1.2026.7?><defs/><g font-family="sans-serif" lengthAdjust="spacing"><g class="title" data-source-line="4"><text x="1274.748" y="24.533" fill="#000" font-size="14" textLength="422.413" font-weight="700">Code diagram for Book Reading 3.2.2 and Book Reader Plugins</text></g><!--class IBookReadingService--><g class="entity" data-qualified-name="IBookReadingService" id="ent0001" data-source-line="13"><rect x="1079.5" y="45.609" width="310.054" height="558.672" fill="#FFF" style="stroke:#000;stroke-width:0.5;" rx="2.5" ry="2.5"/><ellipse cx="1162.96" cy="61.609" rx="11" ry="11" fill="#B4A7E5" style="stroke:#181818;stroke-width:1;"/><path d="M1163.913,58.25 L1163.913,64.906 L1165.632,64.906 Q1166.241,64.906 1166.507,65.141 Q1166.772,65.375 1166.772,65.766 Q1166.772,66.141 1166.507,66.375 Q1166.241,66.609 1165.632,66.609 L1160.491,66.609 Q1159.882,66.609 1159.616,66.375 Q1159.351,66.141 1159.351,65.75 Q1159.351,65.375 1159.616,65.141 Q1159.882,64.906 1160.491,64.906 L1162.21,64.906 L1162.21,58.25 L1160.491,58.25 Q1159.882,58.25 1159.616,58.016 Q1159.351,57.781 1159.351,57.391 Q1159.351,57.016 1159.616,56.781 Q1159.882,56.547 1160.491,56.547 L1165.632,56.547 Q1166.241,56.547 1166.507,56.781 Q1166.772,57.016 1166.772,57.391 Q1166.772,57.781 1166.507,58.016 Q1166.241,58.25 1165.632,58.25 L1163.913,58.25 Z " fill="#000"/><text x="1183.46" y="67.338" fill="#000" font-size="14" textLength="134.634" font-style="italic">IBookReadingService</text><line x1="1080.5" y1="77.609" x2="1388.554" y2="77.609" style="stroke:#000;stroke-width:0.5;"/><line x1="1080.5" y1="85.609" x2="1388.554" y2="85.609" style="stroke:#000;stroke-width:0.5;"/><g data-visibility-modifier="PUBLIC_METHOD"><ellipse cx="1090.5" cy="152.742" rx="3" ry="3" fill="#84BE84" style="stroke:#038048;stroke-width:1;"/></g><text x="1099.5" y="104.143" fill="#000" font-size="14" textLength="164.186">GetManifestAsync(bookId:</text><text x="1099.5" y="121.752" fill="#000" font-size="14" textLength="33.462">Guid,</text><text x="1132.962" y="121.752" fill="#000" font-size="14"> </text><text x="1136.852" y="121.752" fill="#000" font-size="14" textLength="53.683">libraryId:</text><text x="1190.534" y="121.752" fill="#000" font-size="14"> </text><text x="1194.424" y="121.752" fill="#000" font-size="14" textLength="33.462">Guid,</text><text x="1227.886" y="121.752" fill="#000" font-size="14"> </text><text x="1231.775" y="121.752" fill="#000" font-size="14" textLength="31.138">path:</text><text x="1099.5" y="139.361" fill="#000" font-size="14" textLength="38.124">string,</text><text x="1137.624" y="139.361" fill="#000" font-size="14"> </text><text x="1141.514" y="139.361" fill="#000" font-size="14" textLength="73.131">libraryType:</text><text x="1214.645" y="139.361" fill="#000" font-size="14"> </text><text x="1218.534" y="139.361" fill="#000" font-size="14" textLength="77.807">LibraryType,</text><text x="1099.5" y="156.971" fill="#000" font-size="14" textLength="174.323">shouldRenderPdfAsImages:</text><text x="1099.5" y="174.58" fill="#000" font-size="14" textLength="30.358">bool,</text><text x="1129.858" y="174.58" fill="#000" font-size="14"> </text><text x="1133.748" y="174.58" fill="#000" font-size="14" textLength="38.138">token:</text><text x="1099.5" y="192.189" fill="#000" font-size="14" textLength="124.51">CancellationToken):</text><text x="1099.5" y="209.799" fill="#000" font-size="14" textLength="270.826">Task<Result<ReadingManifestResponse>></text><g data-visibility-modifier="PUBLIC_METHOD"><ellipse cx="1090.5" cy="293.617" rx="3" ry="3" fill="#84BE84" style="stroke:#038048;stroke-width:1;"/></g><text x="1099.5" y="227.408" fill="#000" font-size="14" textLength="157.972">GetSectionAsync(bookId:</text><text x="1257.472" y="227.408" fill="#000" font-size="14"> </text><text x="1261.361" y="227.408" fill="#000" font-size="14" textLength="33.462">Guid,</text><text x="1099.5" y="245.018" fill="#000" font-size="14" textLength="53.683">libraryId:</text><text x="1153.183" y="245.018" fill="#000" font-size="14"> </text><text x="1157.072" y="245.018" fill="#000" font-size="14" textLength="33.462">Guid,</text><text x="1190.534" y="245.018" fill="#000" font-size="14"> </text><text x="1194.424" y="245.018" fill="#000" font-size="14" textLength="31.138">path:</text><text x="1225.562" y="245.018" fill="#000" font-size="14"> </text><text x="1229.451" y="245.018" fill="#000" font-size="14" textLength="38.124">string,</text><text x="1099.5" y="262.627" fill="#000" font-size="14" textLength="73.131">libraryType:</text><text x="1172.631" y="262.627" fill="#000" font-size="14"> </text><text x="1176.521" y="262.627" fill="#000" font-size="14" textLength="7Line truncated
|
||||
|
After Width: | Height: | Size: 155 KiB |
@@ -0,0 +1,2 @@
|
||||
GET {{host}}/api/v1/books/{{$guid}}/reading/availability
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -0,0 +1,2 @@
|
||||
GET {{host}}/api/v1/books/{{$guid}}/reading/manifest
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -0,0 +1,2 @@
|
||||
GET {{host}}/api/v1/books/{{$guid}}/reading/resources/0f4d6e2b1c9a4f3e8d7c6b5a4f3e2d1c
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -0,0 +1,2 @@
|
||||
GET {{host}}/api/v1/books/{{$guid}}/reading/sections/chapter1
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -0,0 +1,2 @@
|
||||
GET {{host}}/api/v1/libraries/{{$guid}}/book-readers
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -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
|
||||
}
|
||||
@@ -6,5 +6,8 @@ Content-Type: application/json
|
||||
"isPaginationEnabled": true,
|
||||
"itemsPerPage": 50,
|
||||
"ignoreThePrefixForAlphaPicker": true,
|
||||
"isThemeCachingEnabled": true
|
||||
"isThemeCachingEnabled": true,
|
||||
"shouldAggregateMetadataWhenMissing": true,
|
||||
"shouldRenderPdfAsImages": false,
|
||||
"shouldPreserveBookStyles": true
|
||||
}
|
||||
@@ -8,16 +8,16 @@ using System;
|
||||
namespace Lumina.Plugins.Calibre.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class CalibreServices
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
|
||||
/// <returns>The service collection, for chaining.</returns>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
internal static IServiceCollection AddCalibreBookMetadataProvider(this IServiceCollection services, Guid pluginId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
@@ -29,7 +29,7 @@ internal static class CalibreServices
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin that provides the artwork.</param>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||
<Private>false</Private>
|
||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Utility class for registering the services of the EPUB format reader into the Dependency Injection container.
|
||||
/// </summary>
|
||||
internal static class EpubServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the services of the EPUB format reader into the Dependency Injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin that provides the book reader.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
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<IBookReader, EpubReader>(pluginId);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Epub.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the parsed OPF package document of an EPUB.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
internal sealed class OpfDocumentDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the title of the book.
|
||||
/// </summary>
|
||||
public string? Title { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the author of the book, if applicable.
|
||||
/// </summary>
|
||||
public string? Author { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the manifest items of the EPUB.
|
||||
/// </summary>
|
||||
public List<OpfManifestItemDto> Items { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the manifest items of the EPUB, keyed by their Id.
|
||||
/// </summary>
|
||||
public Dictionary<string, OpfManifestItemDto> ItemsById { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Ids of the manifest items that are reading sections, in reading order.
|
||||
/// </summary>
|
||||
public List<string> SpineIds { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the manifest item of the navigation document, if applicable.
|
||||
/// </summary>
|
||||
public string? NavItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the manifest item of the NCX document, if applicable.
|
||||
/// </summary>
|
||||
public string? NcxItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the manifest item of the cover image, if applicable.
|
||||
/// </summary>
|
||||
public string? CoverItemId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Epub.Common.Models.DTO.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a manifest item of the OPF package document of an EPUB.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
internal sealed class OpfManifestItemDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the manifest item.
|
||||
/// </summary>
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the href of the manifest item.
|
||||
/// </summary>
|
||||
public string Href { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the media type of the manifest item.
|
||||
/// </summary>
|
||||
public string MediaType { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Parses an EPUB into a normalized reading document, extracting its sections and resources into a working directory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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:
|
||||
/// <list type="bullet">
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// <c>META-INF/container.xml</c> is the entry point. Its rootfile element points to the OPF package file.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// The OPF package file describes the whole book, with three relevant sections:
|
||||
/// <list type="bullet">
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// <c>metadata</c>: the title, the author, the language, etc. (in the Dublin Core namespace, prefixed <c>dc</c>).
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// <c>manifest</c>: the list of every file that is part of the publication (chapters, images, fonts, CSS, the
|
||||
/// navigation document). Each item has an <c>id</c> (unique within the manifest), an <c>href</c> (the path of the
|
||||
/// file relative to the OPF file), and a <c>media-type</c>.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// <c>spine</c>: the READING ORDER of the book, named after the spine of a physical book. It is a list of
|
||||
/// <c>itemref</c> elements, each referencing a manifest item by its <c>id</c>. 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.
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// </list>
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>
|
||||
/// The table of contents comes from the navigation document (EPUB 3) or the NCX document (EPUB 2).
|
||||
/// </description>
|
||||
/// </item>
|
||||
/// </list>
|
||||
/// 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 <see cref="ReadingDocumentDto"/> model. The host serves those files.
|
||||
/// </remarks>
|
||||
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
|
||||
// "<!DOCTYPE html PUBLIC ...>") 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<string, char> 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);
|
||||
|
||||
/// <summary>
|
||||
/// Parses the EPUB stored at <paramref name="epubPath"/>, extracting its sections and resources into <paramref name="workingDirectory"/>, and returns its normalized reading document.
|
||||
/// </summary>
|
||||
/// <param name="epubPath">The file system path of the EPUB.</param>
|
||||
/// <param name="workingDirectory">The directory into which the sections and resources of the EPUB are extracted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The normalized reading document of the EPUB.</returns>
|
||||
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, <img src="images/cover.png">, 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<string, string> targetByResolvedPath = [];
|
||||
HashSet<string> 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<string, ReadingResourceInfoDto> resources = ExtractResources(zipArchive, workingDirectory, opfDirectory, opfDocument, spineItemIds, ref totalExpandedBytes, cancellationToken);
|
||||
|
||||
(List<ReadingTocEntryDto> tableOfContents, Dictionary<string, string> titlesByItemId) = BuildTableOfContents(zipArchive, opfDocument, opfDirectory, targetByResolvedPath, ref totalExpandedBytes, cancellationToken);
|
||||
|
||||
List<ReadingSpineItemDto> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the archive bounds, so that a decompression bomb cannot exhaust the memory of the host.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive to validate.</param>
|
||||
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.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the path of the OPF file from the container document of the EPUB.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The path of the OPF file, or <see langword="null"/> when it could not be read.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads and parses the OPF document of the EPUB.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive.</param>
|
||||
/// <param name="opfPath">The path of the OPF file.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The parsed OPF document.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the resources of the EPUB into the resources directory of the working directory.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive.</param>
|
||||
/// <param name="workingDirectory">The directory into which the resources are extracted.</param>
|
||||
/// <param name="opfDirectory">The directory of the OPF file, used to resolve the manifest hrefs.</param>
|
||||
/// <param name="opfDocument">The parsed OPF document.</param>
|
||||
/// <param name="spineItemIds">The Ids of the manifest items that are reading sections, which are not extracted as resources.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The extracted resources, keyed by their resource key.</returns>
|
||||
private static Dictionary<string, ReadingResourceInfoDto> ExtractResources(ZipArchive zipArchive, string workingDirectory, string opfDirectory, OpfDocumentDto opfDocument, HashSet<string> spineItemIds, ref long totalExpandedBytes, CancellationToken cancellationToken)
|
||||
{
|
||||
Dictionary<string, ReadingResourceInfoDto> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the reading sections of the EPUB into the sections directory of the working directory.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive.</param>
|
||||
/// <param name="workingDirectory">The directory into which the sections are extracted.</param>
|
||||
/// <param name="opfDirectory">The directory of the OPF file, used to resolve the manifest hrefs.</param>
|
||||
/// <param name="opfDocument">The parsed OPF document.</param>
|
||||
/// <param name="targetByResolvedPath">The target of every resolvable manifest item, keyed by its resolved archive path.</param>
|
||||
/// <param name="titlesByItemId">The titles of the reading sections, keyed by the Id of their manifest item.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The extracted reading sections of the EPUB.</returns>
|
||||
private static List<ReadingSpineItemDto> ExtractSections(ZipArchive zipArchive, string workingDirectory, string opfDirectory, OpfDocumentDto opfDocument, Dictionary<string, string> targetByResolvedPath, Dictionary<string, string> titlesByItemId, ref long totalExpandedBytes, CancellationToken cancellationToken)
|
||||
{
|
||||
List<ReadingSpineItemDto> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="data">The raw content of the reading section.</param>
|
||||
/// <param name="sectionEntryPath">The archive path of the reading section, used to resolve its references.</param>
|
||||
/// <param name="targetByResolvedPath">The target of every resolvable manifest item, keyed by its resolved archive path.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The rewritten content of the reading section.</returns>
|
||||
private static string RewriteSectionContent(byte[] data, string sectionEntryPath, Dictionary<string, string> 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 "<!DOCTYPE html PUBLIC ...>") 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether <paramref name="attribute"/> is an attribute carrying a resource reference.
|
||||
/// </summary>
|
||||
/// <param name="attribute">The attribute to check.</param>
|
||||
/// <returns><see langword="true"/> when the attribute carries a resource reference, <see langword="false"/> otherwise.</returns>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the table of contents of the EPUB, from its navigation document or its NCX document.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive.</param>
|
||||
/// <param name="opfDocument">The parsed OPF document.</param>
|
||||
/// <param name="opfDirectory">The directory of the OPF file, used to resolve the manifest hrefs.</param>
|
||||
/// <param name="targetByResolvedPath">The target of every resolvable manifest item, keyed by its resolved archive path.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The table of contents entries, and the titles of the reading sections keyed by the Id of their manifest item.</returns>
|
||||
private static (List<ReadingTocEntryDto> entries, Dictionary<string, string> titlesByItemId) BuildTableOfContents(ZipArchive zipArchive, OpfDocumentDto opfDocument, string opfDirectory, Dictionary<string, string> targetByResolvedPath, ref long totalExpandedBytes, CancellationToken cancellationToken)
|
||||
{
|
||||
Dictionary<string, string> titlesByItemId = [];
|
||||
List<ReadingTocEntryDto> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the table of contents from the navigation document of an EPUB 3.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive.</param>
|
||||
/// <param name="navPath">The archive path of the navigation document.</param>
|
||||
/// <param name="targetByResolvedPath">The target of every resolvable manifest item, keyed by its resolved archive path.</param>
|
||||
/// <param name="titlesByItemId">The titles of the reading sections, keyed by the Id of their manifest item.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The table of contents entries.</returns>
|
||||
private static List<ReadingTocEntryDto> ReadNavigationDocument(ZipArchive zipArchive, string navPath, Dictionary<string, string> targetByResolvedPath, Dictionary<string, string> 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))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a list item of the navigation document into a table of contents entry.
|
||||
/// </summary>
|
||||
/// <param name="listItem">The list item element to parse.</param>
|
||||
/// <param name="navPath">The archive path of the navigation document.</param>
|
||||
/// <param name="targetByResolvedPath">The target of every resolvable manifest item, keyed by its resolved archive path.</param>
|
||||
/// <param name="titlesByItemId">The titles of the reading sections, keyed by the Id of their manifest item.</param>
|
||||
/// <returns>The parsed table of contents entry.</returns>
|
||||
private static ReadingTocEntryDto ParseNavListItem(XElement listItem, string navPath, Dictionary<string, string> targetByResolvedPath, Dictionary<string, string> 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<ReadingTocEntryDto> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the table of contents from the NCX document of an EPUB 2.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive.</param>
|
||||
/// <param name="ncxPath">The archive path of the NCX document.</param>
|
||||
/// <param name="targetByResolvedPath">The target of every resolvable manifest item, keyed by its resolved archive path.</param>
|
||||
/// <param name="titlesByItemId">The titles of the reading sections, keyed by the Id of their manifest item.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The table of contents entries.</returns>
|
||||
private static List<ReadingTocEntryDto> ReadNcxDocument(ZipArchive zipArchive, string ncxPath, Dictionary<string, string> targetByResolvedPath, Dictionary<string, string> 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))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a navigation point of the NCX document into a table of contents entry.
|
||||
/// </summary>
|
||||
/// <param name="navigationPoint">The navigation point element to parse.</param>
|
||||
/// <param name="ncxPath">The archive path of the NCX document.</param>
|
||||
/// <param name="targetByResolvedPath">The target of every resolvable manifest item, keyed by its resolved archive path.</param>
|
||||
/// <param name="titlesByItemId">The titles of the reading sections, keyed by the Id of their manifest item.</param>
|
||||
/// <returns>The parsed table of contents entry.</returns>
|
||||
private static ReadingTocEntryDto ParseNcxNavPoint(XElement navigationPoint, string ncxPath, Dictionary<string, string> targetByResolvedPath, Dictionary<string, string> 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<ReadingTocEntryDto> children = [.. navigationPoint.Elements(s_ncxNamespace + "navPoint")
|
||||
.Select(child => ParseNcxNavPoint(child, ncxPath, targetByResolvedPath, titlesByItemId))];
|
||||
|
||||
return new ReadingTocEntryDto(label, locationRef, children);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the location reference of a table of contents reference, and records the title of its target section.
|
||||
/// </summary>
|
||||
/// <param name="href">The href of the table of contents reference.</param>
|
||||
/// <param name="documentPath">The archive path of the document containing the reference.</param>
|
||||
/// <param name="targetByResolvedPath">The target of every resolvable manifest item, keyed by its resolved archive path.</param>
|
||||
/// <param name="titlesByItemId">The titles of the reading sections, keyed by the Id of their manifest item.</param>
|
||||
/// <param name="label">The label of the table of contents entry.</param>
|
||||
/// <returns>The location reference of the target section, or an empty string when it could not be resolved.</returns>
|
||||
private static string GetLocationRef(string? href, string documentPath, Dictionary<string, string> targetByResolvedPath, Dictionary<string, string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided media type identifies a resource that is extracted from the EPUB.
|
||||
/// </summary>
|
||||
/// <param name="mediaType">The media type to check.</param>
|
||||
/// <returns><see langword="true"/> when the media type identifies an extractable resource, <see langword="false"/> otherwise.</returns>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a manifest href against the <paramref name="baseDirectory"/>, rejecting paths that escape the archive.
|
||||
/// </summary>
|
||||
/// <param name="baseDirectory">The directory against which the href is resolved.</param>
|
||||
/// <param name="href">The href to resolve.</param>
|
||||
/// <returns>The normalized archive path, or <see langword="null"/> when it escapes the archive.</returns>
|
||||
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<string> 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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the directory part of an archive path.
|
||||
/// </summary>
|
||||
/// <param name="path">The archive path.</param>
|
||||
/// <returns>The directory of the archive path.</returns>
|
||||
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];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the opaque resource key of a manifest href.
|
||||
/// </summary>
|
||||
/// <param name="href">The manifest href.</param>
|
||||
/// <returns>The resource key of the href.</returns>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="data">The raw content of the document.</param>
|
||||
/// <returns>The content, normalized for XML parsing.</returns>
|
||||
private static string NormalizeDocumentText(byte[] data)
|
||||
{
|
||||
string text = DecodeDocumentText(data);
|
||||
if (text.IndexOf("<!DOCTYPE", StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
text = RemoveDocumentTypeDeclaration(text);
|
||||
if (text.IndexOf('&') >= 0)
|
||||
text = ResolveNamedCharacterReferences(text);
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the raw content of an XML or XHTML document of the archive into text, honoring its byte order mark.
|
||||
/// </summary>
|
||||
/// <param name="data">The raw content of the document.</param>
|
||||
/// <returns>The decoded text of the document, without its byte order mark.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="text">The text of the document.</param>
|
||||
/// <returns>The text of the document without its document type declarations.</returns>
|
||||
private static string RemoveDocumentTypeDeclaration(string text)
|
||||
{
|
||||
// The declaration spans from "<!DOCTYPE" to its closing ">", 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("<!DOCTYPE", StringComparison.OrdinalIgnoreCase);
|
||||
while (declarationStart >= 0)
|
||||
{
|
||||
char activeQuote = '\0';
|
||||
int internalSubsetDepth = 0;
|
||||
int declarationEnd = -1;
|
||||
for (int index = declarationStart + "<!DOCTYPE".Length; index < text.Length; index++)
|
||||
{
|
||||
char character = text[index];
|
||||
if (activeQuote != '\0')
|
||||
{
|
||||
if (character == activeQuote)
|
||||
activeQuote = '\0';
|
||||
continue;
|
||||
}
|
||||
if (character is '"' or '\'')
|
||||
{
|
||||
activeQuote = character;
|
||||
continue;
|
||||
}
|
||||
if (character == '[')
|
||||
{
|
||||
internalSubsetDepth++;
|
||||
continue;
|
||||
}
|
||||
if (character == ']')
|
||||
{
|
||||
internalSubsetDepth--;
|
||||
continue;
|
||||
}
|
||||
if (character == '>' && internalSubsetDepth <= 0)
|
||||
{
|
||||
declarationEnd = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (declarationEnd < 0)
|
||||
break;
|
||||
text = text.Remove(declarationStart, declarationEnd - declarationStart + 1);
|
||||
declarationStart = text.IndexOf("<!DOCTYPE", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="text">The text of the document.</param>
|
||||
/// <returns>The text of the document with its mapped HTML named character references resolved.</returns>
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads an XML entry of the archive with hardened XML settings.
|
||||
/// </summary>
|
||||
/// <param name="zipArchive">The EPUB archive.</param>
|
||||
/// <param name="entryPath">The archive path of the entry.</param>
|
||||
/// <param name="maxBytes">The maximum allowed size of the entry.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The parsed XML document.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the content of an archive entry, bounded by <paramref name="maxBytes"/>.
|
||||
/// </summary>
|
||||
/// <param name="entry">The archive entry to read.</param>
|
||||
/// <param name="maxBytes">The maximum allowed size of the entry.</param>
|
||||
/// <param name="totalExpandedBytes">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The content of the archive entry.</returns>
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Plugin that decodes EPUB books into a normalized reading document.
|
||||
/// </summary>
|
||||
public sealed class EpubPlugin : IPlugin, IPluginServiceRegistrator
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public static readonly Guid s_pluginId = new("b1e8a8e0-4f3a-4d2c-9a1e-6d3f8a9b2c3d");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public Guid Id => s_pluginId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the plugin.
|
||||
/// </summary>
|
||||
public string Name => "EPUB Reader";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the author of the plugin.
|
||||
/// </summary>
|
||||
public string Author => "Lumina";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the version of the plugin.
|
||||
/// </summary>
|
||||
public Version Version => new(1, 0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the description of the plugin.
|
||||
/// </summary>
|
||||
public string Description => "Allows reading of EPUB format books.";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings schema of the plugin.
|
||||
/// </summary>
|
||||
/// <returns>The settings descriptors of the plugin.</returns>
|
||||
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services required by the plugin.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
public void RegisterServices(IServiceCollection services)
|
||||
{
|
||||
services.AddEpubReader(pluginId: Id);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Book reader for the EPUB format.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See <see cref="EpubDocumentParser"/> for what an EPUB is, and how it is decoded; this class only declares the supported format and delegates the decoding to the parser.
|
||||
/// </remarks>
|
||||
internal sealed class EpubReader : IBookReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the file extensions supported by the reader.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> SupportedExtensions => [".epub"];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library types the reader supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.EBook, LibraryType.Book];
|
||||
|
||||
/// <summary>
|
||||
/// Opens the EPUB stored at <paramref name="path"/>, extracting its sections and resources into
|
||||
/// <paramref name="workingDirectory"/>, and returns its normalized reading document.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the EPUB.</param>
|
||||
/// <param name="workingDirectory">The directory into which the sections and resources of the EPUB are extracted.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The normalized reading document of the EPUB.</returns>
|
||||
public Task<ReadingDocumentDto> OpenAsync(string path, string workingDirectory, bool shouldRenderPdfAsImages, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(EpubDocumentParser.Parse(path, workingDirectory, cancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Produces the resource identified by <paramref name="resourceKey"/> of the EPUB stored at <paramref name="path"/>.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the EPUB.</param>
|
||||
/// <param name="workingDirectory">The directory into which the sections and resources of the EPUB are extracted.</param>
|
||||
/// <param name="resourceKey">The opaque resource key of the resource to produce.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The binary data of the extracted resource.</returns>
|
||||
public Task<byte[]> GetResourceAsync(string path, string workingDirectory, string resourceKey, CancellationToken cancellationToken)
|
||||
{
|
||||
byte[] data = File.ReadAllBytes(Path.Combine(workingDirectory, "resources", resourceKey));
|
||||
return Task.FromResult(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
|
||||
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.Epub.UnitTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.Epub.Fixtures")]
|
||||
@@ -13,17 +13,17 @@ using System;
|
||||
namespace Lumina.Plugins.OpenLibrary.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class OpenLibraryServices
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
|
||||
/// <param name="settingsCallback">Action used to configure the <see cref="OpenLibrarySettingsDto"/>.</param>
|
||||
/// <returns>The service collection, for chaining.</returns>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
internal static IServiceCollection AddOpenLibraryBookMetadataProvider(this IServiceCollection services, Guid pluginId, Action<OpenLibrarySettingsDto>? settingsCallback = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it loaded from somewhere else-->
|
||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Utility class for registering the services of the PDF format reader into the Dependency Injection container.
|
||||
/// </summary>
|
||||
internal static class PdfServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the services of the PDF format reader into the Dependency Injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <param name="pluginId">The unique identifier of the plugin that provides the book reader.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
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<IBookReader, PdfReader>(pluginId);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Parses a PDF into a normalized reading document, extracting the text of its pages into a working directory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Parses the PDF stored at <paramref name="pdfPath"/>, extracting its pages into <paramref name="workingDirectory"/>, and returns its normalized reading document.
|
||||
/// </summary>
|
||||
/// <param name="pdfPath">The file system path of the PDF.</param>
|
||||
/// <param name="workingDirectory">The directory into which the pages of the PDF are extracted.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The normalized reading document of the PDF.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the PDF stored at <paramref name="pdfPath"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="pdfPath">The file system path of the PDF.</param>
|
||||
/// <param name="sectionsDirectory">The directory into which the section files of the PDF are written.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The normalized reading document of the PDF, without a text layer.</returns>
|
||||
private static ReadingDocumentDto ParseAsImages(string pdfPath, string sectionsDirectory, CancellationToken cancellationToken)
|
||||
{
|
||||
List<ReadingSpineItemDto> spine = [];
|
||||
Dictionary<string, ReadingResourceInfoDto> resources = [];
|
||||
List<ReadingTocEntryDto> 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 = $"<section><img data-lumina-resource=\"{resourceKey}\" alt=\"{WebUtility.HtmlEncode(locationRef)}\" /></section>";
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders the page image identified by <paramref name="resourceKey"/> of the PDF stored at <paramref name="pdfPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="pdfPath">The file system path of the PDF.</param>
|
||||
/// <param name="resourceKey">The resource key of the page image to render, of the form <c>page:{n}</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The PNG bytes of the rendered page.</returns>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the PDF stored at <paramref name="pdfPath"/> by extracting the text layer of its pages, and returns its normalized reading document.
|
||||
/// </summary>
|
||||
/// <param name="pdfPath">The file system path of the PDF.</param>
|
||||
/// <param name="sectionsDirectory">The directory into which the section files of the PDF are written.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The normalized reading document of the PDF, with a text layer when the PDF has one.</returns>
|
||||
private static ReadingDocumentDto ParseAsText(string pdfPath, string sectionsDirectory, CancellationToken cancellationToken)
|
||||
{
|
||||
List<ReadingSpineItemDto> spine = [];
|
||||
bool hasTextContent = false;
|
||||
List<ReadingTocEntryDto> 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("<p>"))
|
||||
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<string, ReadingResourceInfoDto>(), hasTextContent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the HTML content of a PDF page, wrapping its extracted text into paragraphs.
|
||||
/// </summary>
|
||||
/// <param name="page">The PDF page whose content is built.</param>
|
||||
/// <returns>The HTML content of the PDF page.</returns>
|
||||
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("<section>");
|
||||
string text = page.Text ?? string.Empty;
|
||||
foreach (string line in text.Replace("\r\n", "\n").Split('\n'))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
continue;
|
||||
stringBuilder.Append("<p>").Append(WebUtility.HtmlEncode(line)).Append("</p>");
|
||||
}
|
||||
stringBuilder.Append("</section>");
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the table of contents of the PDF from the bookmarks of the already open document.
|
||||
/// </summary>
|
||||
/// <param name="pdfDocument">The open PDF document whose bookmarks are read.</param>
|
||||
/// <returns>The table of contents of the PDF, or an empty list when the PDF has no usable bookmarks.</returns>
|
||||
private static List<ReadingTocEntryDto> 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 [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a bookmark of the PDF into a table of contents entry.
|
||||
/// </summary>
|
||||
/// <param name="bookmark">The bookmark to convert.</param>
|
||||
/// <returns>The converted table of contents entry.</returns>
|
||||
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<ReadingTocEntryDto> children = [.. bookmark.Children.Select(ToTocEntry)];
|
||||
return new ReadingTocEntryDto(bookmark.Title ?? string.Empty, locationRef, children);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Plugin that decodes PDF books into a normalized reading document.
|
||||
/// </summary>
|
||||
public sealed class PdfPlugin : IPlugin, IPluginServiceRegistrator
|
||||
{
|
||||
/// <summary>
|
||||
/// The unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public static readonly Guid s_pluginId = new("c2f9b8f0-5a4b-4e3d-8b2f-7e4a9c1d3e5f");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the unique identifier of the plugin.
|
||||
/// </summary>
|
||||
public Guid Id => s_pluginId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display name of the plugin.
|
||||
/// </summary>
|
||||
public string Name => "PDF Reader";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the author of the plugin.
|
||||
/// </summary>
|
||||
public string Author => "Lumina";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the version of the plugin.
|
||||
/// </summary>
|
||||
public Version Version => new(1, 0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the description of the plugin.
|
||||
/// </summary>
|
||||
public string Description => "Allows reading of PDF format books.";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings schema of the plugin.
|
||||
/// </summary>
|
||||
/// <returns>The settings descriptors of the plugin.</returns>
|
||||
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services required by the plugin.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to register the services into.</param>
|
||||
public void RegisterServices(IServiceCollection services)
|
||||
{
|
||||
services.AddPdfReader(pluginId: Id);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Book reader for the PDF format.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See <see cref="PdfDocumentParser"/> for how a PDF is decoded; this class only declares the supported format and delegates the decoding to the parser.
|
||||
/// </remarks>
|
||||
internal sealed class PdfReader : IBookReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the file extensions supported by the reader.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> SupportedExtensions => [".pdf"];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library types the reader supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.EBook, LibraryType.Book];
|
||||
|
||||
/// <summary>
|
||||
/// Opens the PDF stored at <paramref name="path"/>, extracting its pages into <paramref name="workingDirectory"/>,
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the PDF.</param>
|
||||
/// <param name="workingDirectory">The directory into which the pages of the PDF are extracted.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">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.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The normalized reading document of the PDF.</returns>
|
||||
public Task<ReadingDocumentDto> OpenAsync(string path, string workingDirectory, bool shouldRenderPdfAsImages, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(PdfDocumentParser.Parse(path, workingDirectory, shouldRenderPdfAsImages, cancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Produces the resource identified by <paramref name="resourceKey"/> of the PDF stored at <paramref name="path"/>,
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="path">The file system path of the PDF.</param>
|
||||
/// <param name="workingDirectory">The directory into which the pages of the PDF are extracted.</param>
|
||||
/// <param name="resourceKey">The opaque resource key of the resource to produce, of the form <c>page:{n}</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The binary data of the rendered page image.</returns>
|
||||
/// <remarks>
|
||||
/// The PDFtoImage and SkiaSharp APIs used by <see cref="PdfDocumentParser.RenderResource"/> 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.
|
||||
/// </remarks>
|
||||
[SupportedOSPlatform("windows")]
|
||||
[SupportedOSPlatform("linux")]
|
||||
[SupportedOSPlatform("macos")]
|
||||
public Task<byte[]> GetResourceAsync(string path, string workingDirectory, string resourceKey, CancellationToken cancellationToken)
|
||||
{
|
||||
byte[] data = PdfDocumentParser.RenderResource(path, resourceKey, cancellationToken);
|
||||
return Task.FromResult(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
|
||||
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
<!-- The native libraries of the dependencies ship for every platform and architecture under a runtimes\<rid>\native
|
||||
subdirectory of the plugin output; only the ones of the runtime the host runs on are deployed, flattened into the plugins
|
||||
directory, so that a wrong-architecture native library (for example the x86 pdfium next to a 64-bit host) is never copied. -->
|
||||
<ItemGroup>
|
||||
<_CurrentRidNatives Include="$(OutDir)runtimes\$(NETCoreSdkRuntimeIdentifier)\native\*" />
|
||||
</ItemGroup>
|
||||
<!-- The native libraries are what make the PDF reader work at runtime, so a build that produced none is a build that would deploy
|
||||
a silently broken plugin; failing here makes a missing RuntimeIdentifier visible at build time instead of as a runtime
|
||||
DllNotFoundException. -->
|
||||
<Error Condition="'@(_CurrentRidNatives)' == ''" Text="No native libraries were produced under '$(OutDir)runtimes\$(NETCoreSdkRuntimeIdentifier)\native'. Build the Lumina.Plugins.Pdf project with an explicit runtime identifier (for example: dotnet build -r win-x64) so the PDF reader ships its native rendering libraries." />
|
||||
<Copy SourceFiles="@(_CurrentRidNatives)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="PdfPig" />
|
||||
<PackageReference Include="PDFtoImage" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.UnitTests")]
|
||||
[assembly: InternalsVisibleTo("Lumina.Plugins.Pdf.Fixtures")]
|
||||
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for the configuration of a book reader of a media library.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
|
||||
public class LibraryBookReaderConfigurationEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the configuration.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the media library the configuration belongs to.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the plugin providing the book reader.
|
||||
/// </summary>
|
||||
public required Guid PluginId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the book reader is enabled for the media library.
|
||||
/// </summary>
|
||||
public required bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -47,6 +47,19 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity
|
||||
/// </summary>
|
||||
public bool ShouldAggregateMetadataWhenMissing { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether PDF books are rendered as page images for the user, or not. Rendering PDFs as images preserves the
|
||||
/// original layout, but the pages are not selectable or searchable, unlike their text layer.
|
||||
/// </summary>
|
||||
public bool ShouldRenderPdfAsImages { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the styles of the book content are preserved when it is rendered for the user, or not. Preserving them
|
||||
/// keeps the original look of a book (its fonts, colors, and alignment), but the styles of a book can load resources from
|
||||
/// external servers, which those servers could observe; stripping them removes that possibility, at the cost of the look of the book.
|
||||
/// </summary>
|
||||
public bool ShouldPreserveBookStyles { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for the book reader configurations of media libraries.
|
||||
/// </summary>
|
||||
public interface ILibraryBookReaderConfigurationRepository : IRepository<LibraryBookReaderConfigurationEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets all the book reader configurations of the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configurations are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryBookReaderConfigurationEntity"/>, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the book reader configuration of the media library identified by <paramref name="libraryId"/> for the plugin identified by <paramref name="pluginId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configuration is retrieved.</param>
|
||||
/// <param name="pluginId">The Id of the plugin whose book reader configuration is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="LibraryBookReaderConfigurationEntity"/>, or an error.</returns>
|
||||
Task<Result<LibraryBookReaderConfigurationEntity?>> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Inserts the provided <paramref name="configuration"/> into the storage medium, or updates it when it already exists.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The book reader configuration to insert or update.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Updated>> UpsertAsync(LibraryBookReaderConfigurationEntity configuration, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes all the book reader configurations of the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configurations are deleted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Deleted>> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes all the book reader configurations referencing the plugin identified by <paramref name="pluginId"/>.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The Id of the plugin whose book reader configurations are deleted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Deleted>> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the book reader configurations of the media library identified by <paramref name="libraryId"/> that reference
|
||||
/// one of the plugins identified by <paramref name="pluginIds"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configurations are deleted.</param>
|
||||
/// <param name="pluginIds">The Ids of the plugins whose configurations of the media library are deleted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Deleted>> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable<Guid> pluginIds, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -82,6 +82,11 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the library book reader configuration repository.
|
||||
/// </summary>
|
||||
ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the plugin repository.
|
||||
/// </summary>
|
||||
|
||||
@@ -12,13 +12,13 @@ using System.Reflection;
|
||||
namespace Lumina.Application.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains all services of the Application layer.
|
||||
/// Utility class for registering the services of the Application layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class ApplicationLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the services of the Application layer into the dependency injection container.
|
||||
/// Registers the services of the Application layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
@@ -52,7 +52,7 @@ public static class ApplicationLayerServices
|
||||
continue;
|
||||
}
|
||||
|
||||
// wrap query, command, and domain event handlers in their telemetry decorator, so that every invocation emits traces, metrics, and structured logs
|
||||
// Wrap query, command, and domain event handlers in their telemetry decorator, so that every invocation emits traces, metrics, and structured logs.
|
||||
services.AddScoped(registration.Contract, serviceProvider =>
|
||||
{
|
||||
object handler = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, registration.Implementation);
|
||||
|
||||
@@ -58,4 +58,38 @@ public interface IMediaLibraryProviderConfigurationStore
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Deleted>> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a disabled book reader configuration for every loaded plugin that supports the provided library type and has no configuration yet, for the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configurations are ensured.</param>
|
||||
/// <param name="libraryType">The type of the media library, used to determine the plugins whose book readers apply.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Success>> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the book reader configurations of the media library identified by <paramref name="libraryId"/> so that they match the plugins supporting the provided library type.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configurations are reconciled.</param>
|
||||
/// <param name="libraryType">The type of the media library, used to determine the plugins whose book readers apply.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Success>> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes all the book reader configurations of the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader configurations are deleted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Deleted>> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes all the book reader configurations referencing the plugin identified by <paramref name="pluginId"/>.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The Id of the plugin whose book reader configurations are deleted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Deleted>> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Cache of whether the book reader of a plugin is enabled for a media library. The enablement is read from the database on its first
|
||||
/// use and cached afterwards, because it is consulted on every section and resource request, and it only changes when the user toggles
|
||||
/// a reader or a plugin is uninstalled; those operations invalidate the affected entries.
|
||||
/// </summary>
|
||||
public interface IBookReaderEnablementCache
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the cached enablement of the book reader of the plugin identified by <paramref name="pluginId"/> for the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader enablement is retrieved.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the book reader.</param>
|
||||
/// <returns>The cached enablement, or <see langword="null"/> when it is not cached yet.</returns>
|
||||
bool? Get(Guid libraryId, Guid pluginId);
|
||||
|
||||
/// <summary>
|
||||
/// Caches the enablement of the book reader of the plugin identified by <paramref name="pluginId"/> for the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader enablement is cached.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the book reader.</param>
|
||||
/// <param name="isEnabled">Whether the book reader is enabled for the media library.</param>
|
||||
void Set(Guid libraryId, Guid pluginId, bool isEnabled);
|
||||
|
||||
/// <summary>
|
||||
/// Removes the cached enablement of the book reader of the plugin identified by <paramref name="pluginId"/> for the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader enablement is invalidated.</param>
|
||||
/// <param name="pluginId">The Id of the plugin providing the book reader.</param>
|
||||
void Invalidate(Guid libraryId, Guid pluginId);
|
||||
|
||||
/// <summary>
|
||||
/// Removes every cached enablement of the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose book reader enablements are invalidated.</param>
|
||||
void InvalidateLibrary(Guid libraryId);
|
||||
|
||||
/// <summary>
|
||||
/// Removes every cached enablement of the plugin identified by <paramref name="pluginId"/>.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The Id of the plugin whose book reader enablements are invalidated.</param>
|
||||
void InvalidatePlugin(Guid pluginId);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Registry of the book readers provided by the loaded plugins.
|
||||
/// </summary>
|
||||
public interface IBookReaderRegistry
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the file extensions supported by the book readers of each loaded plugin, keyed by the Id of the plugin.
|
||||
/// </summary>
|
||||
/// <returns>The supported extensions of the book readers, keyed by the Id of the plugin providing them.</returns>
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> GetSupportedExtensionsByPluginId();
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
#endregion
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
#endregion
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetReadingAvailabilityRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetReadingAvailabilityRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetReadingAvailabilityQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetReadingAvailabilityQuery ToQuery(this GetReadingAvailabilityRequest request)
|
||||
{
|
||||
return new GetReadingAvailabilityQuery(
|
||||
request.BookId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetReadingManifestRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetReadingManifestRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetReadingManifestQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetReadingManifestQuery ToQuery(this GetReadingManifestRequest request)
|
||||
{
|
||||
return new GetReadingManifestQuery(
|
||||
request.BookId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetReadingResourceRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetReadingResourceRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetReadingResourceQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetReadingResourceQuery ToQuery(this GetReadingResourceRequest request)
|
||||
{
|
||||
return new GetReadingResourceQuery(
|
||||
request.BookId,
|
||||
request.ResourceKey
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetReadingSectionRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetReadingSectionRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetReadingSectionQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetReadingSectionQuery ToQuery(this GetReadingSectionRequest request)
|
||||
{
|
||||
return new GetReadingSectionQuery(
|
||||
request.BookId,
|
||||
request.LocationRef
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ReadingDocumentDto"/>.
|
||||
/// </summary>
|
||||
public static class ReadingDocumentDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="document"/> to <see cref="ReadingManifestResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="document">The reading document to be converted.</param>
|
||||
/// <returns>The converted reading manifest response.</returns>
|
||||
public static ReadingManifestResponse ToResponse(this ReadingDocumentDto document)
|
||||
{
|
||||
return new ReadingManifestResponse(
|
||||
document.Title,
|
||||
document.Author,
|
||||
document.CoverResourceKey,
|
||||
[.. document.TableOfContents.Select(entry => entry.ToResponse())],
|
||||
[.. document.Spine.Select(spineItem => new ReadingSpineItemResponse(spineItem.LocationRef, spineItem.Title))],
|
||||
[.. document.Resources.Keys],
|
||||
document.HasTextContent
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ReadingTocEntryDto"/>.
|
||||
/// </summary>
|
||||
public static class ReadingTocEntryDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="entry"/> to <see cref="ReadingTocEntryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="entry">The table of contents entry to be converted.</param>
|
||||
/// <returns>The converted table of contents entry response.</returns>
|
||||
public static ReadingTocEntryResponse ToResponse(this ReadingTocEntryDto entry)
|
||||
{
|
||||
return new ReadingTocEntryResponse(
|
||||
entry.Label,
|
||||
entry.LocationRef,
|
||||
[.. entry.Children.Select(child => child.ToResponse())]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetLibraryBookReadersRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetLibraryBookReadersRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetLibraryBookReadersQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetLibraryBookReadersQuery ToQuery(this GetLibraryBookReadersRequest request)
|
||||
{
|
||||
return new GetLibraryBookReadersQuery(
|
||||
request.LibraryId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="LibraryBookReaderConfigurationEntity"/>.
|
||||
/// </summary>
|
||||
public static class LibraryBookReaderConfigurationEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="configuration"/> to <see cref="LibraryBookReaderResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="configuration">The repository entity to be converted.</param>
|
||||
/// <param name="readerName">The display name of the book reader.</param>
|
||||
/// <param name="supportedExtensions">The file extensions supported by the book reader.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static LibraryBookReaderResponse ToResponse(this LibraryBookReaderConfigurationEntity configuration, string readerName, IReadOnlyList<string> supportedExtensions)
|
||||
{
|
||||
return new LibraryBookReaderResponse(
|
||||
configuration.PluginId,
|
||||
readerName,
|
||||
supportedExtensions,
|
||||
configuration.IsEnabled
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="SetLibraryBookReaderEnabledRequest"/>.
|
||||
/// </summary>
|
||||
public static class SetLibraryBookReaderEnabledRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="SetLibraryBookReaderEnabledCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static SetLibraryBookReaderEnabledCommand ToCommand(this SetLibraryBookReaderEnabledRequest request)
|
||||
{
|
||||
return new SetLibraryBookReaderEnabledCommand(
|
||||
request.LibraryId,
|
||||
request.PluginId,
|
||||
request.IsEnabled
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,9 @@ public static class UpdateUserSettingsRequestMapping
|
||||
request.ItemsPerPage,
|
||||
request.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
request.IsThemeCachingEnabled,
|
||||
request.ShouldAggregateMetadataWhenMissing
|
||||
request.ShouldAggregateMetadataWhenMissing,
|
||||
request.ShouldRenderPdfAsImages,
|
||||
request.ShouldPreserveBookStyles
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,9 @@ public static class UserSettingsEntityMapping
|
||||
repositoryEntity.ItemsPerPage,
|
||||
repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
repositoryEntity.IsThemeCachingEnabled,
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing,
|
||||
repositoryEntity.ShouldRenderPdfAsImages,
|
||||
repositoryEntity.ShouldPreserveBookStyles
|
||||
);
|
||||
}
|
||||
|
||||
@@ -47,7 +49,9 @@ public static class UserSettingsEntityMapping
|
||||
repositoryEntity.ItemsPerPage,
|
||||
repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
repositoryEntity.IsThemeCachingEnabled,
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing
|
||||
repositoryEntity.ShouldAggregateMetadataWhenMissing,
|
||||
repositoryEntity.ShouldRenderPdfAsImages,
|
||||
repositoryEntity.ShouldPreserveBookStyles
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,9 @@ public static class UserSettingsMapping
|
||||
ItemsPerPage = domainEntity.ItemsPerPage,
|
||||
ShouldIgnoreThePrefixForAlphaPicker = domainEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled,
|
||||
ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing
|
||||
ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing,
|
||||
ShouldRenderPdfAsImages = domainEntity.ShouldRenderPdfAsImages,
|
||||
ShouldPreserveBookStyles = domainEntity.ShouldPreserveBookStyles
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,7 +45,9 @@ public static class UserSettingsMapping
|
||||
domainEntity.ItemsPerPage,
|
||||
domainEntity.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
domainEntity.IsThemeCachingEnabled,
|
||||
domainEntity.ShouldAggregateMetadataWhenMissing
|
||||
domainEntity.ShouldAggregateMetadataWhenMissing,
|
||||
domainEntity.ShouldRenderPdfAsImages,
|
||||
domainEntity.ShouldPreserveBookStyles
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
|
||||
@@ -6,7 +6,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for storing the artwork of a book into the internal media directory and serving its relative path.
|
||||
@@ -9,7 +9,7 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Command for adding a book.
|
||||
@@ -23,7 +23,7 @@ using System.Threading.Tasks;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add a book.
|
||||
@@ -6,7 +6,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddBookCommand"/>.
|
||||
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting all the books of a media library.
|
||||
@@ -19,7 +19,7 @@ using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get all books.
|
||||
@@ -5,7 +5,7 @@ using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetBooksQuery"/>.
|
||||
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the lightweight details of all the books of a media library.
|
||||
@@ -19,7 +19,7 @@ using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the lightweight details of all books.
|
||||
@@ -6,7 +6,7 @@ using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetBooksLiteQuery"/>.
|
||||
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Query for checking the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading availability is checked.</param>
|
||||
public record GetReadingAvailabilityQuery(
|
||||
Guid BookId
|
||||
) : IQuery;
|
||||
@@ -0,0 +1,95 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to check the reading availability of a book.
|
||||
/// </summary>
|
||||
public class GetReadingAvailabilityQueryHandler : IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingAvailabilityQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingAvailabilityQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingAvailabilityQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to check the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the reading availability of the book, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingAvailabilityResponse>> HandleAsync(GetReadingAvailabilityQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
return await _bookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingAvailabilityQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingAvailabilityQueryValidator : AbstractValidator<GetReadingAvailabilityQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingAvailabilityQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading manifest is retrieved.</param>
|
||||
public record GetReadingManifestQuery(
|
||||
Guid BookId
|
||||
) : IQuery;
|
||||
@@ -0,0 +1,103 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the reading manifest of a book.
|
||||
/// </summary>
|
||||
public class GetReadingManifestQueryHandler : IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingManifestQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingManifestQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingManifestQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingManifestQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the reading manifest of the book, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingManifestResponse>> HandleAsync(GetReadingManifestQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preference decides whether a PDF is rendered as page images or has its text layer extracted; a
|
||||
// missing settings row falls back to the default, which is to extract the text layer.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
|
||||
return await _bookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingManifestQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingManifestQueryValidator : AbstractValidator<GetReadingManifestQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingManifestQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingManifestQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting a resource of a book, for reading.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose resource is retrieved.</param>
|
||||
/// <param name="ResourceKey">The opaque resource key of the resource.</param>
|
||||
public record GetReadingResourceQuery(
|
||||
Guid BookId,
|
||||
string ResourceKey
|
||||
) : IQuery;
|
||||
@@ -0,0 +1,102 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a resource of a book, for reading.
|
||||
/// </summary>
|
||||
public class GetReadingResourceQueryHandler : IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingResourceQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingResourceQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingResourceQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingResourceQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a resource of a book, for reading.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the resource of the book, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingResourceDataDto>> HandleAsync(GetReadingResourceQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preference decides whether a PDF is rendered as page images or has its text layer extracted; a
|
||||
// missing settings row falls back to the default, which is to extract the text layer.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
|
||||
return await _bookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingResourceQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingResourceQueryValidator : AbstractValidator<GetReadingResourceQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingResourceQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingResourceQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.ResourceKey)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.ResourceKeyCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the content of a reading section of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading section is retrieved.</param>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
|
||||
public record GetReadingSectionQuery(
|
||||
Guid BookId,
|
||||
string LocationRef
|
||||
) : IQuery;
|
||||
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the content of a reading section of a book.
|
||||
/// </summary>
|
||||
public class GetReadingSectionQueryHandler : IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingSectionQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingSectionQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingSectionQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingSectionQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the content of a reading section of a book.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the content of the reading section, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingSectionDto>> HandleAsync(GetReadingSectionQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preferences decide how the book is rendered: whether a PDF is rendered as page images or has its text
|
||||
// layer extracted, and whether the styles of the section content are preserved; a missing settings row falls back to the
|
||||
// defaults, which are to extract the text layer and to preserve the styles.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
bool shouldPreserveStyles = getSettingsResult.Value is null || getSettingsResult.Value.ShouldPreserveBookStyles;
|
||||
|
||||
return await _bookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages, shouldPreserveStyles, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingSectionQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingSectionQueryValidator : AbstractValidator<GetReadingSectionQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingSectionQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingSectionQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.LocationRef)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.LocationRefCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for reading books, using the book reader plugins configured for their media library.
|
||||
/// </summary>
|
||||
public interface IBookReadingService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the reading manifest of the book stored at <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <param name="libraryType">The type of the media library the book belongs to.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the reading manifest of the book, or an error.</returns>
|
||||
Task<Result<ReadingManifestResponse>> GetManifestAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, bool shouldRenderPdfAsImages, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the content of the reading section identified by <paramref name="locationRef"/> of the book stored at <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <param name="libraryType">The type of the media library the book belongs to.</param>
|
||||
/// <param name="locationRef">The opaque location reference of the reading section.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
|
||||
/// <param name="shouldPreserveStyles">Whether the styles of the section content are preserved when it is sanitized, or stripped.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the content of the reading section, or an error.</returns>
|
||||
Task<Result<ReadingSectionDto>> GetSectionAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string locationRef, bool shouldRenderPdfAsImages, bool shouldPreserveStyles, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource identified by <paramref name="resourceKey"/> of the book stored at <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <param name="libraryType">The type of the media library the book belongs to.</param>
|
||||
/// <param name="resourceKey">The opaque resource key of the resource.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the resource, or an error.</returns>
|
||||
Task<Result<ReadingResourceDataDto>> GetResourceAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string resourceKey, bool shouldRenderPdfAsImages, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the book stored at <paramref name="path"/> can be opened for reading, resolving the book reader configured
|
||||
/// for its media library and verifying that the reader is enabled, without extracting the book.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <param name="libraryType">The type of the media library the book belongs to.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the reading availability of the book, or an error.</returns>
|
||||
Task<Result<ReadingAvailabilityResponse>> GetAvailabilityAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Command for enabling or disabling a book reader for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library whose book reader is enabled or disabled.</param>
|
||||
/// <param name="PluginId">The unique identifier of the plugin providing the book reader.</param>
|
||||
/// <param name="IsEnabled">Whether the book reader should be enabled for the media library.</param>
|
||||
public record SetLibraryBookReaderEnabledCommand(
|
||||
Guid LibraryId,
|
||||
Guid PluginId,
|
||||
bool IsEnabled
|
||||
) : ICommand;
|
||||
@@ -0,0 +1,106 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Reading;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to enable or disable a book reader for a media library.
|
||||
/// </summary>
|
||||
public class SetLibraryBookReaderEnabledCommandHandler : ICommandHandler<SetLibraryBookReaderEnabledCommand, Result<Success>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReaderEnablementCache _enablementCache;
|
||||
private readonly IValidator<SetLibraryBookReaderEnabledCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="enablementCache">Injected cache of whether the book reader of a plugin is enabled for a media library.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public SetLibraryBookReaderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderEnablementCache enablementCache, IUnitOfWork unitOfWork, IValidator<SetLibraryBookReaderEnabledCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_enablementCache = enablementCache;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to enable or disable a book reader for a media library.
|
||||
/// </summary>
|
||||
/// <param name="command">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<Success>> HandleAsync(SetLibraryBookReaderEnabledCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Admins can configure the book readers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryBookReaderConfigurationEntity?> getConfigurationResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationResult.IsFailure)
|
||||
return getConfigurationResult.Errors;
|
||||
|
||||
LibraryBookReaderConfigurationEntity configuration;
|
||||
if (getConfigurationResult.Value is not null)
|
||||
{
|
||||
configuration = getConfigurationResult.Value;
|
||||
configuration.IsEnabled = command.IsEnabled;
|
||||
}
|
||||
else
|
||||
{
|
||||
configuration = new LibraryBookReaderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = command.LibraryId,
|
||||
PluginId = command.PluginId,
|
||||
IsEnabled = command.IsEnabled,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
}
|
||||
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
return upsertResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// The reading service caches the enablement of a reader, because it consults it on every request; the cache is invalidated here,
|
||||
// so that disabling a reader cuts access to its books immediately, without waiting for the cache to expire.
|
||||
_enablementCache.Invalidate(command.LibraryId, command.PluginId);
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="SetLibraryBookReaderEnabledCommand"/>.
|
||||
/// </summary>
|
||||
public class SetLibraryBookReaderEnabledCommandValidator : AbstractValidator<SetLibraryBookReaderEnabledCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public SetLibraryBookReaderEnabledCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PluginId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.PluginIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the book readers configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library whose book readers are retrieved.</param>
|
||||
public record GetLibraryBookReadersQuery(
|
||||
Guid LibraryId
|
||||
) : IQuery;
|
||||
@@ -0,0 +1,97 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Reading;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the book readers configured for a media library.
|
||||
/// </summary>
|
||||
public class GetLibraryBookReadersQueryHandler : IQueryHandler<GetLibraryBookReadersQuery, Result<IReadOnlyList<LibraryBookReaderResponse>>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReaderRegistry _bookReaderRegistry;
|
||||
private readonly IValidator<GetLibraryBookReadersQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryBookReadersQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReaderRegistry">Injected registry of the book readers provided by the loaded plugins.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetLibraryBookReadersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderRegistry bookReaderRegistry, IUnitOfWork unitOfWork, IValidator<GetLibraryBookReadersQuery> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReaderRegistry = bookReaderRegistry;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the book readers configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="query">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryBookReaderResponse"/>, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<IReadOnlyList<LibraryBookReaderResponse>>> HandleAsync(GetLibraryBookReadersQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Admins can read the book readers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
|
||||
// Build a plugin name lookup from the detected plugins.
|
||||
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getPluginsResult.IsFailure)
|
||||
return getPluginsResult.Errors;
|
||||
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
|
||||
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> supportedExtensionsByPluginId = _bookReaderRegistry.GetSupportedExtensionsByPluginId();
|
||||
|
||||
return getConfigurationsResult.Value
|
||||
.OrderBy(configuration => configuration.IsEnabled ? 0 : 1)
|
||||
.ThenBy(configuration => pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty, StringComparer.OrdinalIgnoreCase)
|
||||
.Select(configuration => configuration.ToResponse(
|
||||
pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty,
|
||||
supportedExtensionsByPluginId.GetValueOrDefault(configuration.PluginId) ?? []))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetLibraryBookReadersQuery"/>.
|
||||
/// </summary>
|
||||
public class GetLibraryBookReadersQueryValidator : AbstractValidator<GetLibraryBookReadersQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryBookReadersQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryBookReadersQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,14 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="ShouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="ShouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
|
||||
/// <param name="ShouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
|
||||
public record UpdateUserSettingsCommand(
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled,
|
||||
bool ShouldAggregateMetadataWhenMissing
|
||||
bool ShouldAggregateMetadataWhenMissing,
|
||||
bool ShouldRenderPdfAsImages,
|
||||
bool ShouldPreserveBookStyles
|
||||
) : ICommand;
|
||||
@@ -53,27 +53,29 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get the existing settings of the current user, if any
|
||||
// Get the existing settings of the current user, if any.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
|
||||
if (getSettingsResult.Value is null)
|
||||
{
|
||||
// create the settings of the current user, since they are not stored yet
|
||||
// Create the settings of the current user, since they are not stored yet.
|
||||
Result<UserSettings> createSettingsResult = UserSettings.Create(
|
||||
UserId.Create(userId),
|
||||
command.IsPaginationEnabled,
|
||||
command.ItemsPerPage,
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled,
|
||||
command.ShouldAggregateMetadataWhenMissing);
|
||||
command.ShouldAggregateMetadataWhenMissing,
|
||||
command.ShouldRenderPdfAsImages,
|
||||
command.ShouldPreserveBookStyles);
|
||||
if (createSettingsResult.IsFailure)
|
||||
return createSettingsResult.Errors;
|
||||
|
||||
@@ -83,7 +85,7 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
}
|
||||
else
|
||||
{
|
||||
// update the stored settings of the current user
|
||||
// Update the stored settings of the current user.
|
||||
Result<UserSettings> toDomainEntityResult = getSettingsResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
@@ -93,7 +95,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
command.ItemsPerPage,
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled,
|
||||
command.ShouldAggregateMetadataWhenMissing);
|
||||
command.ShouldAggregateMetadataWhenMissing,
|
||||
command.ShouldRenderPdfAsImages,
|
||||
command.ShouldPreserveBookStyles);
|
||||
if (updateSettingsResult.IsFailure)
|
||||
return updateSettingsResult.Errors;
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the normalized document model of a book, produced by a reader plugin.
|
||||
/// </summary>
|
||||
/// <param name="Title">The title of the book.</param>
|
||||
/// <param name="Author">The author of the book, if known.</param>
|
||||
/// <param name="CoverResourceKey">The resource key of the cover image of the book, if applicable.</param>
|
||||
/// <param name="TableOfContents">The hierarchical table of contents of the book.</param>
|
||||
/// <param name="Spine">The ordered spine of the reading sections of the book.</param>
|
||||
/// <param name="Resources">The resources of the book, keyed by their resource key.</param>
|
||||
/// <param name="HasTextContent">Whether the book has extractable text content. A scanned book, whose pages are only images, has no text content.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
public sealed record ReadingDocumentDto(
|
||||
string Title,
|
||||
string? Author,
|
||||
string? CoverResourceKey,
|
||||
IReadOnlyList<ReadingTocEntryDto> TableOfContents,
|
||||
IReadOnlyList<ReadingSpineItemDto> Spine,
|
||||
IReadOnlyDictionary<string, ReadingResourceInfoDto> Resources,
|
||||
bool HasTextContent
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the binary data of a reading resource.
|
||||
/// </summary>
|
||||
/// <param name="Data">The binary data of the resource.</param>
|
||||
/// <param name="MimeType">The MIME type of the resource.</param>
|
||||
[DebuggerDisplay("MimeType: {MimeType}")]
|
||||
public sealed record ReadingResourceDataDto(
|
||||
byte[] Data,
|
||||
string MimeType
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the file information of a resource of a reading document.
|
||||
/// </summary>
|
||||
/// <param name="RelativeFilePath">The path of the resource file, relative to the extraction directory of the book.</param>
|
||||
/// <param name="MimeType">The MIME type of the resource.</param>
|
||||
[DebuggerDisplay("RelativeFilePath: {RelativeFilePath}")]
|
||||
public sealed record ReadingResourceInfoDto(
|
||||
string RelativeFilePath,
|
||||
string MimeType
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the content of a reading section.
|
||||
/// </summary>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
|
||||
/// <param name="Title">The title of the reading section, if known.</param>
|
||||
/// <param name="ContentHtml">The sanitized HTML content of the reading section, ready to be rendered by the client.</param>
|
||||
[DebuggerDisplay("LocationRef: {LocationRef}")]
|
||||
public sealed record ReadingSectionDto(
|
||||
string LocationRef,
|
||||
string? Title,
|
||||
string ContentHtml
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for an item of the spine of a reading document.
|
||||
/// </summary>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
|
||||
/// <param name="Title">The title of the reading section, if known.</param>
|
||||
/// <param name="RelativeSectionFilePath">The path of the section content file, relative to the extraction directory of the book.</param>
|
||||
[DebuggerDisplay("LocationRef: {LocationRef}")]
|
||||
public sealed record ReadingSpineItemDto(
|
||||
string LocationRef,
|
||||
string? Title,
|
||||
string RelativeSectionFilePath
|
||||
);
|
||||