diff --git a/docs/manual/managing-libraries/index.md b/docs/manual/managing-libraries/index.md index 916494e7..bffb60d9 100644 --- a/docs/manual/managing-libraries/index.md +++ b/docs/manual/managing-libraries/index.md @@ -21,7 +21,7 @@ A media library is how you tell Lumina where a part of your collection lives and ## What a library is -A library is a name, a media type, and one or more content locations. It belongs to the user who created it, but administrators, and anyone holding the permission to create libraries, can manage any library, including the ones they did not create. +A library is a name, a media type, and one or more content locations. It belongs to the user who created it. Only its owner can change or delete it, and only while they hold the permission to create libraries, so withholding that permission keeps a user from changing even the libraries they own. Administrators can change and delete any library. The libraries page only shows the edit and delete actions to users who hold that permission and to administrators. The library keeps a catalogue of the items it indexed, together with their metadata and artwork. Your actual files stay exactly where they are and are only read, except for the one opt-in setting that writes metadata back (see below). @@ -29,7 +29,7 @@ The library keeps a catalogue of the items it indexed, together with their metad Lumina can scan two kinds of libraries today: -- **Book** libraries, for books and e-books. During discovery Lumina recognizes these file extensions: `.pdf`, `.epub`, `.mobi`, `.azw`, `.azw3`, `.cbz`, `.cbr`, `.djvu`, `.fb2`, `.lit`, `.prc`, `.txt`, `.doc`, `.docx` and `.rtf`. Of those, the ones a user can open and read in the browser depend on the enabled reader plugins. The EPUB and PDF readers are bundled with Lumina, but readers are disabled by default, so a freshly created book library cannot open any book until you enable one for it. The rest are still indexed and listed in the catalogue, but cannot be opened for reading until a reader for their format is enabled. +- **Book** libraries, for books and e-books. During discovery Lumina recognizes these file extensions: `.pdf`, `.epub`, `.mobi`, `.azw`, `.azw3`, `.cbz`, `.cbr`, `.djvu`, `.fb2`, `.lit`, `.prc`, `.txt`, `.doc`, `.docx` and `.rtf`. Of those, the ones a user can open and read in the browser depend on the enabled reader plugins. The EPUB and PDF readers are bundled with Lumina, but readers are disabled by default, so a book library cannot open any book until you enable a reader for it. The rest are still indexed and listed in the catalogue, but cannot be opened for reading until a reader for their format is enabled. - **Music** libraries, for artists, albums and tracks. During discovery Lumina recognizes these file extensions: `.mp3`, `.flac`, `.m4a`, `.aac`, `.ogg`, `.opus`, `.wav`, `.wma`, `.aiff`, `.aif`, `.ape`, `.wv`, `.dsf`, `.dff` and `.mka`. The other types in Lumina's model, such as movies, TV shows, comics, manga, photos, podcasts and audiobooks, are designed but not implemented yet. There is no scanner for them, so they cannot be scanned. @@ -55,9 +55,12 @@ Open the Libraries management page, choose to add a library, and fill in the for | Track consumption progress | the type default | Whether the latest playback or reading position of the library's items is remembered, so a user can resume where they left off. | | Completion threshold | the type default | The percentage of an item that must be consumed for a stopped session to be recorded as completed. Empty means completion is recorded only when it is reported explicitly. | | Path template | the type's ideal structure | Tells Lumina how your folders are arranged on disk. Unless you customize it, it holds the default template of the library type, which is exactly the structure Lumina expects. Optional, and explained in full below. | +| Metadata providers, artwork providers, book readers | all off | The plugins that fill in the library's metadata and artwork, and, for a book library, open its books. The form lists the ones that support the selected type and refreshes the lists when you change the type. Each is switched on or off, and providers are put in order. A section is hidden when no installed plugin offers that kind of provider for the type. See [Plugins](../plugins/index.md). | A library that is disabled or locked is never scanned, so those two settings double as a pause switch, and `Locked` also freezes edits. +Everything on the form, provider choices included, is saved in one step when you save the library. + ## Path templates To make sense of your files, Lumina needs to know how they are arranged. A path template describes that arrangement as an ordered list of parts, and Lumina uses it to pull values such as an author and a title, or an artist, a release and a track number, straight out of the folder and file names. @@ -132,7 +135,7 @@ A disabled or locked library is refused a scan, and a library whose type has no Editing a library reopens the same form, and changes take effect on the next scan. Beyond the fields above, two things change the wider picture: -- Changing the **type** of an existing library also reconciles the metadata, artwork and reader provider settings of that library, so they match the plugins that support the new type. +- Changing the **type** of an existing library updates the provider lists on the form right away, so you can adjust them before saving: providers the library already has keep their on or off setting and their order when the new type still supports them, providers that only the new type supports are added switched off, and providers the new type does not support are removed, together with their settings, when you save. - Changing the **content locations** takes effect on the next scan. Items found under a location you removed are dropped from the catalogue, along with the metadata and artwork Lumina had stored for them, and items under a location you added are picked up. ## Progress tracking and completion thresholds diff --git a/docs/manual/plugins/index.md b/docs/manual/plugins/index.md index f355216a..fcc34a76 100644 --- a/docs/manual/plugins/index.md +++ b/docs/manual/plugins/index.md @@ -65,7 +65,7 @@ There is no uninstall button. To remove a plugin, delete its assembly (and any f ## Enabling, ranking and configuring -Plugins themselves are installed once, but they are turned on per library. Open a library to edit it and you will find a section for metadata providers and one for artwork providers. A book library has one more, for its book readers: +Plugins themselves are installed once, but they are turned on per library. The form has a section for metadata providers and one for artwork providers, and a book library has one more, for its book readers. Your choices are saved together with the rest of the library: - **Metadata providers.** Each is switched on or off, and ordered. The providers are tried in that order, the first one that produces a result is used, and, when you enable the `Aggregate metadata when missing` setting, the fields it left empty are filled from the providers that come after it. - **Artwork providers.** The same idea for images: switched on or off, and ordered, so you decide which source wins when more than one has something. diff --git a/docs/technical/api/library/management/Api.Libraries.md b/docs/technical/api/library/management/Api.Libraries.md index 29803fc9..b3e75170 100644 --- a/docs/technical/api/library/management/Api.Libraries.md +++ b/docs/technical/api/library/management/Api.Libraries.md @@ -68,10 +68,25 @@ POST api/v1/libraries "isContentOnSsd": false, "shouldTrackConsumptionProgress": true, "completionThresholdPercentage": 100, - "pathTemplateParts": [] + "pathTemplateParts": [], + "metadataProviders": [ + { + "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", + "isEnabled": true + } + ], + "artworkProviders": null, + "bookReaders": [ + { + "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", + "isEnabled": true + } + ] } ``` +The `metadataProviders`, `artworkProviders` and `bookReaders` lists configure the providers and readers of the library in the same request: each entry names a plugin returned by the matching `GET api/v1/libraries/{metadata-providers|artwork-providers|book-readers}/{libraryType}` request, and whether it is enabled, and the order of the provider entries is the order in which the providers are tried. A supported plugin left out of a list is added disabled, after the listed ones. The `isEnabled` of an entry can be omitted, in which case the stored state is kept and a provider without one starts disabled, so a list can reorder providers without changing their state. A list that is `null` or absent adds every supported plugin disabled, in alphabetical order. A plugin that does not support the library type fails the request with `PluginNotSupportedForLibraryType`. + #### Add Library Response ```js @@ -231,7 +246,6 @@ PUT api/v1/libraries/{id} ```json { "id": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "userId": "2cff0c0f-3a67-4e30-b94f-f4e948a3b64f", "title": "Books", "libraryType": "Book", "contentLocations": [ @@ -246,10 +260,22 @@ PUT api/v1/libraries/{id} "isContentOnSsd": false, "shouldTrackConsumptionProgress": true, "completionThresholdPercentage": 100, - "pathTemplateParts": [] + "pathTemplateParts": [], + "metadataProviders": [ + { + "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", + "isEnabled": true + } + ], + "artworkProviders": null, + "bookReaders": null } ``` +Updating a library requires being its owner and holding the `CanCreateLibraries` permission, or being an admin, who can update any library; any other user is answered with `403 NotAuthorized` before the cover image is read. The owner of the library is the user who created it: an update never changes it, so the request carries no owner. + +The `metadataProviders`, `artworkProviders` and `bookReaders` lists work as for [Add Library](#add-library). A list that is sent also removes the stored configurations of the plugins that do not support the library type, even when the list does not name them, and keeps the stored state of the supported plugins it leaves out, ordering them after the listed ones. A list that is `null` or absent keeps the stored configurations when the library type is unchanged, and when the type changes, removes the configurations of the plugins that do not support the new type and adds the newly supported plugins disabled. + #### Update Library Response ```js @@ -288,6 +314,8 @@ PUT api/v1/libraries/{id} DELETE api/v1/libraries/{id} ``` +Deleting a library requires being its owner and holding the `CanCreateLibraries` permission, or being an admin, who can delete any library; any other user is answered with `403 NotAuthorized`. + #### Delete Library Response ```js diff --git a/docs/technical/api/plugins/Api.Plugins.md b/docs/technical/api/plugins/Api.Plugins.md index 194c76c3..a9cdeca4 100644 --- a/docs/technical/api/plugins/Api.Plugins.md +++ b/docs/technical/api/plugins/Api.Plugins.md @@ -17,27 +17,21 @@ - [Get Library Metadata Providers](#get-library-metadata-providers) - [Get Library Metadata Providers Request](#get-library-metadata-providers-request) - [Get Library Metadata Providers Response](#get-library-metadata-providers-response) - - [Set Library Metadata Provider Enabled](#set-library-metadata-provider-enabled) - - [Set Library Metadata Provider Enabled Request](#set-library-metadata-provider-enabled-request) - - [Set Library Metadata Provider Enabled Response](#set-library-metadata-provider-enabled-response) - - [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 Artwork Providers](#get-library-artwork-providers) - [Get Library Artwork Providers Request](#get-library-artwork-providers-request) - [Get Library Artwork Providers Response](#get-library-artwork-providers-response) - - [Set Library Artwork Provider Enabled](#set-library-artwork-provider-enabled) - - [Set Library Artwork Provider Enabled Request](#set-library-artwork-provider-enabled-request) - - [Set Library Artwork Provider Enabled Response](#set-library-artwork-provider-enabled-response) - - [Reorder Library Artwork Providers](#reorder-library-artwork-providers) - - [Reorder Library Artwork Providers Request](#reorder-library-artwork-providers-request) - - [Reorder Library Artwork Providers Response](#reorder-library-artwork-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) + - [Get Library Type Metadata Providers](#get-library-type-metadata-providers) + - [Get Library Type Metadata Providers Request](#get-library-type-metadata-providers-request) + - [Get Library Type Metadata Providers Response](#get-library-type-metadata-providers-response) + - [Get Library Type Artwork Providers](#get-library-type-artwork-providers) + - [Get Library Type Artwork Providers Request](#get-library-type-artwork-providers-request) + - [Get Library Type Artwork Providers Response](#get-library-type-artwork-providers-response) + - [Get Library Type Book Readers](#get-library-type-book-readers) + - [Get Library Type Book Readers Request](#get-library-type-book-readers-request) + - [Get Library Type Book Readers Response](#get-library-type-book-readers-response) - [Music Plugins](#music-plugins) ## Plugins @@ -200,7 +194,7 @@ PUT api/v1/plugins/{pluginId}/settings GET api/v1/libraries/{libraryId}/metadata-providers ``` -Returns the metadata providers available for the media library, one entry per plugin that provides metadata, along with whether the provider is enabled for the media library and its rank, which determines the order in which the providers are tried. +Returns the metadata providers available for the media library, one entry per plugin that provides metadata, along with whether the provider is enabled for the media library and its rank, which determines the order in which the providers are tried. The enabled state and the rank are changed by sending the `metadataProviders` of the [Add Library](../library/management/Api.Libraries.md#add-library) or [Update Library](../library/management/Api.Libraries.md#update-library) request. #### Get Library Metadata Providers Response @@ -219,52 +213,6 @@ Returns the metadata providers available for the media library, one entry per pl ] ``` -### Set Library Metadata Provider Enabled - -#### Set Library Metadata Provider Enabled Request - -```js -PUT api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled -``` - -```json -{ - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", - "isEnabled": true -} -``` - -#### Set Library Metadata Provider Enabled Response - -```js -200 Ok -``` - -### Reorder Library Metadata Providers - -#### Reorder Library Metadata Providers Request - -```js -PUT api/v1/libraries/{libraryId}/metadata-providers/reorder -``` - -```json -{ - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "pluginIds": [ - "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", - "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d" - ] -} -``` - -#### Reorder Library Metadata Providers Response - -```js -200 Ok -``` - ### Get Library Artwork Providers #### Get Library Artwork Providers Request @@ -273,7 +221,7 @@ PUT api/v1/libraries/{libraryId}/metadata-providers/reorder GET api/v1/libraries/{libraryId}/artwork-providers ``` -Returns the artwork providers available for the media library, one entry per plugin that provides artwork, along with whether the provider is enabled for the media library and its rank, which determines the order in which the providers are tried when resolving the artwork. +Returns the artwork providers available for the media library, one entry per plugin that provides artwork, along with whether the provider is enabled for the media library and its rank, which determines the order in which the providers are tried when resolving the artwork. The enabled state and the rank are changed by sending the `artworkProviders` of the [Add Library](../library/management/Api.Libraries.md#add-library) or [Update Library](../library/management/Api.Libraries.md#update-library) request. #### Get Library Artwork Providers Response @@ -298,52 +246,6 @@ Returns the artwork providers available for the media library, one entry per plu ] ``` -### Set Library Artwork Provider Enabled - -#### Set Library Artwork Provider Enabled Request - -```js -PUT api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled -``` - -```json -{ - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "pluginId": "b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14", - "isEnabled": true -} -``` - -#### Set Library Artwork Provider Enabled Response - -```js -200 Ok -``` - -### Reorder Library Artwork Providers - -#### Reorder Library Artwork Providers Request - -```js -PUT api/v1/libraries/{libraryId}/artwork-providers/reorder -``` - -```json -{ - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "pluginIds": [ - "c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42", - "b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14" - ] -} -``` - -#### Reorder Library Artwork Providers Response - -```js -200 Ok -``` - ### Get Library Book Readers #### Get Library Book Readers Request @@ -352,7 +254,7 @@ PUT api/v1/libraries/{libraryId}/artwork-providers/reorder 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. +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. The enabled state is changed by sending the `bookReaders` of the [Add Library](../library/management/Api.Libraries.md#add-library) or [Update Library](../library/management/Api.Libraries.md#update-library) request. #### Get Library Book Readers Response @@ -381,31 +283,98 @@ Returns the book readers available for the media library, one entry per plugin t ] ``` -### Set Library Book Reader Enabled +### Get Library Type Metadata Providers -#### Set Library Book Reader Enabled Request +#### Get Library Type Metadata Providers Request ```js -PUT api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled +GET api/v1/libraries/metadata-providers/{libraryType} ``` -```json -{ - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", - "isEnabled": true -} -``` +Returns the metadata providers available for a media library type, without a media library, so that the providers of a library can be chosen before it is created or before a change of its type is saved. The providers are returned the way a new media library of the type starts with them: disabled, and ranked in alphabetical order. -#### Set Library Book Reader Enabled Response +#### Get Library Type Metadata Providers Response ```js 200 Ok ``` +```json +[ + { + "pluginId": "f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3", + "name": "MusicBrainz Metadata", + "isEnabled": false, + "rank": 1 + } +] +``` + +### Get Library Type Artwork Providers + +#### Get Library Type Artwork Providers Request + +```js +GET api/v1/libraries/artwork-providers/{libraryType} +``` + +Returns the artwork providers available for a media library type, without a media library, disabled and ranked in alphabetical order. + +#### Get Library Type Artwork Providers Response + +```js +200 Ok +``` + +```json +[ + { + "pluginId": "b7e4c2a9-1f38-4d65-9a02-3e6b8f5c7d14", + "name": "Cover Art Archive", + "isEnabled": false, + "rank": 1 + }, + { + "pluginId": "c9f1a7d3-2b64-4e18-8f05-7a3d9c1b6e42", + "name": "Local Music Artwork", + "isEnabled": false, + "rank": 2 + } +] +``` + +### Get Library Type Book Readers + +#### Get Library Type Book Readers Request + +```js +GET api/v1/libraries/book-readers/{libraryType} +``` + +Returns the book readers available for a media library type, without a media library, with their supported file extensions, disabled and in alphabetical order. + +#### Get Library Type Book Readers Response + +```js +200 Ok +``` + +```json +[ + { + "pluginId": "f0d1a2b3-4c5d-4e6f-8a7b-9c0d1e2f3a4b", + "name": "EPUB Reader", + "supportedExtensions": [ + ".epub" + ], + "isEnabled": false + } +] +``` + ## Music Plugins -The music media library type is served by four plugins, which register their capabilities through `IPluginServiceRegistrator`. A single plugin can expose more than one capability, and the capabilities are enabled and ranked per media library through the endpoints above. +The music media library type is served by four plugins, which register their capabilities through `IPluginServiceRegistrator`. A single plugin can expose more than one capability, and the capabilities are enabled and ranked per media library by sending the provider lists of the [Add Library](../library/management/Api.Libraries.md#add-library) or [Update Library](../library/management/Api.Libraries.md#update-library) request. | Plugin | Capability | Web access | Description | | --- | --- | --- | --- | diff --git a/docs/technical/architecture/4.2 code-book-reading-diagram.puml b/docs/technical/architecture/4.2 code-book-reading-diagram.puml index 3f319d1d..04df1260 100644 --- a/docs/technical/architecture/4.2 code-book-reading-diagram.puml +++ b/docs/technical/architecture/4.2 code-book-reading-diagram.puml @@ -123,17 +123,35 @@ class GetLibraryBookReadersQueryHandler { + HandleAsync(query: GetLibraryBookReadersQuery, token: CancellationToken): Task>> } -class SetLibraryBookReaderEnabledCommandHandler { +class GetLibraryTypeBookReadersQueryHandler { - _unitOfWork: IUnitOfWork - - _enablementCache: IBookReaderEnablementCache - + HandleAsync(command: SetLibraryBookReaderEnabledCommand, token: CancellationToken): Task> + - _providerConfigurationStore: IMediaLibraryProviderConfigurationStore + - _bookReaderRegistry: IBookReaderRegistry + + HandleAsync(query: GetLibraryTypeBookReadersQuery, token: CancellationToken): Task>> } -note right of SetLibraryBookReaderEnabledCommandHandler - Enables or disables the book reader of a plugin for a media - library by upserting its configuration row, then invalidates - the enablement cache so that a disabled reader stops being - served immediately. +note right of GetLibraryTypeBookReadersQueryHandler + Lists the book readers that support a library type, disabled, + so that they can be chosen before a library is created or + before a change of its type is saved. +end note + +class MediaLibraryProviderConfigurationStore { + - _unitOfWork: IUnitOfWork + - _enablementCache: IBookReaderEnablementCache + + ConfigureProvidersAsync(libraryId: Guid, libraryType: LibraryType, metadataProviders: IReadOnlyList?, artworkProviders: IReadOnlyList?, bookReaders: IReadOnlyList?, shouldReconcileOmittedKinds: bool, token: CancellationToken): Task> + + GetSupportedBookReaderPluginIds(libraryType: LibraryType): IReadOnlyList +} + +note right of MediaLibraryProviderConfigurationStore + Called by the add and update library commands. Applies the + chosen metadata providers, artwork providers and book readers + of a media library by upserting their configuration rows in + the same save as the library. When shouldReconcileOmittedKinds + is set, the kinds without explicit choices are reconciled with + the library type first. Book reader changes invalidate the + enablement cache of the library so that a disabled reader + stops being served immediately. end note ' ============================== BOOK READER PLUGINS ============================== @@ -221,8 +239,10 @@ BookReaderRegistry ..> IBookReader : reads the supported extensions of loaded pl GetLibraryBookReadersQueryHandler --> ILibraryBookReaderConfigurationRepository : reads configurations GetLibraryBookReadersQueryHandler --> IBookReaderRegistry : reads supported extensions -SetLibraryBookReaderEnabledCommandHandler --> ILibraryBookReaderConfigurationRepository : upserts the configuration -SetLibraryBookReaderEnabledCommandHandler --> IBookReaderEnablementCache : invalidates the entry +GetLibraryTypeBookReadersQueryHandler --> MediaLibraryProviderConfigurationStore : reads the supported readers +GetLibraryTypeBookReadersQueryHandler --> IBookReaderRegistry : reads supported extensions +MediaLibraryProviderConfigurationStore --> ILibraryBookReaderConfigurationRepository : upserts the configurations +MediaLibraryProviderConfigurationStore --> IBookReaderEnablementCache : invalidates the library entries ILibraryBookReaderConfigurationRepository --> LibraryBookReaderConfigurationEntity : persists diff --git a/docs/technical/architecture/4.2 code-book-reading-diagram.svg b/docs/technical/architecture/4.2 code-book-reading-diagram.svg index e137e374..71f770f4 100644 --- a/docs/technical/architecture/4.2 code-book-reading-diagram.svg +++ b/docs/technical/architecture/4.2 code-book-reading-diagram.svg @@ -1 +1 @@ -Code diagram for Book Reading 3.2.2 and Book Reader PluginsIBookReadingServiceGetManifestAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingManifestResponse>>GetSectionAsync(bookId: Guid,libraryId: Guid, path: string,libraryType: LibraryType,locationRef: string,shouldRenderPdfAsImages:bool, shouldPreserveStyles:bool, token:CancellationToken):Task<Result<ReadingSectionDto>>GetResourceAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,resourceKey: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,token: CancellationToken):Task<Result<ReadingAvailabilityResponse>>IBookReaderRegistryGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>IBookReaderEnablementCacheGet(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)BookReadingService_extractions:ConcurrentDictionary<ReadingCacheKey,BookExtractionEntry>_bookExtractionLocks:ConcurrentDictionary<ReadingCacheKey,SemaphoreSlim>_pluginIdsByReaderKey:IReadOnlyDictionary<ReaderKey,Guid>_enablementCache:IBookReaderEnablementCacheGetManifestAsync(...):Task<Result<ReadingManifestResponse>>GetSectionAsync(...):Task<Result<ReadingSectionDto>>GetResourceAsync(...):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(...):Task<Result<ReadingAvailabilityResponse>>Serves the manifest, sections andresources of a book:resolves the reader of the bookformat, checks theper-library enablement through thecache, reuses the alreadyextracted document while thefingerprint of the book file isunchanged, extracts eachrendering preference (text or pageimages) into its own directoryunder the reading cache, andproduces on-demand resources(for example a PDF page render)once per resource file.BookReaderRegistry_pluginManager:IPluginManager_serviceProvider:IServiceProviderGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>Reads the supported extensionslive from the book readersregistered by the loaded plugins,so that a plugin updatethat changes its formats neverleaves stale configurations.BookReaderEnablementCache_enablements:ConcurrentDictionary<(GuidLibraryId, Guid PluginId), bool>Get(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)ReadingCachePathsDIRECTORY_NAME: string =reading-cacheGetRootDirectory(): stringThe reading cache is a temporarydirectory in the API output,wiped at startup, under whichevery book keeps one directoryper rendering preference (text andimages).ReadingContentSanitizerRESOURCE_ATTRIBUTE:string = data-lumina-resourceSanitize(html: string,shouldPreserveStyles: bool):stringSanitizes every reading sectionwith an explicit allowlist ofinert markup, regardless of whatthe reader plugin produced;whether the style attributesurvives is the per-user choice.LibraryBookReaderConfigurationEntityId: GuidLibraryId: GuidPluginId: GuidIsEnabled: boolILibraryBookReaderConfigurationRepositoryGetByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>>>GetByLibraryAndPluginIdAsync(libraryId:Guid, pluginId: Guid, token:CancellationToken):Task<Result<LibraryBookReaderConfigurationEntity?>>UpsertAsync(configuration:LibraryBookReaderConfigurationEntity,token: CancellationToken):Task<Result<Updated>>DeleteByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByPluginIdAsync(pluginId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByLibraryIdAndPluginIdsAsync(libraryId:Guid, pluginIds:IEnumerable<Guid>, token:CancellationToken):Task<Result<Deleted>>LibraryBookReaderConfigurationRepositoryGetLibraryBookReadersQueryHandler_unitOfWork: IUnitOfWork_bookReaderRegistry:IBookReaderRegistryHandleAsync(query:GetLibraryBookReadersQuery,token: CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>SetLibraryBookReaderEnabledCommandHandler_unitOfWork: IUnitOfWork_enablementCache:IBookReaderEnablementCacheHandleAsync(command:SetLibraryBookReaderEnabledCommand,token: CancellationToken):Task<Result<Success>>Enables or disables the bookreader of a plugin for a medialibrary by upserting itsconfiguration row, then invalidatesthe enablement cache so that adisabled reader stops beingserved immediately.IBookReaderSupportedExtensions:IReadOnlyList<string>SupportedLibraryTypes:IReadOnlyList<LibraryType>OpenAsync(path: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<ReadingDocumentDto>GetResourceAsync(path: string,workingDirectory: string,resourceKey: string, token:CancellationToken):Task<byte[]>Contract of a reader plugin,implemented inLumina.Plugins.Contracts.The plugins are host-trusted: theyreceive the absolute path of thebook and a working directory toextract into, while the hostsanitizes and contained-checkseverything they produce beforeserving it to the client.EpubReaderReads .epub books of the EBookand Book library types.EPUB is a ZIP archive, decodedentry by entry with boundedsizes and archive-containedpaths.EpubDocumentParserParse(epubPath: string,workingDirectory: string, token:CancellationToken):ReadingDocumentDtoPdfReaderReads .pdf books of the EBookand Book library types.Each page is a reading section;the table of contents comesfrom the PDF bookmarks.PdfDocumentParserParse(pdfPath: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):ReadingDocumentDtoRenderResource(pdfPath:string, resourceKey: string,token: CancellationToken):byte[]Extracts the text layer of thepages with PdfPig, and rendersthe pages as images withPDFtoImage on demand when therender-as-images user setting isenabled; file size, page countand rendered page area arebounded.EpubPluginId: GuidName: string = EPUB ReaderRegisterServices(services:IServiceCollection)PdfPluginId: GuidName: string = PDF ReaderRegisterServices(services:IServiceCollection)implementsimplementsimplementsimplementsfinds the plugin of the book formatchecks the per-library enablementfills the cache on a missopens and produces resourcessanitizes section contentextracts into and serves fromreads the supported extensions ofloaded pluginsreads configurationsreads supported extensionsupserts the configurationinvalidates the entrypersistsimplementsimplementsparsesparses and renders pagesregisters as a keyed IBookReaderregisters as a keyed IBookReaderLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Book Reading 3.2.2 and Book Reader PluginsThe code diagram for the Book Reading 3.2.2 and the Book Reader Plugins - created with PlantUML \ No newline at end of file +Code diagram for Book Reading 3.2.2 and Book Reader PluginsIBookReadingServiceGetManifestAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingManifestResponse>>GetSectionAsync(bookId: Guid,libraryId: Guid, path: string,libraryType: LibraryType,locationRef: string,shouldRenderPdfAsImages:bool, shouldPreserveStyles:bool, token:CancellationToken):Task<Result<ReadingSectionDto>>GetResourceAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,resourceKey: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,token: CancellationToken):Task<Result<ReadingAvailabilityResponse>>IBookReaderRegistryGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>IBookReaderEnablementCacheGet(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)BookReadingService_extractions:ConcurrentDictionary<ReadingCacheKey,BookExtractionEntry>_bookExtractionLocks:ConcurrentDictionary<ReadingCacheKey,SemaphoreSlim>_pluginIdsByReaderKey:IReadOnlyDictionary<ReaderKey,Guid>_enablementCache:IBookReaderEnablementCacheGetManifestAsync(...):Task<Result<ReadingManifestResponse>>GetSectionAsync(...):Task<Result<ReadingSectionDto>>GetResourceAsync(...):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(...):Task<Result<ReadingAvailabilityResponse>>Serves the manifest, sections andresources of a book:resolves the reader of the bookformat, checks theper-library enablement through thecache, reuses the alreadyextracted document while thefingerprint of the book file isunchanged, extracts eachrendering preference (text or pageimages) into its own directoryunder the reading cache, andproduces on-demand resources(for example a PDF page render)once per resource file.BookReaderRegistry_pluginManager:IPluginManager_serviceProvider:IServiceProviderGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>Reads the supported extensionslive from the book readersregistered by the loaded plugins,so that a plugin updatethat changes its formats neverleaves stale configurations.BookReaderEnablementCache_enablements:ConcurrentDictionary<(GuidLibraryId, Guid PluginId), bool>Get(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)ReadingCachePathsDIRECTORY_NAME: string =reading-cacheGetRootDirectory(): stringThe reading cache is a temporarydirectory in the API output,wiped at startup, under whichevery book keeps one directoryper rendering preference (text andimages).ReadingContentSanitizerRESOURCE_ATTRIBUTE:string = data-lumina-resourceSanitize(html: string,shouldPreserveStyles: bool):stringSanitizes every reading sectionwith an explicit allowlist ofinert markup, regardless of whatthe reader plugin produced;whether the style attributesurvives is the per-user choice.LibraryBookReaderConfigurationEntityId: GuidLibraryId: GuidPluginId: GuidIsEnabled: boolILibraryBookReaderConfigurationRepositoryGetByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>>>GetByLibraryAndPluginIdAsync(libraryId:Guid, pluginId: Guid, token:CancellationToken):Task<Result<LibraryBookReaderConfigurationEntity?>>UpsertAsync(configuration:LibraryBookReaderConfigurationEntity,token: CancellationToken):Task<Result<Updated>>DeleteByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByPluginIdAsync(pluginId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByLibraryIdAndPluginIdsAsync(libraryId:Guid, pluginIds:IEnumerable<Guid>, token:CancellationToken):Task<Result<Deleted>>LibraryBookReaderConfigurationRepositoryGetLibraryBookReadersQueryHandler_unitOfWork: IUnitOfWork_bookReaderRegistry:IBookReaderRegistryHandleAsync(query:GetLibraryBookReadersQuery,token: CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>GetLibraryTypeBookReadersQueryHandler_unitOfWork: IUnitOfWork_providerConfigurationStore:IMediaLibraryProviderConfigurationStore_bookReaderRegistry:IBookReaderRegistryHandleAsync(query:GetLibraryTypeBookReadersQuery,token: CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>Lists the book readers thatsupport a library type, disabled,so that they can be chosen beforea library is created orbefore a change of its type issaved.MediaLibraryProviderConfigurationStore_unitOfWork: IUnitOfWork_enablementCache:IBookReaderEnablementCacheConfigureProvidersAsync(libraryId:Guid, libraryType: LibraryType,metadataProviders:IReadOnlyList<LibraryProviderSelectionDto>?,artworkProviders:IReadOnlyList<LibraryProviderSelectionDto>?,bookReaders:IReadOnlyList<LibraryProviderSelectionDto>?,shouldReconcileOmittedKinds:bool, token:CancellationToken):Task<Result<Success>>GetSupportedBookReaderPluginIds(libraryType:LibraryType):IReadOnlyList<Guid>Called by the add and updatelibrary commands. Applies thechosen metadata providers,artwork providers and bookreadersof a media library by upsertingtheir configuration rows inthe same save as the library.WhenshouldReconcileOmittedKindsis set, the kinds without explicitchoices are reconciled withthe library type first. Book readerchanges invalidate theenablement cache of the library sothat a disabled readerstops being served immediately.IBookReaderSupportedExtensions:IReadOnlyList<string>SupportedLibraryTypes:IReadOnlyList<LibraryType>OpenAsync(path: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<ReadingDocumentDto>GetResourceAsync(path: string,workingDirectory: string,resourceKey: string, token:CancellationToken):Task<byte[]>Contract of a reader plugin,implemented inLumina.Plugins.Contracts.The plugins are host-trusted: theyreceive the absolute path of thebook and a working directory toextract into, while the hostsanitizes and contained-checkseverything they produce beforeserving it to the client.EpubReaderReads .epub books of the EBookand Book library types.EPUB is a ZIP archive, decodedentry by entry with boundedsizes and archive-containedpaths.EpubDocumentParserParse(epubPath: string,workingDirectory: string, token:CancellationToken):ReadingDocumentDtoPdfReaderReads .pdf books of the EBookand Book library types.Each page is a reading section;the table of contents comesfrom the PDF bookmarks.PdfDocumentParserParse(pdfPath: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):ReadingDocumentDtoRenderResource(pdfPath:string, resourceKey: string,token: CancellationToken):byte[]Extracts the text layer of thepages with PdfPig, and rendersthe pages as images withPDFtoImage on demand when therender-as-images user setting isenabled; file size, page countand rendered page area arebounded.EpubPluginId: GuidName: string = EPUB ReaderRegisterServices(services:IServiceCollection)PdfPluginId: GuidName: string = PDF ReaderRegisterServices(services:IServiceCollection)implementsimplementsimplementsimplementsfinds the plugin of the book formatchecks the per-library enablementfills the cache on a missopens and produces resourcessanitizes section contentextracts into and serves fromreads the supported extensions ofloaded pluginsreads configurationsreads supported extensionsreads the supported readersreads supported extensionsupserts the configurationsinvalidates the library entriespersistsimplementsimplementsparsesparses and renders pagesregisters as a keyed IBookReaderregisters as a keyed IBookReaderLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Book Reading 3.2.2 and Book Reader PluginsThe code diagram for the Book Reading 3.2.2 and the Book Reader Plugins - created with PlantUML \ No newline at end of file diff --git a/docs/technical/requests/library/management/AddLibrary.http b/docs/technical/requests/library/management/AddLibrary.http index 57ca97a3..0a141063 100644 --- a/docs/technical/requests/library/management/AddLibrary.http +++ b/docs/technical/requests/library/management/AddLibrary.http @@ -20,5 +20,8 @@ Content-Type: application/json "pathTemplateParts": [ { "kind": "Artist", "representation": "{0}", "isOptional": false }, { "kind": "Separator", "representation": "", "isOptional": false } - ] + ], + "metadataProviders": null, + "artworkProviders": null, + "bookReaders": null } diff --git a/docs/technical/requests/library/management/UpdateLibrary.http b/docs/technical/requests/library/management/UpdateLibrary.http index 63065f1f..5fc86f8d 100644 --- a/docs/technical/requests/library/management/UpdateLibrary.http +++ b/docs/technical/requests/library/management/UpdateLibrary.http @@ -4,7 +4,6 @@ Content-Type: application/json { "id": "{{$guid}}", - "userId": "{{$guid}}", "title": "Books", "libraryType": "Book", "contentLocations": [ @@ -22,5 +21,8 @@ Content-Type: application/json "pathTemplateParts": [ { "kind": "Artist", "representation": "{0}", "isOptional": false }, { "kind": "Separator", "representation": "", "isOptional": false } - ] + ], + "metadataProviders": null, + "artworkProviders": null, + "bookReaders": null } diff --git a/docs/technical/requests/plugins/GetLibraryTypeArtworkProviders.http b/docs/technical/requests/plugins/GetLibraryTypeArtworkProviders.http new file mode 100644 index 00000000..1590a8cc --- /dev/null +++ b/docs/technical/requests/plugins/GetLibraryTypeArtworkProviders.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/artwork-providers/Book +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/plugins/GetLibraryTypeBookReaders.http b/docs/technical/requests/plugins/GetLibraryTypeBookReaders.http new file mode 100644 index 00000000..d0af07af --- /dev/null +++ b/docs/technical/requests/plugins/GetLibraryTypeBookReaders.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/book-readers/Book +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/plugins/GetLibraryTypeMetadataProviders.http b/docs/technical/requests/plugins/GetLibraryTypeMetadataProviders.http new file mode 100644 index 00000000..86d7e01b --- /dev/null +++ b/docs/technical/requests/plugins/GetLibraryTypeMetadataProviders.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/metadata-providers/Book +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/plugins/ReorderLibraryArtworkProviders.http b/docs/technical/requests/plugins/ReorderLibraryArtworkProviders.http deleted file mode 100644 index 26b86886..00000000 --- a/docs/technical/requests/plugins/ReorderLibraryArtworkProviders.http +++ /dev/null @@ -1,11 +0,0 @@ -PUT {{host}}/api/v1/libraries/{{$guid}}/artwork-providers/reorder -Authorization: Bearer {{ACCESS_TOKEN}} -Content-Type: application/json - -{ - "libraryId": "{{$guid}}", - "pluginIds": [ - "{{$guid}}", - "{{$guid}}" - ] -} diff --git a/docs/technical/requests/plugins/ReorderLibraryMetadataProviders.http b/docs/technical/requests/plugins/ReorderLibraryMetadataProviders.http deleted file mode 100644 index 4e380910..00000000 --- a/docs/technical/requests/plugins/ReorderLibraryMetadataProviders.http +++ /dev/null @@ -1,11 +0,0 @@ -PUT {{host}}/api/v1/libraries/{{$guid}}/metadata-providers/reorder -Authorization: Bearer {{ACCESS_TOKEN}} -Content-Type: application/json - -{ - "libraryId": "{{$guid}}", - "pluginIds": [ - "{{$guid}}", - "{{$guid}}" - ] -} diff --git a/docs/technical/requests/plugins/SetLibraryArtworkProviderEnabled.http b/docs/technical/requests/plugins/SetLibraryArtworkProviderEnabled.http deleted file mode 100644 index c12b851b..00000000 --- a/docs/technical/requests/plugins/SetLibraryArtworkProviderEnabled.http +++ /dev/null @@ -1,9 +0,0 @@ -PUT {{host}}/api/v1/libraries/{{$guid}}/artwork-providers/{{$guid}}/enabled -Authorization: Bearer {{ACCESS_TOKEN}} -Content-Type: application/json - -{ - "libraryId": "{{$guid}}", - "pluginId": "{{$guid}}", - "isEnabled": true -} diff --git a/docs/technical/requests/plugins/SetLibraryBookReaderEnabled.http b/docs/technical/requests/plugins/SetLibraryBookReaderEnabled.http deleted file mode 100644 index b340bd38..00000000 --- a/docs/technical/requests/plugins/SetLibraryBookReaderEnabled.http +++ /dev/null @@ -1,9 +0,0 @@ -PUT {{host}}/api/v1/libraries/{{$guid}}/book-readers/{{$guid}}/enabled -Authorization: Bearer {{ACCESS_TOKEN}} -Content-Type: application/json - -{ - "libraryId": "{{$guid}}", - "pluginId": "{{$guid}}", - "isEnabled": true -} diff --git a/docs/technical/requests/plugins/SetLibraryMetadataProviderEnabled.http b/docs/technical/requests/plugins/SetLibraryMetadataProviderEnabled.http deleted file mode 100644 index cdcabb4b..00000000 --- a/docs/technical/requests/plugins/SetLibraryMetadataProviderEnabled.http +++ /dev/null @@ -1,9 +0,0 @@ -PUT {{host}}/api/v1/libraries/{{$guid}}/metadata-providers/{{$guid}}/enabled -Authorization: Bearer {{ACCESS_TOKEN}} -Content-Type: application/json - -{ - "libraryId": "{{$guid}}", - "pluginId": "{{$guid}}", - "isEnabled": true -} diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDto.cs new file mode 100644 index 00000000..cefd576f --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.Management; + +/// +/// Data transfer object for the choice made for one metadata provider, artwork provider or book reader of a media library, carried by the commands that create or update a media library. +/// +/// The Id of the plugin providing the metadata provider, artwork provider or book reader. +/// Whether the provider or reader is enabled for the media library. When absent, the stored state is kept, and a provider or reader without a stored state starts disabled. +[DebuggerDisplay("PluginId: {PluginId}; IsEnabled: {IsEnabled}")] +public record LibraryProviderSelectionDto( + Guid PluginId, + bool? IsEnabled +); diff --git a/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs b/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs index 3f911baa..444cc400 100644 --- a/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs +++ b/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; @@ -11,7 +12,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.Infrastructure.Plugins; /// -/// Store of the metadata and artwork provider configurations of the media libraries. +/// Store of the metadata provider, artwork provider and book reader configurations of the media libraries. /// public interface IMediaLibraryProviderConfigurationStore { @@ -24,25 +25,18 @@ public interface IMediaLibraryProviderConfigurationStore Task>> GetConfigurationsAsync(Guid libraryId, CancellationToken cancellationToken); /// - /// Adds a disabled provider configuration for every loaded plugin that supports the provided library type and has no + /// Adds a disabled metadata provider, artwork provider and book reader configuration for every loaded plugin that supports the provided library type and has no /// configuration yet for the media library identified by . /// + /// + /// The added configurations are only staged until the unit of work is saved, and are not visible to a later ensure, so it must be called at most once per media library before the changes are saved. + /// /// The Id of the media library whose provider configurations are ensured. /// The type of the media library, used to determine the plugins whose providers apply. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> EnsureProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); - /// - /// Replaces the provider configurations of the media library identified by so that they - /// match the plugins supporting the provided library type. - /// - /// The Id of the media library whose provider configurations are reconciled. - /// The type of the media library, used to determine the plugins whose providers apply. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); - /// /// Deletes all the provider configurations of the media library identified by . /// @@ -60,36 +54,52 @@ public interface IMediaLibraryProviderConfigurationStore Task> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken); /// - /// Adds a disabled book reader configuration for every loaded plugin that supports the provided library type and has no configuration yet, for the media library identified by . + /// Makes the provider and book reader configurations of the media library identified by match the plugins supporting the provided library type, and applies the choices made for them. /// - /// The Id of the media library whose book reader configurations are ensured. - /// The type of the media library, used to determine the plugins whose book readers apply. + /// + /// A list that is provided reconciles that kind of configuration with the library type and applies the choices: the configurations of the plugins that do not support the library type + /// are removed, even when the list does not name them, every supported plugin gets a configuration, and the list sets the enabled state of every provider or reader it names and, for the + /// metadata and artwork providers, their order. A choice without an enabled state keeps the stored state, the supported plugins the list does not name keep their stored state and are + /// ordered after the named ones, and a plugin without a stored configuration starts disabled. A list that is leaves that kind of configuration untouched, unless + /// is , in which case it is reconciled the same way, without choices. Whenever the book reader configurations are + /// reconciled or chosen, the cached reader enablements of the library are dropped. + /// + /// The Id of the media library whose provider and book reader configurations are configured. + /// The type of the media library, used to determine the plugins whose providers and book readers apply. + /// The choices made for the metadata providers, in the order in which they are tried. + /// The choices made for the artwork providers, in the order in which they are tried. + /// The choices made for the book readers. + /// Whether the kinds of configuration whose list of choices is are reconciled with the library type, which is needed when the + /// library is new or its type changed. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); + /// An representing either a successful operation, or an error when a choice names a plugin that does not support the library type. + Task> ConfigureProvidersAsync( + Guid libraryId, + LibraryType libraryType, + IReadOnlyList? metadataProviders, + IReadOnlyList? artworkProviders, + IReadOnlyList? bookReaders, + bool shouldReconcileOmittedKinds, + CancellationToken cancellationToken); /// - /// Replaces the book reader configurations of the media library identified by so that they match the plugins supporting the provided library type. + /// Gets the Ids of the loaded plugins that provide metadata for the provided library type, ordered alphabetically by plugin name. /// - /// The Id of the media library whose book reader configurations are reconciled. - /// The type of the media library, used to determine the plugins whose book readers apply. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); + /// The type of the media library the metadata providers must support. + /// The Ids of the plugins providing metadata for the library type. + IReadOnlyList GetSupportedMetadataProviderPluginIds(LibraryType libraryType); /// - /// Deletes all the book reader configurations of the media library identified by . + /// Gets the Ids of the loaded plugins that provide artwork for the provided library type, ordered alphabetically by plugin name. /// - /// The Id of the media library whose book reader configurations are deleted. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + /// The type of the media library the artwork providers must support. + /// The Ids of the plugins providing artwork for the library type. + IReadOnlyList GetSupportedArtworkProviderPluginIds(LibraryType libraryType); /// - /// Deletes all the book reader configurations referencing the plugin identified by . + /// Gets the Ids of the loaded plugins that provide a book reader for the provided library type, ordered alphabetically by plugin name. /// - /// The Id of the plugin whose book reader configurations are deleted. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken); + /// The type of the media library the book readers must support. + /// The Ids of the plugins providing a book reader for the library type. + IReadOnlyList GetSupportedBookReaderPluginIds(LibraryType libraryType); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs index 0c62bc02..b9044904 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; using System.Linq; #endregion @@ -15,6 +16,10 @@ public static class AddMediaLibraryRequestMapping /// /// Converts to . /// + /// + /// A path template part that is is converted to a part without a kind, and a provider or book reader choice that is is + /// converted to a choice without a plugin Id, so that the validation of the command reports them, instead of the conversion failing before the command is validated. + /// /// The request to be converted. /// The converted command. public static AddLibraryCommand ToCommand(this AddLibraryRequest request) @@ -32,7 +37,10 @@ public static class AddMediaLibraryRequestMapping request.IsContentOnSsd, request.ShouldTrackConsumptionProgress, request.CompletionThresholdPercentage, - request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray() + request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part?.Kind, part?.Representation, part?.IsOptional ?? false)).ToArray(), + request.MetadataProviders?.Select(provider => new LibraryProviderSelectionDto(provider?.PluginId ?? Guid.Empty, provider?.IsEnabled)).ToArray(), + request.ArtworkProviders?.Select(provider => new LibraryProviderSelectionDto(provider?.PluginId ?? Guid.Empty, provider?.IsEnabled)).ToArray(), + request.BookReaders?.Select(reader => new LibraryProviderSelectionDto(reader?.PluginId ?? Guid.Empty, reader?.IsEnabled)).ToArray() ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs index 6ab4c212..75add9b6 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; using System.Linq; #endregion @@ -15,13 +16,16 @@ public static class UpdateLibraryRequestMapping /// /// Converts to . /// + /// + /// A path template part that is is converted to a part without a kind, and a provider or book reader choice that is is + /// converted to a choice without a plugin Id, so that the validation of the command reports them, instead of the conversion failing before the command is validated. + /// /// The request to be converted. /// The converted command. public static UpdateLibraryCommand ToCommand(this UpdateLibraryRequest request) { return new UpdateLibraryCommand( request.Id, - request.UserId, request.Title, request.LibraryType, request.ContentLocations, @@ -34,7 +38,10 @@ public static class UpdateLibraryRequestMapping request.IsContentOnSsd, request.ShouldTrackConsumptionProgress, request.CompletionThresholdPercentage, - request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part.Kind, part.Representation, part.IsOptional)).ToArray() + request.PathTemplateParts?.Select(part => new LibraryPathTemplatePartDto(part?.Kind, part?.Representation, part?.IsOptional ?? false)).ToArray(), + request.MetadataProviders?.Select(provider => new LibraryProviderSelectionDto(provider?.PluginId ?? Guid.Empty, provider?.IsEnabled)).ToArray(), + request.ArtworkProviders?.Select(provider => new LibraryProviderSelectionDto(provider?.PluginId ?? Guid.Empty, provider?.IsEnabled)).ToArray(), + request.BookReaders?.Select(reader => new LibraryProviderSelectionDto(reader?.PluginId ?? Guid.Empty, reader?.IsEnabled)).ToArray() ); } } diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMapping.cs new file mode 100644 index 00000000..73e2945c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryTypeArtworkProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryTypeArtworkProvidersQuery ToQuery(this GetLibraryTypeArtworkProvidersRequest request) + { + return new GetLibraryTypeArtworkProvidersQuery( + request.LibraryType + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMapping.cs new file mode 100644 index 00000000..f299d721 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryTypeBookReadersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryTypeBookReadersQuery ToQuery(this GetLibraryTypeBookReadersRequest request) + { + return new GetLibraryTypeBookReadersQuery( + request.LibraryType + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMapping.cs new file mode 100644 index 00000000..31826085 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryTypeMetadataProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryTypeMetadataProvidersQuery ToQuery(this GetLibraryTypeMetadataProvidersRequest request) + { + return new GetLibraryTypeMetadataProvidersQuery( + request.LibraryType + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs deleted file mode 100644 index 7b0ab2fc..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Contracts.Requests.Plugins; -#endregion - -namespace Lumina.Application.Common.Mapping.Plugins; - -/// -/// Extension methods for converting . -/// -public static class ReorderLibraryArtworkProvidersRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted command. - public static ReorderLibraryArtworkProvidersCommand ToCommand(this ReorderLibraryArtworkProvidersRequest request) - { - return new ReorderLibraryArtworkProvidersCommand( - LibraryId: request.LibraryId, - PluginIds: request.PluginIds - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs deleted file mode 100644 index 6857df1e..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMapping.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Contracts.Requests.Plugins; -#endregion - -namespace Lumina.Application.Common.Mapping.Plugins; - -/// -/// Extension methods for converting . -/// -public static class ReorderLibraryMetadataProvidersRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted command. - public static ReorderLibraryMetadataProvidersCommand ToCommand(this ReorderLibraryMetadataProvidersRequest request) - { - return new ReorderLibraryMetadataProvidersCommand(request.LibraryId, request.PluginIds); - } -} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs deleted file mode 100644 index 4494aeb8..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs +++ /dev/null @@ -1,26 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Contracts.Requests.Plugins; -#endregion - -namespace Lumina.Application.Common.Mapping.Plugins; - -/// -/// Extension methods for converting . -/// -public static class SetLibraryArtworkProviderEnabledRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted command. - public static SetLibraryArtworkProviderEnabledCommand ToCommand(this SetLibraryArtworkProviderEnabledRequest request) - { - return new SetLibraryArtworkProviderEnabledCommand( - LibraryId: request.LibraryId, - PluginId: request.PluginId, - IsEnabled: request.IsEnabled - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs deleted file mode 100644 index 727601ca..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMapping.cs +++ /dev/null @@ -1,26 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Contracts.Requests.Plugins; -#endregion - -namespace Lumina.Application.Common.Mapping.Plugins; - -/// -/// Extension methods for converting . -/// -public static class SetLibraryBookReaderEnabledRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted command. - public static SetLibraryBookReaderEnabledCommand ToCommand(this SetLibraryBookReaderEnabledRequest request) - { - return new SetLibraryBookReaderEnabledCommand( - request.LibraryId, - request.PluginId, - request.IsEnabled - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs deleted file mode 100644 index a0b46032..00000000 --- a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMapping.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Contracts.Requests.Plugins; -#endregion - -namespace Lumina.Application.Common.Mapping.Plugins; - -/// -/// Extension methods for converting . -/// -public static class SetLibraryMetadataProviderEnabledRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted command. - public static SetLibraryMetadataProviderEnabledCommand ToCommand(this SetLibraryMetadataProviderEnabledRequest request) - { - return new SetLibraryMetadataProviderEnabledCommand(request.LibraryId, request.PluginId, request.IsEnabled); - } -} diff --git a/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs index b6a46775..dd9a9998 100644 --- a/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs +++ b/src/Lumina.Application/Core/Favorites/Commands/RemoveFavorite/RemoveFavoriteCommandValidator.cs @@ -4,7 +4,6 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.Favorites; using System; -using System.Linq; #endregion namespace Lumina.Application.Core.Favorites.Commands.RemoveFavorite; @@ -26,9 +25,12 @@ public class RemoveFavoriteCommandValidator : AbstractValidator command.MediaKind) - .Must(mediaKind => Enum.GetNames() - .Where(mediaKindName => !string.Equals(mediaKindName, nameof(FavoriteMediaKind.None), StringComparison.Ordinal)) - .Contains(mediaKind, StringComparer.OrdinalIgnoreCase)) + .IsInEnum() + .When(command => command.MediaKind is not null && command.MediaKind.Length > 0) + .WithError(Errors.Favorites.FavoriteMediaKindIsInvalid); + + RuleFor(command => command.MediaKind) + .Must(mediaKind => !string.Equals(mediaKind, nameof(FavoriteMediaKind.None), StringComparison.OrdinalIgnoreCase)) .When(command => command.MediaKind is not null && command.MediaKind.Length > 0) .WithError(Errors.Favorites.FavoriteMediaKindIsInvalid); diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs index f12a2dab..d39cfe27 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs @@ -4,7 +4,6 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; -using System.Linq; #endregion namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption; @@ -35,7 +34,7 @@ public class StartConsumptionCommandValidator : AbstractValidator command.MediaKind) - .Must(mediaKind => Enum.GetNames().Contains(mediaKind, StringComparer.OrdinalIgnoreCase)) + .IsInEnum() .When(command => command.MediaKind is not null && command.MediaKind.Length > 0) .WithError(Errors.MediaConsumption.UnsupportedMediaKind); diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs index 389ae690..64fbe268 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetResumePoint/GetResumePointQueryValidator.cs @@ -4,7 +4,6 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; -using System.Linq; #endregion namespace Lumina.Application.Core.MediaConsumption.Queries.GetResumePoint; @@ -25,7 +24,7 @@ public class GetResumePointQueryValidator : AbstractValidator query.MediaKind) - .Must(mediaKind => Enum.GetNames().Contains(mediaKind, StringComparer.OrdinalIgnoreCase)) + .IsInEnum() .When(query => query.MediaKind is not null && query.MediaKind.Length > 0) .WithError(Errors.MediaConsumption.UnsupportedMediaKind); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index 6b013e07..92600e28 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -22,6 +22,9 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// Whether the consumption progress of the media library items should be tracked, or not. When absent, the default of the library type is used. /// The percentage of a media library item that must be consumed for its session to be considered completed. When absent, the default of the library type is used on creation. /// The ordered parts of the template describing the structure of the media library on disk. +/// The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, every provider supported by the library type is added disabled. +/// The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, every provider supported by the library type is added disabled. +/// The book readers of the media library, and whether each one is enabled. When absent, every reader supported by the library type is added disabled. [DebuggerDisplay("Title: {Title}")] public record AddLibraryCommand( string? Title, @@ -36,5 +39,8 @@ public record AddLibraryCommand( bool IsContentOnSsd, bool? ShouldTrackConsumptionProgress, int? CompletionThresholdPercentage, - LibraryPathTemplatePartDto[]? PathTemplateParts + LibraryPathTemplatePartDto[]? PathTemplateParts, + LibraryProviderSelectionDto[]? MetadataProviders, + LibraryProviderSelectionDto[]? ArtworkProviders, + LibraryProviderSelectionDto[]? BookReaders ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 1a4cf50b..2f6232dd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -114,7 +114,7 @@ public class AddLibraryCommandHandler : ICommandHandler(command.LibraryType!); + LibraryType libraryType = Enum.Parse(command.LibraryType!, ignoreCase: true); // A library created without explicit consumption settings uses the defaults of its type. When progress tracking is on and no threshold is // supplied, the default threshold of the type is used; a type without one keeps no threshold, which means completion is recorded explicitly. @@ -158,15 +158,15 @@ public class AddLibraryCommandHandler : ICommandHandler insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (insertLibraryResult.IsFailure) return insertLibraryResult.Errors; - Result ensureProviderConfigurationsResult = await _providerConfigurationStore.EnsureProviderConfigurationsAsync( - createLibraryResult.Value.Id.Value, libraryType, cancellationToken).ConfigureAwait(false); - if (ensureProviderConfigurationsResult.IsFailure) - return ensureProviderConfigurationsResult.Errors; + Result configureProvidersResult = await _providerConfigurationStore.ConfigureProvidersAsync( + createLibraryResult.Value.Id.Value, libraryType, command.MetadataProviders, command.ArtworkProviders, command.BookReaders, shouldReconcileOmittedKinds: true, cancellationToken).ConfigureAwait(false); + if (configureProvidersResult.IsFailure) + return configureProvidersResult.Errors; Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs index d5974c69..beb7f1c6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Errors; using System; +using System.Linq; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; @@ -21,7 +22,7 @@ public class AddLibraryCommandValidator : AbstractValidator RuleFor(command => command.LibraryType) .NotNull() .WithError(Errors.Library.LibraryTypeCannotBeNull) - .Must(libraryType => Enum.TryParse(libraryType, out _)) + .IsInEnum() .WithError(Errors.Library.UnknownLibraryType); RuleFor(command => command.ContentLocations) @@ -61,5 +62,32 @@ public class AddLibraryCommandValidator : AbstractValidator .When(pathPart => !string.Equals(pathPart.Kind, nameof(LibraryPathPartKind.Separator), StringComparison.OrdinalIgnoreCase)) .WithError(Errors.Library.PathTemplateLiteralCannotBeEmpty); }); + + RuleForEach(command => command.MetadataProviders) + .ChildRules(provider => provider.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.MetadataProviders) + .Must(providers => providers is null || providers.Select(selection => selection.PluginId).Distinct().Count() == providers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); + + RuleForEach(command => command.ArtworkProviders) + .ChildRules(provider => provider.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.ArtworkProviders) + .Must(providers => providers is null || providers.Select(selection => selection.PluginId).Distinct().Count() == providers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); + + RuleForEach(command => command.BookReaders) + .ChildRules(reader => reader.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.BookReaders) + .Must(readers => readers is null || readers.Select(selection => selection.PluginId).Distinct().Count() == readers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index ae7b4e06..81572f86 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -13,6 +13,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; using System.Collections.Generic; using System.Threading; @@ -85,10 +86,12 @@ public class DeleteLibraryCommandHandler : ICommandHandler( - userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) + // Admins can delete any library. Everyone else can only delete the libraries they own, and only while they hold the permission to manage media + // libraries, which can be withheld to keep a user from deleting even the libraries they own. + if (!await _authorizationService.EvaluatePolicyAsync(userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false) && + !await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false)) return ApplicationErrors.Authorization.NotAuthorized; // Create a domain library object. diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs index 66819bd4..5ad99baf 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommand.cs @@ -11,7 +11,6 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// Command for updating a media library. /// /// The unique identifier of the media library. -/// The unique identifier of the user owning the media library. /// The title of the media library. /// The type of the media library. /// The file system paths of the directories where the media library elements are located. @@ -25,10 +24,12 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary /// Whether the consumption progress of the media library items should be tracked, or not. When absent, the stored value is kept. /// The percentage of a media library item that must be consumed for its session to be considered completed. When absent, the stored value is kept. /// The ordered parts of the template describing the structure of the media library on disk. +/// The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, the stored configurations are kept, or reconciled with the library type when it changes. +/// The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, the stored configurations are kept, or reconciled with the library type when it changes. +/// The book readers of the media library, and whether each one is enabled. When absent, the stored configurations are kept, or reconciled with the library type when it changes. [DebuggerDisplay("Title: {Title}")] public record UpdateLibraryCommand( Guid Id, - Guid OwnerId, string? Title, string? LibraryType, string[]? ContentLocations, @@ -41,5 +42,8 @@ public record UpdateLibraryCommand( bool IsContentOnSsd, bool? ShouldTrackConsumptionProgress, int? CompletionThresholdPercentage, - LibraryPathTemplatePartDto[]? PathTemplateParts + LibraryPathTemplatePartDto[]? PathTemplateParts, + LibraryProviderSelectionDto[]? MetadataProviders, + LibraryProviderSelectionDto[]? ArtworkProviders, + LibraryProviderSelectionDto[]? BookReaders ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index b77a417c..84209f82 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -105,6 +105,16 @@ public class UpdateLibraryCommandHandler : ICommandHandler(userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false) && + !await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + bool hasProviderChoices = command.MetadataProviders is not null || command.ArtworkProviders is not null || command.BookReaders is not null; + // Make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is // relative to the application base directory and is already validated, so it must not block saving unrelated changes. if (command.CoverImage is not null && command.CoverImage != getLibraryResult.Value.CoverImage) @@ -120,15 +130,8 @@ public class UpdateLibraryCommandHandler : ICommandHandler( - userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); - if (!hasManagePermission && !canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - // Create a domain library object. - LibraryType newLibraryType = Enum.Parse(command.LibraryType!); + LibraryType newLibraryType = Enum.Parse(command.LibraryType!, ignoreCase: true); // Keep the stored consumption settings unless the request explicitly changes them. When progress tracking is enabled and // no threshold is supplied, the stored threshold is kept; the value object never retains a threshold while tracking is disabled. @@ -157,9 +160,10 @@ public class UpdateLibraryCommandHandler : ICommandHandler createLibraryResult = Library.Create( LibraryId.Create(command.Id), - UserId.Create(command.OwnerId), + UserId.Create(getLibraryResult.Value.UserId), command.Title!, newLibraryType, command.ContentLocations!, @@ -179,16 +183,19 @@ public class UpdateLibraryCommandHandler : ICommandHandler updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) return updateLibraryResult.Errors; - if (getLibraryResult.Value.LibraryType != newLibraryType) + bool isLibraryTypeChanged = getLibraryResult.Value.LibraryType != newLibraryType; + if (isLibraryTypeChanged || hasProviderChoices) { - Result reconcileResult = await _providerConfigurationStore.ReconcileProviderConfigurationsAsync(command.Id, newLibraryType, cancellationToken).ConfigureAwait(false); - if (reconcileResult.IsFailure) - return reconcileResult.Errors; + Result configureProvidersResult = await _providerConfigurationStore.ConfigureProvidersAsync( + command.Id, newLibraryType, command.MetadataProviders, command.ArtworkProviders, command.BookReaders, isLibraryTypeChanged, cancellationToken).ConfigureAwait(false); + if (configureProvidersResult.IsFailure) + return configureProvidersResult.Errors; } Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs index d0a2c721..70d8deff 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Errors; using System; +using System.Linq; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; @@ -24,16 +25,10 @@ public class UpdateLibraryCommandValidator : AbstractValidator id != Guid.Empty) .WithError(Errors.Library.LibraryIdCannotBeEmpty); - RuleFor(command => command.OwnerId) - .NotEmpty() - .WithError(Errors.Users.UserIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Users.UserIdCannotBeEmpty); - RuleFor(command => command.LibraryType) .NotNull() .WithError(Errors.Library.LibraryTypeCannotBeNull) - .Must(libraryType => Enum.TryParse(libraryType, out _)) + .IsInEnum() .WithError(Errors.Library.UnknownLibraryType); RuleFor(command => command.ContentLocations) @@ -73,5 +68,32 @@ public class UpdateLibraryCommandValidator : AbstractValidator !string.Equals(pathPart.Kind, nameof(LibraryPathPartKind.Separator), StringComparison.OrdinalIgnoreCase)) .WithError(Errors.Library.PathTemplateLiteralCannotBeEmpty); }); + + RuleForEach(command => command.MetadataProviders) + .ChildRules(provider => provider.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.MetadataProviders) + .Must(providers => providers is null || providers.Select(selection => selection.PluginId).Distinct().Count() == providers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); + + RuleForEach(command => command.ArtworkProviders) + .ChildRules(provider => provider.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.ArtworkProviders) + .Must(providers => providers is null || providers.Select(selection => selection.PluginId).Distinct().Count() == providers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); + + RuleForEach(command => command.BookReaders) + .ChildRules(reader => reader.RuleFor(selection => selection.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty)); + + RuleFor(command => command.BookReaders) + .Must(readers => readers is null || readers.Select(selection => selection.PluginId).Distinct().Count() == readers.Length) + .WithError(Errors.Plugins.PluginIdsMustBeUnique); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs index ac64fcec..b39ec76d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandler.cs @@ -41,19 +41,19 @@ public class GetLibraryPathTemplatePartsQueryHandler : IQueryHandler public Task> HandleAsync(GetLibraryPathTemplatePartsQuery query, CancellationToken cancellationToken) { - // the library type travels as a string taken from the route, and is matched against the enum the same way the create and update + // The library type travels as a string taken from the route, and is matched against the enum the same way the create and update // library commands do, so that a malformed type is reported as an unknown library type instead of silently returning an empty catalog. - if (!Enum.TryParse(query.LibraryType, ignoreCase: true, out LibraryType libraryType)) + if (!Enum.TryParse(query.LibraryType, ignoreCase: true, out LibraryType libraryType) || !Enum.IsDefined(libraryType)) return Task.FromResult>(DomainErrors.Library.UnknownLibraryType); - // only the catalog registered for the requested library type applies, so the parts and the default structure offered to the user are + // Only the catalog registered for the requested library type applies, so the parts and the default structure offered to the user are // type aware (music libraries get artist and release parts, book libraries get author and title parts, and so on). ILibraryPathPartCatalog? catalog = _catalogs.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); if (catalog is null) - // a library type without a catalog has no structure to describe, so an empty catalog is returned, which the client uses to hide the editor. + // A library type without a catalog has no structure to describe, so an empty catalog is returned, which the client uses to hide the editor. return Task.FromResult(Result.Success(new LibraryPathTemplateCatalogResponse([], []))); - // the selectable parts describe what the user can drop into the template, together with the value type and the default on-disk representation of each part. + // The selectable parts describe what the user can drop into the template, together with the value type and the default on-disk representation of each part. List parts = [ .. catalog.GetPartDefinitions().Select(definition => new LibraryPathPartDefinitionResponse( @@ -62,7 +62,7 @@ public class GetLibraryPathTemplatePartsQueryHandler : IQueryHandler defaultTemplateParts = [ .. catalog.GetDefaultTemplate().Parts.Select(part => new LibraryPathTemplatePartResponse(part.Kind.ToString(), part.Representation, part.IsOptional)) diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs deleted file mode 100644 index a202a355..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using System; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Command for reordering the artwork providers of a media library. -/// -/// The Id of the media library whose artwork providers are reordered. -/// The plugin Ids in the new order, from highest to lowest rank. -public record ReorderLibraryArtworkProvidersCommand( - Guid LibraryId, - IReadOnlyList PluginIds -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs deleted file mode 100644 index 8c713a6b..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs +++ /dev/null @@ -1,98 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Validation; -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.Commands.ReorderLibraryArtworkProviders; - -/// -/// Handler for the command to reorder the artwork providers of a media library. -/// -public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public ReorderLibraryArtworkProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// Handles the command to reorder the artwork providers of a media library. - /// - /// The request to be handled. - /// Cancellation token that can be used to stop the execution. - /// - /// An representing either a successful operation, or an error. - /// - public async Task> HandleAsync(ReorderLibraryArtworkProvidersCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can reorder the artwork providers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - // Load the artwork provider configurations that are currently registered for the library, so that only providers it actually has are reordered. - Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - return getConfigurationsResult.Errors; - - // Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list. - Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); - // Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice. - for (int rank = 0; rank < command.PluginIds.Count; rank++) - { - Guid pluginId = command.PluginIds[rank]; - if (configurationsByPluginId.TryGetValue(pluginId, out LibraryArtworkProviderConfigurationEntity? configuration)) - { - configuration.Rank = rank + 1; - Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - } - } - - // Persist all the rank changes in a single save, so that the reorder is applied atomically. - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs deleted file mode 100644 index 770f3f31..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -#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.ReorderLibraryArtworkProviders; - -/// -/// Validates the needed validation rules for . -/// -public class ReorderLibraryArtworkProvidersCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryArtworkProvidersCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginIds) - .NotNull() - .WithError(Errors.Plugins.PluginIdsListCannotBeNull) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs deleted file mode 100644 index a1ab58c2..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommand.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using System; -using System.Collections.Generic; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Command for reordering the metadata providers of a media library. -/// -/// The Id of the media library whose metadata providers are reordered. -/// The plugin Ids in the new order, from highest to lowest rank. -public record ReorderLibraryMetadataProvidersCommand( - Guid LibraryId, - IReadOnlyList PluginIds -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs deleted file mode 100644 index 3b3133c8..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ /dev/null @@ -1,97 +0,0 @@ -#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.Validation; -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.Commands.ReorderLibraryMetadataProviders; - -/// -/// Handler for the command to reorder the metadata providers of a media library. -/// -public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public ReorderLibraryMetadataProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// Handles the command to reorder the metadata providers of a media library. - /// - /// The request to be handled. - /// Cancellation token that can be used to stop the execution. - /// - /// An representing either a successful operation, or an error. - /// - public async Task> HandleAsync(ReorderLibraryMetadataProvidersCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can reorder the metadata providers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - // Load the metadata provider configurations that are currently registered for the library, so that only providers it actually has are reordered. - Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - return getConfigurationsResult.Errors; - - // Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list. - Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); - // Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice. - for (int rank = 0; rank < command.PluginIds.Count; rank++) - { - Guid pluginId = command.PluginIds[rank]; - if (configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? configuration)) - { - configuration.Rank = rank + 1; - Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - } - } - - // Persist all the rank changes in a single save, so that the reorder is applied atomically. - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs deleted file mode 100644 index 95c01884..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -#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.ReorderLibraryMetadataProviders; - -/// -/// Validates the needed validation rules for . -/// -public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryMetadataProvidersCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginIds) - .NotNull() - .WithError(Errors.Plugins.PluginIdsListCannotBeNull) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs deleted file mode 100644 index e4acf111..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Command for enabling or disabling an artwork provider for a media library. -/// -/// The Id of the media library whose artwork provider is enabled or disabled. -/// The unique identifier of the plugin providing the artwork. -/// Whether the artwork provider should be enabled for the media library. -public record SetLibraryArtworkProviderEnabledCommand( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs deleted file mode 100644 index 09b304db..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs +++ /dev/null @@ -1,113 +0,0 @@ -#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.Validation; -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.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Handler for the command to enable or disable an artwork provider for a media library. -/// -public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public SetLibraryArtworkProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// Handles the command to enable or disable an artwork provider for a media library. - /// - /// The request to be handled. - /// Cancellation token that can be used to stop the execution. - /// - /// An representing either a successful operation, or an error. - /// - public async Task> HandleAsync(SetLibraryArtworkProviderEnabledCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can configure the artwork providers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - // Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated. - Result getConfigurationResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); - if (getConfigurationResult.IsFailure) - return getConfigurationResult.Errors; - - LibraryArtworkProviderConfigurationEntity configuration; - if (getConfigurationResult.Value is not null) - { - // The provider is already configured for the library, so only its enabled state changes, keeping its existing rank in the display order. - configuration = getConfigurationResult.Value; - configuration.IsEnabled = command.IsEnabled; - } - else - { - // Compute the rank to assign to the new configuration, appending it after the existing ones. - Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - return getConfigurationsResult.Errors; - int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; - configuration = new LibraryArtworkProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = command.LibraryId, - PluginId = command.PluginId, - IsEnabled = command.IsEnabled, - Rank = nextRank, - CreatedOnUtc = default, - CreatedBy = default, - UpdatedBy = default - }; - } - - // Insert the new configuration, or update the existing one, and persist the change. - Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs deleted file mode 100644 index 040a486f..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -#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.SetLibraryArtworkProviderEnabled; - -/// -/// Validates the needed validation rules for . -/// -public class SetLibraryArtworkProviderEnabledCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryArtworkProviderEnabledCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginId) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.PluginIdCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs deleted file mode 100644 index a40b4e93..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommand.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Command for enabling or disabling a book reader for a media library. -/// -/// The Id of the media library whose book reader is enabled or disabled. -/// The unique identifier of the plugin providing the book reader. -/// Whether the book reader should be enabled for the media library. -public record SetLibraryBookReaderEnabledCommand( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs deleted file mode 100644 index 6ff5d6c9..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs +++ /dev/null @@ -1,108 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Authentication; -using Lumina.Application.Common.Infrastructure.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; -using Lumina.Application.Common.Infrastructure.Reading; -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Handler for the command to enable or disable a book reader for a media library. -/// -public class SetLibraryBookReaderEnabledCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IBookReaderEnablementCache _enablementCache; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected cache of whether the book reader of a plugin is enabled for a media library. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public SetLibraryBookReaderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderEnablementCache enablementCache, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _enablementCache = enablementCache; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// Handles the command to enable or disable a book reader for a media library. - /// - /// The request to be handled. - /// Cancellation token that can be used to stop the execution. - /// - /// An representing either a successful operation, or an error. - /// - public async Task> HandleAsync(SetLibraryBookReaderEnabledCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can configure the book readers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - Result getConfigurationResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); - if (getConfigurationResult.IsFailure) - return getConfigurationResult.Errors; - - LibraryBookReaderConfigurationEntity configuration; - if (getConfigurationResult.Value is not null) - { - configuration = getConfigurationResult.Value; - configuration.IsEnabled = command.IsEnabled; - } - else - { - configuration = new LibraryBookReaderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = command.LibraryId, - PluginId = command.PluginId, - IsEnabled = command.IsEnabled, - CreatedOnUtc = default, - CreatedBy = default, - UpdatedBy = default - }; - } - - Result upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - // The reading service caches the enablement of a reader, because it consults it on every request; the cache is invalidated here, - // so that disabling a reader cuts access to its books immediately, without waiting for the cache to expire. - _enablementCache.Invalidate(command.LibraryId, command.PluginId); - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs deleted file mode 100644 index 1178b5f9..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidator.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Common.Utilities; -using Lumina.Domain.Common.Errors; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Validates the needed validation rules for . -/// -public class SetLibraryBookReaderEnabledCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryBookReaderEnabledCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginId) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs deleted file mode 100644 index c81174c5..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommand.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using System; -#endregion - -namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Command for enabling or disabling a metadata provider for a media library. -/// -/// The Id of the media library whose metadata provider is enabled or disabled. -/// The unique identifier of the plugin providing the metadata. -/// Whether the metadata provider should be enabled for the media library. -public record SetLibraryMetadataProviderEnabledCommand( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs deleted file mode 100644 index 526852b2..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ /dev/null @@ -1,113 +0,0 @@ -#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.Validation; -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.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Handler for the command to enable or disable a metadata provider for a media library. -/// -public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IAuthorizationService _authorizationService; - private readonly ICurrentUserService _currentUserService; - private readonly IValidator _validator; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for authorization related functionality. - /// Injected service to retrieve the current user information. - /// Injected unit of work for interacting with the data access layer repositories. - /// Injected validator for application validation rules. - public SetLibraryMetadataProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) - { - _authorizationService = authorizationService; - _currentUserService = currentUserService; - _unitOfWork = unitOfWork; - _validator = validator; - } - - /// - /// Handles the command to enable or disable a metadata provider for a media library. - /// - /// The request to be handled. - /// Cancellation token that can be used to stop the execution. - /// - /// An representing either a successful operation, or an error. - /// - public async Task> HandleAsync(SetLibraryMetadataProviderEnabledCommand command, CancellationToken cancellationToken) - { - List validationResult = _validator.Validate(command); - if (validationResult.Count > 0) - return validationResult; - - // An authenticated request must always carry a user identity. - Guid? currentUserId = _currentUserService.UserId; - if (currentUserId is null) - return ApplicationErrors.Authorization.NotAuthorized; - Guid userId = currentUserId.Value; - - // Admins can configure the metadata providers of any library; for everyone else, only their own libraries. - bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); - if (!canAccessLibrary) - return ApplicationErrors.Authorization.NotAuthorized; - - // Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated. - Result getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); - if (getConfigurationResult.IsFailure) - return getConfigurationResult.Errors; - - LibraryMetadataProviderConfigurationEntity configuration; - if (getConfigurationResult.Value is not null) - { - // The provider is already configured for the library, so only its enabled state changes, keeping its existing rank in the display order. - configuration = getConfigurationResult.Value; - configuration.IsEnabled = command.IsEnabled; - } - else - { - // Compute the rank to assign to the new configuration, appending it after the existing ones. - Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); - if (getConfigurationsResult.IsFailure) - return getConfigurationsResult.Errors; - int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; - configuration = new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = command.LibraryId, - PluginId = command.PluginId, - IsEnabled = command.IsEnabled, - Rank = nextRank, - CreatedOnUtc = default, - CreatedBy = default, - UpdatedBy = default - }; - } - - // Insert the new configuration, or update the existing one, and persist the change. - Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); - if (upsertResult.IsFailure) - return upsertResult.Errors; - - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - return Result.Success; - } -} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs deleted file mode 100644 index b910702f..00000000 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs +++ /dev/null @@ -1,32 +0,0 @@ -#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.SetLibraryMetadataProviderEnabled; - -/// -/// Validates the needed validation rules for . -/// -public class SetLibraryMetadataProviderEnabledCommandValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryMetadataProviderEnabledCommandValidator() - { - RuleFor(command => command.LibraryId) - .NotEmpty() - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); - - RuleFor(command => command.PluginId) - .NotEmpty() - .WithError(Errors.Plugins.PluginIdCannotBeEmpty) - .Must(id => id != Guid.Empty) - .WithError(Errors.Plugins.PluginIdCannotBeEmpty); - } -} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQuery.cs new file mode 100644 index 00000000..ed2691f7 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Query for getting the artwork providers available for a media library type. +/// +/// The media library type whose available artwork providers are retrieved. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeArtworkProvidersQuery( + string? LibraryType +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandler.cs new file mode 100644 index 00000000..92cfe456 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandler.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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.GetLibraryTypeArtworkProviders; + +/// +/// Handler for the query to get the artwork providers available for a media library type. +/// +public class GetLibraryTypeArtworkProvidersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected store of the provider configurations of the media libraries. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryTypeArtworkProvidersQueryHandler(ICurrentUserService currentUserService, IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _providerConfigurationStore = providerConfigurationStore; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the artwork providers available for a media library type. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryTypeArtworkProvidersQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + if (_currentUserService.UserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + + LibraryType libraryType = Enum.Parse(query.LibraryType!, ignoreCase: true); + + // Build a plugin name lookup from the detected plugins, so that each provider is returned with its display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + // The providers are returned the way a new media library of this type is configured with them: disabled, and ranked in alphabetical order. + IReadOnlyList pluginIds = _providerConfigurationStore.GetSupportedArtworkProviderPluginIds(libraryType); + return pluginIds + .Select((pluginId, index) => new LibraryArtworkProviderResponse(pluginId, pluginNames.GetValueOrDefault(pluginId) ?? string.Empty, IsEnabled: false, Rank: index + 1)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidator.cs new file mode 100644 index 00000000..53f53134 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryTypeArtworkProvidersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersQueryValidator() + { + RuleFor(query => query.LibraryType) + .NotNull() + .WithError(Errors.Library.LibraryTypeCannotBeNull) + .IsInEnum() + .WithError(Errors.Library.UnknownLibraryType); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQuery.cs new file mode 100644 index 00000000..aa64b3e8 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Query for getting the book readers available for a media library type. +/// +/// The media library type whose available book readers are retrieved. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeBookReadersQuery( + string? LibraryType +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandler.cs new file mode 100644 index 00000000..1b6fd722 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandler.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Reading; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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.GetLibraryTypeBookReaders; + +/// +/// Handler for the query to get the book readers available for a media library type. +/// +public class GetLibraryTypeBookReadersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore; + private readonly IBookReaderRegistry _bookReaderRegistry; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected store of the provider configurations of the media libraries. + /// Injected registry of the book readers provided by the loaded plugins. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryTypeBookReadersQueryHandler(ICurrentUserService currentUserService, IMediaLibraryProviderConfigurationStore providerConfigurationStore, IBookReaderRegistry bookReaderRegistry, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _providerConfigurationStore = providerConfigurationStore; + _bookReaderRegistry = bookReaderRegistry; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the book readers available for a media library type. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryTypeBookReadersQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + if (_currentUserService.UserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + + LibraryType libraryType = Enum.Parse(query.LibraryType!, ignoreCase: true); + + // Build a plugin name lookup from the detected plugins, so that each reader is returned with its display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + IReadOnlyDictionary> supportedExtensionsByPluginId = _bookReaderRegistry.GetSupportedExtensionsByPluginId(); + + // The readers are returned the way a new media library of this type is configured with them: disabled, in alphabetical order. + IReadOnlyList pluginIds = _providerConfigurationStore.GetSupportedBookReaderPluginIds(libraryType); + return pluginIds + .Select(pluginId => new LibraryBookReaderResponse( + pluginId, + pluginNames.GetValueOrDefault(pluginId) ?? string.Empty, + supportedExtensionsByPluginId.GetValueOrDefault(pluginId) ?? [], + IsEnabled: false)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidator.cs new file mode 100644 index 00000000..eed752b0 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryTypeBookReadersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersQueryValidator() + { + RuleFor(query => query.LibraryType) + .NotNull() + .WithError(Errors.Library.LibraryTypeCannotBeNull) + .IsInEnum() + .WithError(Errors.Library.UnknownLibraryType); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQuery.cs new file mode 100644 index 00000000..a7e250c2 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQuery.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Query for getting the metadata providers available for a media library type. +/// +/// The media library type whose available metadata providers are retrieved. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeMetadataProvidersQuery( + string? LibraryType +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandler.cs new file mode 100644 index 00000000..3b867d57 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandler.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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.GetLibraryTypeMetadataProviders; + +/// +/// Handler for the query to get the metadata providers available for a media library type. +/// +public class GetLibraryTypeMetadataProvidersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibraryProviderConfigurationStore _providerConfigurationStore; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected store of the provider configurations of the media libraries. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryTypeMetadataProvidersQueryHandler(ICurrentUserService currentUserService, IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator validator) + { + _currentUserService = currentUserService; + _providerConfigurationStore = providerConfigurationStore; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the metadata providers available for a media library type. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryTypeMetadataProvidersQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + if (_currentUserService.UserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + + LibraryType libraryType = Enum.Parse(query.LibraryType!, ignoreCase: true); + + // Build a plugin name lookup from the detected plugins, so that each provider is returned with its display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + // The providers are returned the way a new media library of this type is configured with them: disabled, and ranked in alphabetical order. + IReadOnlyList pluginIds = _providerConfigurationStore.GetSupportedMetadataProviderPluginIds(libraryType); + return pluginIds + .Select((pluginId, index) => new LibraryMetadataProviderResponse(pluginId, pluginNames.GetValueOrDefault(pluginId) ?? string.Empty, IsEnabled: false, Rank: index + 1)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidator.cs new file mode 100644 index 00000000..c727f952 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryTypeMetadataProvidersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersQueryValidator() + { + RuleFor(query => query.LibraryType) + .NotNull() + .WithError(Errors.Library.LibraryTypeCannotBeNull) + .IsInEnum() + .WithError(Errors.Library.UnknownLibraryType); + } +} diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs index 6daf08ed..0a755dd6 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs @@ -11,15 +11,18 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// The type of the media library. Required. /// The file system paths of the directories where the media library elements are located. Required. /// The path of the image file used as the cover for the library. Optional. -/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. -/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. -/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional. -/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. -/// Whether the content of this media library is stored on a solid state drive, in which case the file discovery and content hashing stages read the files in parallel. Optional. +/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Required. +/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Required. +/// Whether this media library should update the metadata of its elements from the web, or not. Required. +/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Required. +/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Required. +/// Whether the content of this media library is stored on a solid state drive, in which case the file discovery and content hashing stages read the files in parallel. Required. /// Whether the consumption progress of the media library items should be tracked, or not. Optional, the default of the library type is used when absent. /// The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the default of the library type is used when absent. /// The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent. +/// The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, every provider supported by the library type is added disabled. +/// The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, every provider supported by the library type is added disabled. +/// The book readers of the media library, and whether each one is enabled. Optional, every reader supported by the library type is added disabled. [DebuggerDisplay("Title: {Title}")] public record AddLibraryRequest( string? Title, @@ -34,5 +37,8 @@ public record AddLibraryRequest( bool IsContentOnSsd, bool? ShouldTrackConsumptionProgress, int? CompletionThresholdPercentage, - LibraryPathTemplatePartRequest[]? PathTemplateParts + LibraryPathTemplatePartRequest?[]? PathTemplateParts, + LibraryProviderSelectionRequest?[]? MetadataProviders, + LibraryProviderSelectionRequest?[]? ArtworkProviders, + LibraryProviderSelectionRequest?[]? BookReaders ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryProviderSelectionRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryProviderSelectionRequest.cs new file mode 100644 index 00000000..26552e4e --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/LibraryProviderSelectionRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.Management; + +/// +/// Represents the choice made for one metadata provider, artwork provider or book reader of a media library. +/// +/// The Id of the plugin providing the metadata provider, artwork provider or book reader. Required. +/// Whether the provider or reader is enabled for the media library. Optional, the stored state is kept when absent, and a provider or reader without a stored state starts disabled. +[DebuggerDisplay("PluginId: {PluginId}; IsEnabled: {IsEnabled}")] +public record LibraryProviderSelectionRequest( + Guid PluginId, + bool? IsEnabled +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs index 9d4377f2..b1183e6f 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs @@ -9,24 +9,25 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// Represents a request to update a media library. /// /// The unique identifier of the media library. Required. -/// The unique identifier of the user owning the media library. Required. /// The title of the media library. Required. /// The type of the media library. Required. /// The file system paths of the directories where the media library elements are located. Required. /// The path of the image file used as the cover for the library. Optional. -/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. -/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. -/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. -/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. -/// Whether the content of this media library is stored on a solid state drive, in which case the file discovery and content hashing stages read the files in parallel. Optional. +/// Whether this media library is enabled or not. A disabled media library is never shown or changed. Required. +/// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Required. +/// Whether this media library should update the metadata of its elements from the web, or not. Required. +/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Required. +/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Required. +/// Whether the content of this media library is stored on a solid state drive, in which case the file discovery and content hashing stages read the files in parallel. Required. /// Whether the consumption progress of the media library items should be tracked, or not. Optional, the stored value is kept when absent. /// The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the stored value is kept when absent. /// The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent. +/// The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes. +/// The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes. +/// The book readers of the media library, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes. [DebuggerDisplay("Title: {Title}")] public record class UpdateLibraryRequest( Guid Id, - Guid UserId, string? Title, string? LibraryType, string[]? ContentLocations, @@ -39,5 +40,8 @@ public record class UpdateLibraryRequest( bool IsContentOnSsd, bool? ShouldTrackConsumptionProgress, int? CompletionThresholdPercentage, - LibraryPathTemplatePartRequest[]? PathTemplateParts + LibraryPathTemplatePartRequest?[]? PathTemplateParts, + LibraryProviderSelectionRequest?[]? MetadataProviders, + LibraryProviderSelectionRequest?[]? ArtworkProviders, + LibraryProviderSelectionRequest?[]? BookReaders ); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeArtworkProvidersRequest.cs new file mode 100644 index 00000000..21c66ce0 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeArtworkProvidersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the artwork providers available for a media library type. +/// +/// The media library type whose available artwork providers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public sealed record GetLibraryTypeArtworkProvidersRequest( + string? LibraryType +); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeBookReadersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeBookReadersRequest.cs new file mode 100644 index 00000000..496af117 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeBookReadersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the book readers available for a media library type. +/// +/// The media library type whose available book readers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public sealed record GetLibraryTypeBookReadersRequest( + string? LibraryType +); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeMetadataProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeMetadataProvidersRequest.cs new file mode 100644 index 00000000..8eff614b --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryTypeMetadataProvidersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the metadata providers available for a media library type. +/// +/// The media library type whose available metadata providers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public sealed record GetLibraryTypeMetadataProvidersRequest( + string? LibraryType +); diff --git a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs deleted file mode 100644 index 0e0f815c..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Plugins; - -/// -/// Represents a request to reorder the artwork providers of a media library. -/// -/// The unique identifier of the media library whose artwork providers are reordered. Required. -/// The plugin Ids in the new order, from highest to lowest rank. Required. -[DebuggerDisplay("LibraryId: {LibraryId}")] -public sealed record ReorderLibraryArtworkProvidersRequest( - Guid LibraryId, - IReadOnlyList PluginIds -); diff --git a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs deleted file mode 100644 index 24b6021e..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Plugins; - -/// -/// Represents a request to reorder the metadata providers of a media library. -/// -/// The Id of the media library whose metadata providers are reordered. Required. -/// The plugin Ids in the new order, from highest to lowest rank. Required. -[DebuggerDisplay("LibraryId: {LibraryId}")] -public sealed record ReorderLibraryMetadataProvidersRequest( - Guid LibraryId, - IReadOnlyList PluginIds -); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs deleted file mode 100644 index bbfb2b95..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Plugins; - -/// -/// Represents a request to enable or disable an artwork provider for a media library. -/// -/// The unique identifier of the media library whose artwork provider is enabled or disabled. Required. -/// The unique identifier of the plugin providing the artwork. Required. -/// Whether the artwork provider should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public sealed record SetLibraryArtworkProviderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs deleted file mode 100644 index 3392ae17..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/SetLibraryBookReaderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Plugins; - -/// -/// Represents a request to enable or disable a book reader for a media library. -/// -/// The Id of the media library whose book reader is enabled or disabled. Required. -/// The unique identifier of the plugin providing the book reader. Required. -/// Whether the book reader should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public sealed record SetLibraryBookReaderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs deleted file mode 100644 index 342ec7b7..00000000 --- a/src/Lumina.Contracts/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Plugins; - -/// -/// Represents a request to enable or disable a metadata provider for a media library. -/// -/// The Id of the media library whose metadata provider is enabled or disabled. Required. -/// The unique identifier of the plugin providing the metadata. Required. -/// Whether the metadata provider should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public sealed record SetLibraryMetadataProviderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs index c9b01c01..a000754a 100644 --- a/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs @@ -5,12 +5,12 @@ using System; namespace Lumina.Contracts.Responses.Plugins; /// -/// Represents an artwork provider configured for a media library. +/// Represents an artwork provider, either as configured for a media library, or as available for a library type, the way a new library of that type starts. /// /// The unique identifier of the plugin providing the artwork. /// The display name of the artwork provider. -/// Whether the artwork provider is enabled for the media library. -/// The rank of the artwork provider, determining the order in which providers are tried. +/// Whether the artwork provider is enabled for the media library. Always for a provider available for a library type, since a new provider starts disabled. +/// The rank of the artwork provider, determining the order in which providers are tried. For a provider available for a library type, it is the rank a new library starts with, in alphabetical order of the plugin names. public sealed record LibraryArtworkProviderResponse( Guid PluginId, string Name, diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs index bb095299..8c2141d7 100644 --- a/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryBookReaderResponse.cs @@ -7,12 +7,12 @@ using System.Diagnostics; namespace Lumina.Contracts.Responses.Plugins; /// -/// Represents a book reader configured for a media library. +/// Represents a book reader, either as configured for a media library, or as available for a library type, the way a new library of that type starts. /// /// The unique identifier of the plugin providing the book reader. /// The display name of the book reader. /// The file extensions supported by the book reader. -/// Whether the book reader is enabled for the media library. +/// Whether the book reader is enabled for the media library. Always for a reader available for a library type, since a new reader starts disabled. [DebuggerDisplay("Name: {Name}")] public sealed record LibraryBookReaderResponse( Guid PluginId, diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs index b47a3b1a..923a5d54 100644 --- a/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryMetadataProviderResponse.cs @@ -5,12 +5,12 @@ using System; namespace Lumina.Contracts.Responses.Plugins; /// -/// Represents a metadata provider configured for a media library. +/// Represents a metadata provider, either as configured for a media library, or as available for a library type, the way a new library of that type starts. /// /// The unique identifier of the plugin providing the metadata. /// The display name of the metadata provider. -/// Whether the metadata provider is enabled for the media library. -/// The rank of the metadata provider, determining the order in which providers are tried. +/// Whether the metadata provider is enabled for the media library. Always for a provider available for a library type, since a new provider starts disabled. +/// The rank of the metadata provider, determining the order in which providers are tried. For a provider available for a library type, it is the rank a new library starts with, in alphabetical order of the plugin names. public sealed record LibraryMetadataProviderResponse( Guid PluginId, string Name, diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs index 89618882..ada861a6 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs @@ -20,7 +20,7 @@ public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfi builder.ToTable("LibraryArtworkProviderConfigurations"); builder.HasKey(configuration => configuration.Id); builder.Property(configuration => configuration.Id) - .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it. .HasColumnOrder(0); builder.Property(configuration => configuration.LibraryId) .IsRequired() @@ -35,7 +35,7 @@ public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfi .IsRequired() .HasColumnOrder(4); - // audit + // Audit. builder.Property(configuration => configuration.CreatedOnUtc) .IsRequired() .HasColumnOrder(5); @@ -52,6 +52,9 @@ public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfi .HasDefaultValue(null) .HasColumnOrder(8); - builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }); + // A media library has at most one artwork provider configuration per plugin, so the pair is unique; the repository upserts on it, and + // the constraint guarantees that two concurrent upserts cannot insert duplicate rows. + builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }) + .IsUnique(); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryMetadataProviderConfigurationConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryMetadataProviderConfigurationConfiguration.cs index 2130ed43..8b167ebb 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryMetadataProviderConfigurationConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryMetadataProviderConfigurationConfiguration.cs @@ -20,7 +20,7 @@ public class LibraryMetadataProviderConfigurationConfiguration : IEntityTypeConf builder.ToTable("LibraryMetadataProviderConfigurations"); builder.HasKey(configuration => configuration.Id); builder.Property(configuration => configuration.Id) - .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it. .HasColumnOrder(0); builder.Property(configuration => configuration.LibraryId) .IsRequired() @@ -35,7 +35,7 @@ public class LibraryMetadataProviderConfigurationConfiguration : IEntityTypeConf .IsRequired() .HasColumnOrder(4); - // audit + // Audit. builder.Property(configuration => configuration.CreatedOnUtc) .IsRequired() .HasColumnOrder(5); @@ -52,6 +52,9 @@ public class LibraryMetadataProviderConfigurationConfiguration : IEntityTypeConf .HasDefaultValue(null) .HasColumnOrder(8); - builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }); + // A media library has at most one metadata provider configuration per plugin, so the pair is unique; the repository upserts on it, and + // the constraint guarantees that two concurrent upserts cannot insert duplicate rows. + builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }) + .IsUnique(); } } diff --git a/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.Designer.cs new file mode 100644 index 00000000..4dce5d66 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.Designer.cs @@ -0,0 +1,3904 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin")] + partial class MakesProviderConfigurationsUniquePerLibraryAndPlugin + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "CreatedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("Favorites", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ConsecutivePagesRead") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(14); + + b.Property("ConsumedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LastActivityOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionKind") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(13); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "StartedOnUtc"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId", "LastActivityOnUtc"); + + b.ToTable("MediaConsumptionRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LastConsumedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastPositionLocation") + .HasMaxLength(4096) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("LastPositionTimeOffsetMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("LastProgressFraction") + .HasColumnType("REAL") + .HasColumnOrder(8); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaKind") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("UserId", "MediaKind", "MediaItemId") + .IsUnique(); + + b.ToTable("MediaResumePoints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CompletionThresholdPercentage") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsContentOnSsd") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(18); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("ShouldTrackConsumptionProgress") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(16); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(28); + + b.Property("VuMeterHighThreshold") + .HasColumnType("REAL") + .HasColumnOrder(23); + + b.Property("VuMeterMediumThreshold") + .HasColumnType("REAL") + .HasColumnOrder(22); + + b.Property("VuMeterOrientation") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("VuMeterPeakHoldDurationInMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("VuMeterPeakReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(27); + + b.Property("VuMeterReleasePerSecond") + .HasColumnType("REAL") + .HasColumnOrder(26); + + b.Property("VuMeterSegmentCount") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("VuMeterSegmentGap") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("VuMeterShowPeak") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaConsumptionRecordEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaConsumption.MediaResumePointEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.cs b/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.cs new file mode 100644 index 00000000..778c777a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261104063504_MakesProviderConfigurationsUniquePerLibraryAndPlugin.cs @@ -0,0 +1,72 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class MakesProviderConfigurationsUniquePerLibraryAndPlugin : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // The upserts read before they add, so two concurrent ones could store the same plugin twice for a library; the duplicates are removed before the + // indexes become unique, keeping the configuration that is tried first, so the unique indexes can be created on an existing database. + migrationBuilder.Sql(""" + DELETE FROM LibraryMetadataProviderConfigurations WHERE rowid NOT IN ( + SELECT rowid FROM ( + SELECT rowid, ROW_NUMBER() OVER (PARTITION BY LibraryId, PluginId ORDER BY Rank, rowid) AS RowNumber + FROM LibraryMetadataProviderConfigurations) + WHERE RowNumber = 1); + + DELETE FROM LibraryArtworkProviderConfigurations WHERE rowid NOT IN ( + SELECT rowid FROM ( + SELECT rowid, ROW_NUMBER() OVER (PARTITION BY LibraryId, PluginId ORDER BY Rank, rowid) AS RowNumber + FROM LibraryArtworkProviderConfigurations) + WHERE RowNumber = 1); + """); + + migrationBuilder.DropIndex( + name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId", + table: "LibraryMetadataProviderConfigurations"); + + migrationBuilder.DropIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations"); + + migrationBuilder.CreateIndex( + name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId", + table: "LibraryMetadataProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId", + table: "LibraryMetadataProviderConfigurations"); + + migrationBuilder.DropIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations"); + + migrationBuilder.CreateIndex( + name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId", + table: "LibraryMetadataProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }); + + migrationBuilder.CreateIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 7bc06864..d1761391 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -2223,7 +2223,8 @@ namespace Lumina.DataAccess.Common.Migrations b.HasKey("Id"); - b.HasIndex("LibraryId", "PluginId"); + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); b.ToTable("LibraryArtworkProviderConfigurations", (string)null); }); @@ -2310,7 +2311,8 @@ namespace Lumina.DataAccess.Common.Migrations b.HasKey("Id"); - b.HasIndex("LibraryId", "PluginId"); + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); b.ToTable("LibraryMetadataProviderConfigurations", (string)null); }); diff --git a/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs b/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs index f79e7cb1..bad24145 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Plugins.cs @@ -15,8 +15,8 @@ public static partial class Errors public static Error PluginIdCannotBeEmpty => Error.Validation(description: nameof(PluginIdCannotBeEmpty)); public static Error PluginSettingsCannotBeNull => Error.Validation(description: nameof(PluginSettingsCannotBeNull)); public static Error LibraryIdCannotBeEmpty => Error.Validation(description: nameof(LibraryIdCannotBeEmpty)); - public static Error PluginIdsListCannotBeNull => Error.Validation(description: nameof(PluginIdsListCannotBeNull)); - public static Error PluginIdsListCannotBeEmpty => Error.Validation(description: nameof(PluginIdsListCannotBeEmpty)); + public static Error PluginIdsMustBeUnique => Error.Validation(description: nameof(PluginIdsMustBeUnique)); + public static Error PluginNotSupportedForLibraryType => Error.Validation(description: nameof(PluginNotSupportedForLibraryType)); public static Error LibraryMetadataProviderConfigurationNotFound => Error.NotFound(description: nameof(LibraryMetadataProviderConfigurationNotFound)); public static Error PluginArchiveCannotBeNull => Error.Validation(description: nameof(PluginArchiveCannotBeNull)); public static Error PluginFileNameCannotBeEmpty => Error.Validation(description: nameof(PluginFileNameCannotBeEmpty)); diff --git a/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs b/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs index f1347aae..debdadd7 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Reading; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Contracts.Core.Metadata; @@ -25,9 +27,10 @@ namespace Lumina.Infrastructure.Core.Plugins; /// The configurations decide, per media library, which loaded plugins may serve metadata or artwork, which book reader opens the /// books of the library, and whether each of them is currently enabled. They are persisted as rows instead of being derived from /// the loaded plugins on the fly, because the user can enable or disable a provider per library, and because the set of loaded -/// plugins can change between restarts. This class is the single place that maintains them, and the only one that knows the -/// difference between "ensure" (only add what is missing) and "reconcile" (make the persisted configurations match the loaded -/// plugins exactly). +/// plugins can change between restarts. This class is the only one that writes them, while the queries, the scan enrichers and the +/// reading service read them through their repositories. It maintains them in three ways: "ensure" only adds what is missing, +/// "reconcile" makes the persisted configurations match the plugins supporting the library type, and "apply" reconciles them +/// and sets the enabled state and the order chosen when the library is added or updated. /// internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProviderConfigurationStore { @@ -63,8 +66,12 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv } /// - /// Adds a disabled provider configuration for every loaded plugin that supports the provided library type and has no configuration yet for the media library identified by . + /// Adds a disabled metadata provider, artwork provider and book reader configuration for every loaded plugin that supports the provided library type and has no configuration yet + /// for the media library identified by . /// + /// + /// The added configurations are only staged until the unit of work is saved, and are not visible to a later ensure, so it must be called at most once per media library before the changes are saved. + /// /// The Id of the media library whose provider configurations are ensured. /// The type of the media library, used to determine the plugins whose providers apply. /// Cancellation token that can be used to stop the execution. @@ -83,28 +90,6 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv return await EnsureBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false); } - /// - /// Replaces the provider configurations of the media library identified by so that they match the plugins supporting the provided library type. - /// - /// The Id of the media library whose provider configurations are reconciled. - /// The type of the media library, used to determine the plugins whose providers apply. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) - { - // "Reconcile" makes the persisted configurations match the loaded plugins exactly: configurations of plugins that no longer support - // the library type are removed, configurations for newly supported plugins are added, and the rest are kept. It is called when a - // plugin is uninstalled or when the type of a library changes. - (IReadOnlyList metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType); - Result reconcileMetadataResult = await ReconcileMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false); - if (reconcileMetadataResult.IsFailure) - return reconcileMetadataResult; - Result reconcileArtworkResult = await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false); - if (reconcileArtworkResult.IsFailure) - return reconcileArtworkResult; - return await ReconcileBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false); - } - /// /// Deletes all the provider configurations of the media library identified by . /// @@ -152,35 +137,63 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv } /// - /// Deletes all the book reader configurations of the media library identified by . + /// Makes the provider and book reader configurations of the media library identified by match the plugins supporting the provided library type, + /// and applies the choices made for them. /// - /// The Id of the media library whose book reader configurations are deleted. + /// + /// A list that is provided reconciles that kind of configuration with the library type and applies the choices: the configurations of the plugins that do not support the library type + /// are removed, even when the list does not name them, every supported plugin gets a configuration, and the list sets the enabled state of every provider or reader it names and, for the + /// metadata and artwork providers, their order. A choice without an enabled state keeps the stored state, the supported plugins the list does not name keep their stored state and are + /// ordered after the named ones, and a plugin without a stored configuration starts disabled. A list that is leaves that kind of configuration untouched, unless + /// is , in which case it is reconciled the same way, without choices. Whenever the book reader configurations are + /// reconciled or chosen, the cached reader enablements of the library are dropped. + /// + /// The Id of the media library whose provider and book reader configurations are configured. + /// The type of the media library, used to determine the plugins whose providers and book readers apply. + /// The choices made for the metadata providers, in the order in which they are tried. + /// The choices made for the artwork providers, in the order in which they are tried. + /// The choices made for the book readers. + /// Whether the kinds of configuration whose list of choices is are reconciled with the library type, which is needed when the + /// library is new or its type changed. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> RemoveBookReaderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + /// An representing either a successful operation, or an error when a choice names a plugin that does not support the library type. + public async Task> ConfigureProvidersAsync( + Guid libraryId, + LibraryType libraryType, + IReadOnlyList? metadataProviders, + IReadOnlyList? artworkProviders, + IReadOnlyList? bookReaders, + bool shouldReconcileOmittedKinds, + CancellationToken cancellationToken) { - Result removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); - if (removeResult.IsFailure) - return removeResult; - // The reader enablements of the deleted library are no longer valid, so the reading service must not serve its books from the cache. + // The configurations are computed in a single pass from the stored state, instead of reconciling first and applying the choices afterwards, + // because the configurations added by a reconcile are only staged until the unit of work is saved, and a second upsert of the same plugin would not find them and would add a duplicate. + (IReadOnlyList metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType); + if (metadataProviders is not null || shouldReconcileOmittedKinds) + { + Result configureMetadataResult = metadataProviders is null + ? await ReconcileMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false) + : await ApplyMetadataProviderSelectionsAsync(libraryId, metadataProviderPluginIds, metadataProviders, cancellationToken).ConfigureAwait(false); + if (configureMetadataResult.IsFailure) + return configureMetadataResult; + } + if (artworkProviders is not null || shouldReconcileOmittedKinds) + { + Result configureArtworkResult = artworkProviders is null + ? await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false) + : await ApplyArtworkProviderSelectionsAsync(libraryId, artworkProviderPluginIds, artworkProviders, cancellationToken).ConfigureAwait(false); + if (configureArtworkResult.IsFailure) + return configureArtworkResult; + } + // Reconciling the book readers drops the cached enablements of the library by itself. + if (bookReaders is null) + return shouldReconcileOmittedKinds ? await ReconcileBookReaderConfigurationsAsync(libraryId, libraryType, cancellationToken).ConfigureAwait(false) : Result.Success; + Result configureBookReadersResult = await ApplyBookReaderSelectionsAsync(libraryId, GetSupportedBookReaderPluginIds(libraryType), bookReaders, cancellationToken).ConfigureAwait(false); + if (configureBookReadersResult.IsFailure) + return configureBookReadersResult; + // The reading service caches the enablement of the readers, so the cached state of the library is dropped, and a reader that was disabled stops serving its books immediately. _enablementCache.InvalidateLibrary(libraryId); - return removeResult; - } - - /// - /// Deletes all the book reader configurations referencing the plugin identified by . - /// - /// The Id of the plugin whose book reader configurations are deleted. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> RemoveBookReaderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken) - { - Result removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false); - if (removeResult.IsFailure) - return removeResult; - // The reader enablements of the removed plugin are no longer valid, so the reading service must not serve its books from the cache. - _enablementCache.InvalidatePlugin(pluginId); - return removeResult; + return Result.Success; } /// @@ -205,12 +218,32 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv return (metadataProviderPluginIds, artworkProviderPluginIds); } + /// + /// Gets the Ids of the loaded plugins that provide metadata for the provided library type, ordered alphabetically by plugin name. + /// + /// The type of the media library the metadata providers must support. + /// The Ids of the plugins providing metadata for the library type. + public IReadOnlyList GetSupportedMetadataProviderPluginIds(LibraryType libraryType) + { + return GetSupportedProviderPluginIds(libraryType).metadataProviderPluginIds; + } + + /// + /// Gets the Ids of the loaded plugins that provide artwork for the provided library type, ordered alphabetically by plugin name. + /// + /// The type of the media library the artwork providers must support. + /// The Ids of the plugins providing artwork for the library type. + public IReadOnlyList GetSupportedArtworkProviderPluginIds(LibraryType libraryType) + { + return GetSupportedProviderPluginIds(libraryType).artworkProviderPluginIds; + } + /// /// Gets the Ids of the loaded plugins that provide a book reader for the provided library type, ordered alphabetically by plugin name so that the assigned order is stable. /// /// The type of the media library the book readers must support. /// The Ids of the plugins providing a book reader for the library type. - private IReadOnlyList GetSupportedBookReaderPluginIds(LibraryType libraryType) + public IReadOnlyList GetSupportedBookReaderPluginIds(LibraryType libraryType) { // Book readers have no rank: a book is opened by exactly one reader matched by its file extension, not by priority, so the alphabetical order is only used to keep the display order stable. List bookReaderPluginIds = []; @@ -224,11 +257,14 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv /// /// Replaces the book reader configurations of the media library identified by so that they match the plugins supporting the provided library type. /// + /// + /// The cached reader enablements of the library are dropped, so a reader whose configuration was removed stops serving its books immediately. + /// /// The Id of the media library whose book reader configurations are reconciled. /// The type of the media library, used to determine the plugins whose book readers apply. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async Task> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) + private async Task> ReconcileBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) { // First, the configurations of readers that no longer apply are deleted, then a disabled configuration is added for every reader // that applies, but is not configured yet; the configurations of readers that still apply are kept untouched. @@ -267,6 +303,8 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv if (upsertResult.IsFailure) return Result.Failure(upsertResult.Errors); } + // The reading service caches the enablement of the readers, so the cached state of the library is dropped, and a reader whose configuration was removed stops serving its books immediately. + _enablementCache.InvalidateLibrary(libraryId); return Result.Success; } @@ -277,7 +315,7 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv /// The type of the media library, used to determine the plugins whose book readers apply. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async Task> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) + private async Task> EnsureBookReaderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) { // Unlike reconcile, ensure never deletes: it only adds a disabled configuration for the readers that are not configured yet. IReadOnlyList bookReaderPluginIds = GetSupportedBookReaderPluginIds(libraryType); @@ -499,4 +537,193 @@ internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProv } return Result.Success; } + + /// + /// Makes the metadata provider configurations of the media library match the plugins supporting its type, and applies the provided choices. + /// + /// The Id of the media library whose metadata provider configurations are configured. + /// The Ids of the plugins providing metadata for the library type, in alphabetical order. + /// The choices made for the metadata providers, in the order in which they are tried. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ApplyMetadataProviderSelectionsAsync(Guid libraryId, IReadOnlyList metadataProviderPluginIds, IReadOnlyList selections, CancellationToken cancellationToken) + { + // The command validation rejects duplicated choices already, and they are reported here too, so that a direct caller gets an error instead of an exception. + if (selections.Select(selection => selection.PluginId).Distinct().Count() != selections.Count) + return Errors.Plugins.PluginIdsMustBeUnique; + if (selections.Any(selection => !metadataProviderPluginIds.Contains(selection.PluginId))) + return Errors.Plugins.PluginNotSupportedForLibraryType; + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + List stalePluginIds = [.. getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !metadataProviderPluginIds.Contains(pluginId))]; + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + Dictionary configurationsByPluginId = getConfigurationsResult.Value + .Where(configuration => metadataProviderPluginIds.Contains(configuration.PluginId)) + .ToDictionary(configuration => configuration.PluginId); + IReadOnlyList orderedPluginIds = GetProviderOrder(selections, configurationsByPluginId.Values.OrderBy(configuration => configuration.Rank).Select(configuration => configuration.PluginId), metadataProviderPluginIds); + Dictionary enabledStatesByPluginId = selections.ToDictionary(selection => selection.PluginId, selection => selection.IsEnabled); + for (int index = 0; index < orderedPluginIds.Count; index++) + { + Guid pluginId = orderedPluginIds[index]; + configurationsByPluginId.TryGetValue(pluginId, out LibraryMetadataProviderConfigurationEntity? storedConfiguration); + // A provider that is not named, or is named without an enabled state, keeps its stored state, and a provider that has no configuration yet starts disabled, so it never silently starts enriching the library. + bool isEnabled = enabledStatesByPluginId.GetValueOrDefault(pluginId) ?? storedConfiguration?.IsEnabled ?? false; + LibraryMetadataProviderConfigurationEntity configuration = storedConfiguration ?? new LibraryMetadataProviderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = isEnabled, + Rank = index + 1, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + configuration.IsEnabled = isEnabled; + configuration.Rank = index + 1; + Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + } + return Result.Success; + } + + /// + /// Makes the artwork provider configurations of the media library match the plugins supporting its type, and applies the provided choices. + /// + /// The Id of the media library whose artwork provider configurations are configured. + /// The Ids of the plugins providing artwork for the library type, in alphabetical order. + /// The choices made for the artwork providers, in the order in which they are tried. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ApplyArtworkProviderSelectionsAsync(Guid libraryId, IReadOnlyList artworkProviderPluginIds, IReadOnlyList selections, CancellationToken cancellationToken) + { + // The command validation rejects duplicated choices already, and they are reported here too, so that a direct caller gets an error instead of an exception. + if (selections.Select(selection => selection.PluginId).Distinct().Count() != selections.Count) + return Errors.Plugins.PluginIdsMustBeUnique; + if (selections.Any(selection => !artworkProviderPluginIds.Contains(selection.PluginId))) + return Errors.Plugins.PluginNotSupportedForLibraryType; + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + List stalePluginIds = [.. getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !artworkProviderPluginIds.Contains(pluginId))]; + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + Dictionary configurationsByPluginId = getConfigurationsResult.Value + .Where(configuration => artworkProviderPluginIds.Contains(configuration.PluginId)) + .ToDictionary(configuration => configuration.PluginId); + IReadOnlyList orderedPluginIds = GetProviderOrder(selections, configurationsByPluginId.Values.OrderBy(configuration => configuration.Rank).Select(configuration => configuration.PluginId), artworkProviderPluginIds); + Dictionary enabledStatesByPluginId = selections.ToDictionary(selection => selection.PluginId, selection => selection.IsEnabled); + for (int index = 0; index < orderedPluginIds.Count; index++) + { + Guid pluginId = orderedPluginIds[index]; + configurationsByPluginId.TryGetValue(pluginId, out LibraryArtworkProviderConfigurationEntity? storedConfiguration); + // A provider that is not named, or is named without an enabled state, keeps its stored state, and a provider that has no configuration yet starts disabled, so it never silently starts enriching the library. + bool isEnabled = enabledStatesByPluginId.GetValueOrDefault(pluginId) ?? storedConfiguration?.IsEnabled ?? false; + LibraryArtworkProviderConfigurationEntity configuration = storedConfiguration ?? new LibraryArtworkProviderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = isEnabled, + Rank = index + 1, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + configuration.IsEnabled = isEnabled; + configuration.Rank = index + 1; + Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + } + return Result.Success; + } + + /// + /// Makes the book reader configurations of the media library match the plugins supporting its type, and applies the provided choices. + /// + /// The Id of the media library whose book reader configurations are configured. + /// The Ids of the plugins providing a book reader for the library type. + /// The choices made for the book readers. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ApplyBookReaderSelectionsAsync(Guid libraryId, IReadOnlyList bookReaderPluginIds, IReadOnlyList selections, CancellationToken cancellationToken) + { + // The command validation rejects duplicated choices already, and they are reported here too, so that a direct caller gets an error instead of an exception. + if (selections.Select(selection => selection.PluginId).Distinct().Count() != selections.Count) + return Errors.Plugins.PluginIdsMustBeUnique; + if (selections.Any(selection => !bookReaderPluginIds.Contains(selection.PluginId))) + return Errors.Plugins.PluginNotSupportedForLibraryType; + Result> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + List stalePluginIds = [.. getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !bookReaderPluginIds.Contains(pluginId))]; + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + Dictionary configurationsByPluginId = getConfigurationsResult.Value + .Where(configuration => bookReaderPluginIds.Contains(configuration.PluginId)) + .ToDictionary(configuration => configuration.PluginId); + Dictionary enabledStatesByPluginId = selections.ToDictionary(selection => selection.PluginId, selection => selection.IsEnabled); + // Book readers have no rank, since a book is opened by the reader matched by its file extension, so only their enabled state is applied. + foreach (Guid pluginId in bookReaderPluginIds) + { + configurationsByPluginId.TryGetValue(pluginId, out LibraryBookReaderConfigurationEntity? storedConfiguration); + // A reader that is not named, or is named without an enabled state, keeps its stored state, and a reader that has no configuration yet starts disabled, so it never silently takes over reading the books of the library. + bool isEnabled = enabledStatesByPluginId.GetValueOrDefault(pluginId) ?? storedConfiguration?.IsEnabled ?? false; + LibraryBookReaderConfigurationEntity configuration = storedConfiguration ?? new LibraryBookReaderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = isEnabled, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + configuration.IsEnabled = isEnabled; + Result upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + } + return Result.Success; + } + + /// + /// Gets the order in which the supported providers of a media library are tried: the named providers in the order of the choices, then the providers that are already configured, + /// in their stored order, then the providers that are not configured yet, in alphabetical order. + /// + /// The choices made for the providers, in the order in which they are tried. + /// The Ids of the plugins whose providers are already configured and still supported, in their stored order. + /// The Ids of the plugins providing for the library type, in alphabetical order. + /// The Ids of the plugins, in the order in which their providers are tried. + private static IReadOnlyList GetProviderOrder(IReadOnlyList selections, IEnumerable configuredPluginIds, IReadOnlyList supportedPluginIds) + { + List orderedPluginIds = [.. selections.Select(selection => selection.PluginId)]; + HashSet orderedPluginIdSet = [.. orderedPluginIds]; + foreach (Guid pluginId in configuredPluginIds.Concat(supportedPluginIds)) + if (orderedPluginIdSet.Add(pluginId)) + orderedPluginIds.Add(pluginId); + return orderedPluginIds; + } } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index c31213fa..e7f94809 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -129,7 +129,9 @@ internal sealed class PluginDetectionSyncJob : BackgroundService } } - // Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type. + // Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata, artwork or a book reader for its type. + // A single ensure covers all three kinds, because the configurations it adds are only staged until the unit of work is saved, and a second ensure in the + // same scope would not find them and would add duplicates that break the unique index on save. Result> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(cancellationToken: stoppingToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) _logger.LogError("Failed to get the media libraries while seeding the provider configurations."); @@ -140,9 +142,6 @@ internal sealed class PluginDetectionSyncJob : BackgroundService Result ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false); if (ensureResult.IsFailure) _logger.LogError("Failed to seed the provider configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureResult.FirstError.Description); - Result ensureBookReadersResult = await providerConfigurationStore.EnsureBookReaderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false); - if (ensureBookReadersResult.IsFailure) - _logger.LogError("Failed to seed the book reader configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureBookReadersResult.FirstError.Description); } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index 2f6fd0de..5a0d88dc 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -23,13 +23,11 @@ public static partial class ApiRoutes public const string CANCEL_LIBRARIES_SCAN = "/libraries/scans/cancel"; public const string CANCEL_LIBRARY_SCAN = "/libraries/{libraryId}/scans/{scanId}/cancel"; public const string GET_LIBRARY_METADATA_PROVIDERS = "/libraries/{libraryId}/metadata-providers"; - public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "/libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; - public const string REORDER_LIBRARY_METADATA_PROVIDERS = "/libraries/{libraryId}/metadata-providers/reorder"; public const string GET_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers"; - public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "/libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; - public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers/reorder"; public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "/libraries/path-template-parts/{libraryType}"; public const string GET_LIBRARY_BOOK_READERS = "/libraries/{libraryId}/book-readers"; - public const string SET_LIBRARY_BOOK_READER_ENABLED = "/libraries/{libraryId}/book-readers/{pluginId}/enabled"; + public const string GET_LIBRARY_TYPE_METADATA_PROVIDERS = "/libraries/metadata-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_ARTWORK_PROVIDERS = "/libraries/artwork-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_BOOK_READERS = "/libraries/book-readers/{libraryType}"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs index a2e8a6f0..2dfa66f7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -40,7 +40,10 @@ public class AddLibraryEndpointSummary : Summary r.Title, "The title of the media library. Required."); @@ -56,6 +59,9 @@ public class AddLibraryEndpointSummary : Summary r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items should be tracked, or not. Optional, the default of the library type is used when absent."); RequestParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the default of the library type is used when absent."); RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); + RequestParam(r => r.MetadataProviders, "The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, every provider supported by the library type is added disabled when absent."); + RequestParam(r => r.ArtworkProviders, "The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, every provider supported by the library type is added disabled when absent."); + RequestParam(r => r.BookReaders, "The book readers of the media library, and whether each one is enabled. Optional, every reader supported by the library type is added disabled when absent."); ResponseParam(r => r.Id, "The unique identifier of the entity."); ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); @@ -172,7 +178,10 @@ public class AddLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library. Required."); - RequestParam(r => r.UserId, "The unique identifier of the user owning the media library. Required."); RequestParam(r => r.Title, "The title of the media library. Required."); RequestParam(r => r.LibraryType, "The type of the media library. Required."); RequestParam(r => r.ContentLocations, ">The file system paths of the directories where the media library elements are located. Required."); @@ -60,6 +61,9 @@ public class UpdateLibraryEndpointSummary : Summary r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items should be tracked, or not. Optional, the stored value is kept when absent."); RequestParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the stored value is kept when absent."); RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); + RequestParam(r => r.MetadataProviders, "The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes when absent."); + RequestParam(r => r.ArtworkProviders, "The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes when absent."); + RequestParam(r => r.BookReaders, "The book readers of the media library, and whether each one is enabled. Optional, the stored configurations are kept, or reconciled with the library type when it changes when absent."); ResponseParam(r => r.Id, "The unique identifier of the entity."); ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); @@ -130,7 +134,7 @@ public class UpdateLibraryEndpointSummary : Summary +/// API endpoint for the /libraries/artwork-providers/{libraryType} route. +/// +public class GetLibraryTypeArtworkProvidersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryTypeArtworkProvidersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library type artwork providers queries. + public GetLibraryTypeArtworkProvidersEndpoint(IQueryHandler>> getLibraryTypeArtworkProvidersQueryHandler) + { + _getLibraryTypeArtworkProvidersQueryHandler = getLibraryTypeArtworkProvidersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the artwork providers available for the media library type provided in . + /// + /// The request containing the media library type whose available artwork providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeArtworkProvidersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryTypeArtworkProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs new file mode 100644 index 00000000..583e08c6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersEndpointSummary() + { + Summary = "Retrieves the artwork providers available for a media library type."; + Description = "Retrieves the artwork providers of the loaded plugins that support a media library type, in the state a new media library of that type starts with: disabled, and ranked in alphabetical order."; + + ExampleRequest = new GetLibraryTypeArtworkProvidersRequest( + LibraryType: "Book" + ); + + RequestParam(r => r.LibraryType, "The media library type whose available artwork providers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork."); + ResponseParam(r => r.Name, "The display name of the artwork provider."); + ResponseParam(r => r.IsEnabled, "Whether the artwork provider is enabled. Always false, since no media library is involved."); + ResponseParam(r => r.Rank, "The rank of the artwork provider, determining the order in which providers are tried."); + + Response(200, "The artwork providers available for the media library type are returned.", + example: new LibraryArtworkProviderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "Goodreads", + IsEnabled: false, + Rank: 1 + ), + new( + PluginId: Guid.NewGuid(), + Name: "OpenLibrary", + IsEnabled: false, + Rank: 2 + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/libraries/artwork-providers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/libraries/artwork-providers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/artwork-providers/{libraryType}" + } + } + ); + + Response(403, "The request failed because the request carries no user identity.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/artwork-providers/{libraryType}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/artwork-providers/{libraryType}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryTypeCannotBeNull", + "UnknownLibraryType" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs new file mode 100644 index 00000000..d4b290f3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// API endpoint for the /libraries/book-readers/{libraryType} route. +/// +public class GetLibraryTypeBookReadersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryTypeBookReadersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library type book readers queries. + public GetLibraryTypeBookReadersEndpoint(IQueryHandler>> getLibraryTypeBookReadersQueryHandler) + { + _getLibraryTypeBookReadersQueryHandler = getLibraryTypeBookReadersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the book readers available for the media library type provided in . + /// + /// The request containing the media library type whose available book readers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeBookReadersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryTypeBookReadersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs new file mode 100644 index 00000000..05f2fb0a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersEndpointSummary() + { + Summary = "Retrieves the book readers available for a media library type."; + Description = "Retrieves the book readers of the loaded plugins that support a media library type, with their supported file extensions, in the state a new media library of that type starts with: disabled, in alphabetical order."; + + ExampleRequest = new GetLibraryTypeBookReadersRequest( + LibraryType: "Book" + ); + + RequestParam(r => r.LibraryType, "The media library type whose available book readers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader."); + ResponseParam(r => r.Name, "The display name of the book reader."); + ResponseParam(r => r.SupportedExtensions, "The file extensions supported by the book reader."); + ResponseParam(r => r.IsEnabled, "Whether the book reader is enabled. Always false, since no media library is involved."); + + Response(200, "The book readers available for the media library type are returned.", + example: new LibraryBookReaderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "EPUB Reader", + SupportedExtensions: [".epub"], + IsEnabled: false + ), + new( + PluginId: Guid.NewGuid(), + Name: "PDF Reader", + SupportedExtensions: [".pdf"], + IsEnabled: false + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/libraries/book-readers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/libraries/book-readers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/book-readers/{libraryType}" + } + } + ); + + Response(403, "The request failed because the request carries no user identity.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/book-readers/{libraryType}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/book-readers/{libraryType}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryTypeCannotBeNull", + "UnknownLibraryType" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs new file mode 100644 index 00000000..7cd472a5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// API endpoint for the /libraries/metadata-providers/{libraryType} route. +/// +public class GetLibraryTypeMetadataProvidersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryTypeMetadataProvidersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library type metadata providers queries. + public GetLibraryTypeMetadataProvidersEndpoint(IQueryHandler>> getLibraryTypeMetadataProvidersQueryHandler) + { + _getLibraryTypeMetadataProvidersQueryHandler = getLibraryTypeMetadataProvidersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the metadata providers available for the media library type provided in . + /// + /// The request containing the media library type whose available metadata providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeMetadataProvidersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryTypeMetadataProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs new file mode 100644 index 00000000..a0d27f55 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersEndpointSummary() + { + Summary = "Retrieves the metadata providers available for a media library type."; + Description = "Retrieves the metadata providers of the loaded plugins that support a media library type, in the state a new media library of that type starts with: disabled, and ranked in alphabetical order."; + + ExampleRequest = new GetLibraryTypeMetadataProvidersRequest( + LibraryType: "Book" + ); + + RequestParam(r => r.LibraryType, "The media library type whose available metadata providers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the metadata."); + ResponseParam(r => r.Name, "The display name of the metadata provider."); + ResponseParam(r => r.IsEnabled, "Whether the metadata provider is enabled. Always false, since no media library is involved."); + ResponseParam(r => r.Rank, "The rank of the metadata provider, determining the order in which providers are tried."); + + Response(200, "The metadata providers available for the media library type are returned.", + example: new LibraryMetadataProviderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "Goodreads", + IsEnabled: false, + Rank: 1 + ), + new( + PluginId: Guid.NewGuid(), + Name: "OpenLibrary", + IsEnabled: false, + Rank: 2 + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = "/api/v1/libraries/metadata-providers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/libraries/metadata-providers/{libraryType}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/metadata-providers/{libraryType}" + } + } + ); + + Response(403, "The request failed because the request carries no user identity.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/metadata-providers/{libraryType}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/metadata-providers/{libraryType}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryTypeCannotBeNull", + "UnknownLibraryType" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs deleted file mode 100644 index 57e492af..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// API endpoint for the /libraries/{libraryId}/artwork-providers/reorder route. -/// -public class ReorderLibraryArtworkProvidersEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _reorderLibraryArtworkProvidersCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling reorder library artwork providers commands. - public ReorderLibraryArtworkProvidersEndpoint(ICommandHandler> reorderLibraryArtworkProvidersCommandHandler) - { - _reorderLibraryArtworkProvidersCommandHandler = reorderLibraryArtworkProvidersCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.Http.PUT); - Routes(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS); - Version(1); - DontCatchExceptions(); - } - - /// - /// Reorders the artwork providers of the media library identified by . - /// - /// The request containing the Id of the media library and the plugin Ids in the new order. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken) - { - Result result = await _reorderLibraryArtworkProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs deleted file mode 100644 index 72d7e799..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs +++ /dev/null @@ -1,116 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryArtworkProvidersEndpointSummary() - { - Summary = "Reorders the artwork providers of a media library."; - Description = "Reorders the artwork providers of a media library, determining the order in which the providers are tried during the artwork enrichment of the library scans."; - - ExampleRequest = new ReorderLibraryArtworkProvidersRequest( - LibraryId: Guid.NewGuid(), - PluginIds: - [ - Guid.NewGuid(), - Guid.NewGuid() - ] - ); - - RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required."); - RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); - - Response(200, "The artwork providers of the media library were successfully reordered."); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Authentication failed", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token has expired", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" - } - } - ); - - Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "NotAuthorized", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", - title = "General.NotFound", - status = 404, - detail = "LibraryNotFound", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", - traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "LibraryIdCannotBeEmpty", - "PluginIdsListCannotBeNull", - "PluginIdsListCannotBeEmpty" - } - } - }, - traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs deleted file mode 100644 index c07e7016..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// API endpoint for the /libraries/{libraryId}/metadata-providers/reorder route. -/// -public class ReorderLibraryMetadataProvidersEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _reorderLibraryMetadataProvidersCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling reorder library metadata providers commands. - public ReorderLibraryMetadataProvidersEndpoint(ICommandHandler> reorderLibraryMetadataProvidersCommandHandler) - { - _reorderLibraryMetadataProvidersCommandHandler = reorderLibraryMetadataProvidersCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.Http.PUT); - Routes(ApiRoutes.Libraries.REORDER_LIBRARY_METADATA_PROVIDERS); - Version(1); - DontCatchExceptions(); - } - - /// - /// Reorders the metadata providers of the media library identified by . - /// - /// The request containing the Id of the media library and the plugin Ids in the new order. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(ReorderLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) - { - Result result = await _reorderLibraryMetadataProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointSummary.cs deleted file mode 100644 index de2e24a1..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointSummary.cs +++ /dev/null @@ -1,116 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryMetadataProvidersEndpointSummary() - { - Summary = "Reorders the metadata providers of a media library."; - Description = "Reorders the metadata providers of a media library, determining the order in which the providers are tried during the metadata enrichment of the library scans."; - - ExampleRequest = new ReorderLibraryMetadataProvidersRequest( - LibraryId: Guid.NewGuid(), - PluginIds: - [ - Guid.NewGuid(), - Guid.NewGuid() - ] - ); - - RequestParam(r => r.LibraryId, "The Id of the media library whose metadata providers are reordered. Required."); - RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); - - Response(200, "The metadata providers of the media library were successfully reordered."); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Authentication failed", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token has expired", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder" - } - } - ); - - Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "NotAuthorized", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", - title = "General.NotFound", - status = 404, - detail = "LibraryNotFound", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder", - traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/reorder", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "LibraryIdCannotBeEmpty", - "PluginIdsListCannotBeNull", - "PluginIdsListCannotBeEmpty" - } - } - }, - traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs deleted file mode 100644 index b525dac5..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// API endpoint for the /libraries/{libraryId}/artwork-providers/{pluginId}/enabled route. -/// -public class SetLibraryArtworkProviderEnabledEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _setLibraryArtworkProviderEnabledCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling set library artwork provider enabled commands. - public SetLibraryArtworkProviderEnabledEndpoint(ICommandHandler> setLibraryArtworkProviderEnabledCommandHandler) - { - _setLibraryArtworkProviderEnabledCommandHandler = setLibraryArtworkProviderEnabledCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.Http.PUT); - Routes(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED); - Version(1); - DontCatchExceptions(); - } - - /// - /// Enables or disables the artwork provider identified by for the media library. - /// - /// The request containing the Ids of the media library and of the artwork provider. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken) - { - Result result = await _setLibraryArtworkProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs deleted file mode 100644 index 25100d34..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs +++ /dev/null @@ -1,113 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryArtworkProviderEnabledEndpointSummary() - { - Summary = "Enables or disables an artwork provider for a media library."; - Description = "Enables or disables the artwork provider for the media library, so that it is included or excluded from the artwork enrichment of the library scans."; - - ExampleRequest = new SetLibraryArtworkProviderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - RequestParam(r => r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required."); - RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library. Required."); - - Response(200, "The artwork provider was successfully enabled or disabled for the media library."); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Authentication failed", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token has expired", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" - } - } - ); - - Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "NotAuthorized", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", - title = "General.NotFound", - status = 404, - detail = "LibraryNotFound", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", - traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "LibraryIdCannotBeEmpty", - "PluginIdCannotBeEmpty" - } - } - }, - traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs deleted file mode 100644 index 3ec20be4..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// API endpoint for the /libraries/{libraryId}/book-readers/{pluginId}/enabled route. -/// -public class SetLibraryBookReaderEnabledEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _setLibraryBookReaderEnabledCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling set library book reader enabled commands. - public SetLibraryBookReaderEnabledEndpoint(ICommandHandler> setLibraryBookReaderEnabledCommandHandler) - { - _setLibraryBookReaderEnabledCommandHandler = setLibraryBookReaderEnabledCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.Http.PUT); - Routes(ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED); - Version(1); - DontCatchExceptions(); - } - - /// - /// Enables or disables the book reader identified by for the media library. - /// - /// The request containing the Ids of the media library and of the book reader. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryBookReaderEnabledRequest request, CancellationToken cancellationToken) - { - Result result = await _setLibraryBookReaderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs deleted file mode 100644 index dc5f8742..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointSummary.cs +++ /dev/null @@ -1,118 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryBookReaderEnabledEndpointSummary() - { - Summary = "Enables or disables a book reader for a media library."; - Description = "Enables or disables the book reader of the media library identified by the request."; - - ExampleRequest = new SetLibraryBookReaderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - RequestParam(r => r.LibraryId, "The Id of the media library whose book reader is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader. Required."); - RequestParam(r => r.IsEnabled, "Whether the book reader should be enabled for the media library. Required."); - - Response(200, "The book reader of the media library is enabled or disabled.", - example: new - { - success = true - } - ); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Authentication failed", - instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token has expired", - instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled" - } - } - ); - - Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "NotAuthorized", - instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", - title = "General.NotFound", - status = 404, - detail = "LibraryNotFound", - instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", - traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "LibraryIdCannotBeEmpty", - "PluginIdCannotBeEmpty" - } - } - }, - traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs deleted file mode 100644 index d3d490e3..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Common.Routes.Library.Management; -using Lumina.Presentation.Api.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// API endpoint for the /libraries/{libraryId}/metadata-providers/{pluginId}/enabled route. -/// -public class SetLibraryMetadataProviderEnabledEndpoint : BaseEndpoint -{ - private readonly ICommandHandler> _setLibraryMetadataProviderEnabledCommandHandler; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for handling set library metadata provider enabled commands. - public SetLibraryMetadataProviderEnabledEndpoint(ICommandHandler> setLibraryMetadataProviderEnabledCommandHandler) - { - _setLibraryMetadataProviderEnabledCommandHandler = setLibraryMetadataProviderEnabledCommandHandler; - } - - /// - /// Configures the API endpoint. - /// - public override void Configure() - { - Verbs(FastEndpoints.Http.PUT); - Routes(ApiRoutes.Libraries.SET_LIBRARY_METADATA_PROVIDER_ENABLED); - Version(1); - DontCatchExceptions(); - } - - /// - /// Enables or disables the metadata provider identified by for the media library. - /// - /// The request containing the Ids of the media library and of the metadata provider. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryMetadataProviderEnabledRequest request, CancellationToken cancellationToken) - { - Result result = await _setLibraryMetadataProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); - } -} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointSummary.cs deleted file mode 100644 index 8097bb2a..00000000 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointSummary.cs +++ /dev/null @@ -1,113 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// Class used for providing a textual description for the API endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetLibraryMetadataProviderEnabledEndpointSummary() - { - Summary = "Enables or disables a metadata provider for a media library."; - Description = "Enables or disables the metadata provider for the media library, so that it is included or excluded from the metadata enrichment of the library scans."; - - ExampleRequest = new SetLibraryMetadataProviderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - RequestParam(r => r.LibraryId, "The Id of the media library whose metadata provider is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the metadata. Required."); - RequestParam(r => r.IsEnabled, "Whether the metadata provider should be enabled for the media library. Required."); - - Response(200, "The metadata provider was successfully enabled or disabled for the media library."); - - Response(401, "Authentication required.", "application/problem+json", - example: new[] - { - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "Authentication failed", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token has expired", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled" - }, - new - { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "The token is invalid", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled" - } - } - ); - - Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", - title = "General.Failure", - status = 403, - detail = "NotAuthorized", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", - traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" - } - ); - - Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", - title = "General.NotFound", - status = 404, - detail = "LibraryNotFound", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", - traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" - } - ); - - Response(422, "The request did not pass validation checks.", "application/problem+json", - example: new - { - type = "https://tools.ietf.org/html/rfc4918#section-11.2", - title = "General.Validation", - status = 422, - detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", - errors = new Dictionary - { - { - "General.Validation", new[] - { - "LibraryIdCannotBeEmpty", - "PluginIdCannotBeEmpty" - } - } - }, - traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" - } - ); - } -} diff --git a/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs b/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs index ce4b912b..70fef020 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/PermissionAuthorizationHandler.cs @@ -24,12 +24,18 @@ public class PermissionAuthorizationHandler : AuthorizationHandler - /// Succeeds the requirement when the currently logged in user holds any of the required permissions. + /// Succeeds the requirement when the currently logged in user is an administrator, or holds any of the required permissions. /// /// The authorization context. /// The permission requirement to evaluate. protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, PermissionRequirement permissionRequirement) { + // The API lets administrators do what the permission allows even when they do not hold it, so the Web does not deny them what the API grants. + if (await _authorizationService.IsInRoleAsync("Admin", CancellationToken.None).ConfigureAwait(false)) + { + authorizationHandlerContext.Succeed(permissionRequirement); + return; + } foreach (AuthorizationPermission permission in permissionRequirement.Permissions) { if (await _authorizationService.HasPermissionAsync(permission, CancellationToken.None).ConfigureAwait(false)) diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibrariesIndexPageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibrariesIndexPageDto.cs new file mode 100644 index 00000000..1caafe30 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibrariesIndexPageDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Libraries; + +/// +/// Data transfer object for the data of the media libraries management page. +/// +/// Whether the current user can change and delete their media libraries, which takes the permission to manage media libraries, or the administrator role. +[DebuggerDisplay("CanManageLibraries: {CanManageLibraries}")] +public sealed record LibrariesIndexPageDto( + bool CanManageLibraries +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs index fcb59abc..d33e13db 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs @@ -17,11 +17,6 @@ public class LibraryDto /// public Guid? Id { get; set; } - /// - /// Gets or sets the unique identifier of the user owning the media library. - /// - public Guid? UserId { get; set; } - /// /// Gets or sets the title of the library. /// @@ -88,4 +83,22 @@ public class LibraryDto /// Gets or sets the ordered parts of the template describing the structure of the media library on disk. /// public List PathTemplateParts { get; set; } = []; + + /// + /// Gets or sets the metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, the providers are configured + /// with their defaults on create, and on update the stored configurations are kept, or reconciled with the library type when it changes. + /// + public List? MetadataProviders { get; set; } + + /// + /// Gets or sets the artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. When absent, the providers are configured + /// with their defaults on create, and on update the stored configurations are kept, or reconciled with the library type when it changes. + /// + public List? ArtworkProviders { get; set; } + + /// + /// Gets or sets the book readers of the media library, and whether each one is enabled. When absent, the readers are configured with their defaults on create, and on update + /// the stored configurations are kept, or reconciled with the library type when it changes. + /// + public List? BookReaders { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryProviderSelectionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryProviderSelectionDto.cs new file mode 100644 index 00000000..e8836574 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryProviderSelectionDto.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Libraries; + +/// +/// Data transfer object for the choice made for one metadata provider, artwork provider or book reader of a media library. +/// +[DebuggerDisplay("PluginId: {PluginId}; IsEnabled: {IsEnabled}")] +public class LibraryProviderSelectionDto +{ + /// + /// Gets or sets the unique identifier of the plugin providing the metadata provider, artwork provider or book reader. + /// + public Guid PluginId { get; set; } + + /// + /// Gets or sets whether the provider or reader is enabled for the media library. Optional, the stored state is kept when absent, and a provider or reader without a stored state starts disabled. + /// + public bool? IsEnabled { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequest.cs new file mode 100644 index 00000000..f905852b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request for retrieving the artwork providers available for a media library type. +/// +/// The media library type whose available artwork providers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeArtworkProvidersRequest( + string LibraryType +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequest.cs new file mode 100644 index 00000000..610d219f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request for retrieving the book readers available for a media library type. +/// +/// The media library type whose available book readers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeBookReadersRequest( + string LibraryType +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequest.cs new file mode 100644 index 00000000..ec5a3ddd --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.Management; + +/// +/// Represents a request for retrieving the metadata providers available for a media library type. +/// +/// The media library type whose available metadata providers are retrieved. Required. +[DebuggerDisplay("LibraryType: {LibraryType}")] +public record GetLibraryTypeMetadataProvidersRequest( + string LibraryType +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs deleted file mode 100644 index 86d84308..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.Plugins; - -/// -/// Represents a request to reorder the artwork providers of a media library. -/// -/// The Id of the media library whose artwork providers are reordered. Required. -/// The plugin Ids in the new order, from highest to lowest rank. Required. -[DebuggerDisplay("LibraryId: {LibraryId}")] -public record ReorderLibraryArtworkProvidersRequest( - Guid LibraryId, - List PluginIds -); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs deleted file mode 100644 index a4048843..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.Plugins; - -/// -/// Represents a request to reorder the metadata providers of a media library. -/// -/// The Id of the media library whose metadata providers are reordered. Required. -/// The plugin Ids in the new order, from highest to lowest rank. Required. -[DebuggerDisplay("LibraryId: {LibraryId}")] -public record ReorderLibraryMetadataProvidersRequest( - Guid LibraryId, - List PluginIds -); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs deleted file mode 100644 index 9c934831..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetBookReaderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.Plugins; - -/// -/// Represents a request to enable or disable a book reader for a media library. -/// -/// The Id of the media library whose book reader is enabled or disabled. Required. -/// The unique identifier of the plugin providing the book reader. Required. -/// Whether the book reader should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public record SetBookReaderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs deleted file mode 100644 index aa55773d..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.Plugins; - -/// -/// Represents a request to enable or disable an artwork provider for a media library. -/// -/// The Id of the media library whose artwork provider is enabled or disabled. Required. -/// The unique identifier of the plugin providing the artwork. Required. -/// Whether the artwork provider should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public record SetLibraryArtworkProviderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs deleted file mode 100644 index bf442946..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequest.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.Requests.Plugins; - -/// -/// Represents a request to enable or disable a metadata provider for a media library. -/// -/// The Id of the media library whose metadata provider is enabled or disabled. Required. -/// The unique identifier of the plugin providing the metadata. Required. -/// Whether the metadata provider should be enabled for the media library. Required. -[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] -public record SetLibraryMetadataProviderEnabledRequest( - Guid LibraryId, - Guid PluginId, - bool IsEnabled -); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs index 64ebcdc6..837be446 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Libraries.cs @@ -23,12 +23,10 @@ public static partial class ApiRoutes public const string CANCEL_LIBRARY_SCAN = "libraries/{libraryId}/scans/{scanId}/cancel"; public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "libraries/path-template-parts/{libraryType}"; public const string GET_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers"; - public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; - public const string REORDER_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers/reorder"; public const string GET_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers"; - public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; - public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers/reorder"; public const string GET_LIBRARY_BOOK_READERS = "libraries/{libraryId}/book-readers"; - public const string SET_LIBRARY_BOOK_READER_ENABLED = "libraries/{libraryId}/book-readers/{pluginId}/enabled"; + public const string GET_LIBRARY_TYPE_METADATA_PROVIDERS = "libraries/metadata-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_ARTWORK_PROVIDERS = "libraries/artwork-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_BOOK_READERS = "libraries/book-readers/{libraryType}"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs index d89cf6a3..2f1a8cdf 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryManagement.cs @@ -24,12 +24,10 @@ public static partial class WebRoutes public const string CANCEL_LIBRARY_SCAN = "{culture}/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"; public const string GET_LIBRARY_PATH_TEMPLATE_PARTS = "{culture}/libraries/manage/api-get-path-template-parts/{libraryType}"; public const string GET_METADATA_PROVIDERS = "{culture}/libraries/manage/api-get-metadata-providers/{libraryId}"; - public const string SET_METADATA_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-metadata-provider-enabled"; - public const string REORDER_METADATA_PROVIDERS = "{culture}/libraries/manage/api-reorder-metadata-providers"; public const string GET_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-get-artwork-providers/{libraryId}"; - public const string SET_ARTWORK_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-artwork-provider-enabled"; - public const string REORDER_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-reorder-artwork-providers"; public const string GET_BOOK_READERS = "{culture}/libraries/manage/api-get-book-readers/{libraryId}"; - public const string SET_BOOK_READER_ENABLED = "{culture}/libraries/manage/api-set-book-reader-enabled"; + public const string GET_LIBRARY_TYPE_METADATA_PROVIDERS = "{culture}/libraries/manage/api-get-library-type-metadata-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-get-library-type-artwork-providers/{libraryType}"; + public const string GET_LIBRARY_TYPE_BOOK_READERS = "{culture}/libraries/manage/api-get-library-type-book-readers/{libraryType}"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs index 0396bf28..e8d6974d 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpoint.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; @@ -26,6 +27,7 @@ public class AddLibraryViewEndpoint : BaseEndpoint Routes(WebRoutes.LibraryManagement.ADD_LIBRARY); DontAutoTag(); Options(options => options.WithTags("Libraries")); + Policies(AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs index b84ee688..33f77008 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpoint.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Requests.Library.Management; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; @@ -39,6 +40,7 @@ public class DeleteLibraryEndpoint : BaseEndpoint DontAutoTag(); Options(options => options.WithTags("Libraries")); EnableAntiforgery(); + Policies(AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs index b0106ea2..c22c3faa 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpoint.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Requests.Library.Management; using Lumina.Presentation.Web.Common.Routes; @@ -39,6 +40,7 @@ public class EditLibraryViewEndpoint : BaseEndpoint Routes(WebRoutes.LibraryManagement.EDIT_LIBRARY); DontAutoTag(); Options(options => options.WithTags("Libraries")); + Policies(AuthorizationPolicies.REQUIRE_CREATE_LIBRARIES_PERMISSION); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpoint.cs new file mode 100644 index 00000000..b9c536ec --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-library-type-artwork-providers/{libraryType} route. +/// +public class GetLibraryTypeArtworkProvidersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibraryTypeArtworkProvidersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the artwork providers available for a media library type. + /// + /// The request containing the media library type whose available artwork providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeArtworkProvidersRequest request, CancellationToken cancellationToken) + { + LibraryArtworkProviderDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString(request.LibraryType)), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs new file mode 100644 index 00000000..710e538b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersEndpointSummary() + { + Summary = "Retrieves the artwork providers available for a media library type."; + Description = "Retrieves the artwork providers that support the media library type identified by the route, disabled and ranked in alphabetical order, the way a new media library of that type starts."; + RequestParam(r => r.LibraryType, "The media library type whose available artwork providers are retrieved. Required."); + + ExampleRequest = new GetLibraryTypeArtworkProvidersRequest( + LibraryType: "Book" + ); + + Response(200, "The artwork providers available for the media library type are returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs new file mode 100644 index 00000000..5636f4b3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-library-type-book-readers/{libraryType} route. +/// +public class GetLibraryTypeBookReadersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibraryTypeBookReadersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_BOOK_READERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the book readers available for a media library type. + /// + /// The request containing the media library type whose available book readers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeBookReadersRequest request, CancellationToken cancellationToken) + { + LibraryBookReaderDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", Uri.EscapeDataString(request.LibraryType)), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs new file mode 100644 index 00000000..d3c05dbc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersEndpointSummary() + { + Summary = "Retrieves the book readers available for a media library type."; + Description = "Retrieves the book readers that support the media library type identified by the route, with their supported file extensions, disabled and in alphabetical order, the way a new media library of that type starts."; + RequestParam(r => r.LibraryType, "The media library type whose available book readers are retrieved. Required."); + + ExampleRequest = new GetLibraryTypeBookReadersRequest( + LibraryType: "Book" + ); + + Response(200, "The book readers available for the media library type are returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs new file mode 100644 index 00000000..56104bcf --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// API endpoint for the /{culture}/libraries/manage/api-get-library-type-metadata-providers/{libraryType} route. +/// +public class GetLibraryTypeMetadataProvidersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetLibraryTypeMetadataProvidersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_METADATA_PROVIDERS); + DontAutoTag(); + Options(options => options.WithTags("Libraries")); + } + + /// + /// Retrieves the metadata providers available for a media library type. + /// + /// The request containing the media library type whose available metadata providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryTypeMetadataProvidersRequest request, CancellationToken cancellationToken) + { + LibraryMetadataProviderDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString(request.LibraryType)), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs new file mode 100644 index 00000000..eab5de61 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersEndpointSummary() + { + Summary = "Retrieves the metadata providers available for a media library type."; + Description = "Retrieves the metadata providers that support the media library type identified by the route, disabled and ranked in alphabetical order, the way a new media library of that type starts."; + RequestParam(r => r.LibraryType, "The media library type whose available metadata providers are retrieved. Required."); + + ExampleRequest = new GetLibraryTypeMetadataProvidersRequest( + LibraryType: "Book" + ); + + Response(200, "The metadata providers available for the media library type are returned."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs index f553d0eb..2a561166 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpoint.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -15,6 +17,17 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; /// public class LibrariesIndexViewEndpoint : BaseEndpoint { + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization checks against the remote API. + public LibrariesIndexViewEndpoint(IAuthorizationService authorizationService) + { + _authorizationService = authorizationService; + } + /// /// Configures the endpoint. /// @@ -32,8 +45,12 @@ public class LibrariesIndexViewEndpoint : BaseEndpoint /// /// The request object. /// Cancellation token that can be used to stop the execution. - public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - return Task.FromResult(View("/Core/Views/Library/Management/Index.cshtml")); + // Changing and deleting a media library takes the permission to manage media libraries, or the administrator role, the same rule the API applies, + // so the actions are only offered to the users the API would let through. + bool canManageLibraries = await _authorizationService.IsInRoleAsync("Admin", cancellationToken).ConfigureAwait(false) || + await _authorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false); + return View("/Core/Views/Library/Management/Index.cshtml", new LibrariesIndexPageDto(canManageLibraries)); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpoint.cs deleted file mode 100644 index fc468634..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-reorder-artwork-providers route. -/// -public class ReorderArtworkProvidersEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public ReorderArtworkProvidersEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.REORDER_ARTWORK_PROVIDERS); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Reorders the artwork providers of a media library. - /// - /// The request containing the Id of the media library and the plugin Ids in the new order. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs deleted file mode 100644 index fbb75201..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs +++ /dev/null @@ -1,34 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class ReorderArtworkProvidersEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderArtworkProvidersEndpointSummary() - { - Summary = "Reorders the artwork providers of a media library."; - Description = "Reorders the artwork providers of the media library identified by the route, in the provided order."; - RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required."); - RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); - - ExampleRequest = new ReorderLibraryArtworkProvidersRequest( - LibraryId: Guid.NewGuid(), - PluginIds: [Guid.NewGuid(), Guid.NewGuid()] - ); - - Response(200, "The artwork providers of the media library are reordered.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs deleted file mode 100644 index 89ea7054..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-reorder-metadata-providers route. -/// -public class ReorderMetadataProvidersEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public ReorderMetadataProvidersEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.REORDER_METADATA_PROVIDERS); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Reorders the metadata providers of a media library. - /// - /// The request containing the Id of the media library and the plugin Ids in the new order. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(ReorderLibraryMetadataProvidersRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.REORDER_LIBRARY_METADATA_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs deleted file mode 100644 index 1ea20a6c..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class ReorderMetadataProvidersEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public ReorderMetadataProvidersEndpointSummary() - { - Summary = "Reorders the metadata providers of a media library."; - Description = "Reorders the metadata providers of the media library identified by the route."; - RequestParam(r => r.LibraryId, "The Id of the media library whose metadata providers are reordered. Required."); - RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); - - ExampleRequest = new ReorderLibraryMetadataProvidersRequest( - LibraryId: Guid.NewGuid(), - PluginIds: - [ - Guid.NewGuid(), - Guid.NewGuid(), - ] - ); - - Response(200, "The metadata providers of the media library are reordered.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs index 338d22c4..9f068782 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs @@ -21,7 +21,6 @@ public class SaveLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library. Optional, when creating a new media library."); - RequestParam(r => r.UserId, "The unique identifier of the user owning the media library. Optional."); RequestParam(r => r.Title, "The title of the media library. Required."); RequestParam(r => r.LibraryType, "The type of the media library. Required."); RequestParam(r => r.CoverImage, "The path of the image file used as the cover of the media library. Optional."); @@ -35,6 +34,9 @@ public class SaveLibraryEndpointSummary : Summary r.ShouldTrackConsumptionProgress, "Whether the consumption progress of the media library items should be tracked, or not. Optional, the default of the library type is used on create, and the stored value is kept on update."); RequestParam(r => r.CompletionThresholdPercentage, "The percentage of a media library item that must be consumed for its session to be considered completed. Optional, the default of the library type is used on create, and the stored value is kept on update."); RequestParam(r => r.PathTemplateParts, "The ordered parts of the template describing the structure of the media library on disk. Optional, the ideal structure of the library type is used when absent."); + RequestParam(r => r.MetadataProviders, "The metadata providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the providers are configured with their defaults on create, and the stored configurations are kept on update, when absent."); + RequestParam(r => r.ArtworkProviders, "The artwork providers of the media library, in the order in which they are tried, and whether each one is enabled. Optional, the providers are configured with their defaults on create, and the stored configurations are kept on update, when absent."); + RequestParam(r => r.BookReaders, "The book readers of the media library, and whether each one is enabled. Optional, the readers are configured with their defaults on create, and the stored configurations are kept on update, when absent."); ExampleRequest = new LibraryDto(); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpoint.cs deleted file mode 100644 index 4d454ce8..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-set-artwork-provider-enabled route. -/// -public class SetArtworkProviderEnabledEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public SetArtworkProviderEnabledEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.SET_ARTWORK_PROVIDER_ENABLED); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Enables or disables an artwork provider of a media library. - /// - /// The request containing the Ids of the media library and of the plugin, and whether the provider is enabled. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs deleted file mode 100644 index 7a1922e3..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetArtworkProviderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetArtworkProviderEnabledEndpointSummary() - { - Summary = "Enables or disables an artwork provider of a media library."; - Description = "Enables or disables the artwork provider of the media library identified by the route."; - RequestParam(r => r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required."); - RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library, or not. Required."); - - ExampleRequest = new SetLibraryArtworkProviderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - Response(200, "The artwork provider of the media library is enabled or disabled.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs deleted file mode 100644 index 423d5292..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-set-book-reader-enabled route. -/// -public class SetBookReaderEnabledEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public SetBookReaderEnabledEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.SET_BOOK_READER_ENABLED); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Enables or disables a book reader of a media library. - /// - /// The request containing the Ids of the media library and of the plugin, and whether the book reader is enabled. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetBookReaderEnabledRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs deleted file mode 100644 index bc08a3e0..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetBookReaderEnabledEndpointSummary() - { - Summary = "Enables or disables a book reader of a media library."; - Description = "Enables or disables the book reader of the media library identified by the route."; - RequestParam(r => r.LibraryId, "The Id of the media library whose book reader is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader. Required."); - RequestParam(r => r.IsEnabled, "Whether the book reader should be enabled for the media library, or not. Required."); - - ExampleRequest = new SetBookReaderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - Response(200, "The book reader of the media library is enabled or disabled.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs deleted file mode 100644 index c27924c3..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpoint.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; - -/// -/// API endpoint for the /{culture}/libraries/manage/api-set-metadata-provider-enabled route. -/// -public class SetMetadataProviderEnabledEndpoint : BaseEndpoint -{ - private readonly IApiHttpClient _apiHttpClient; - - /// - /// Initializes a new instance of the class. - /// - /// Injected service for interactions with the API. - public SetMetadataProviderEnabledEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.PUT); - Routes(WebRoutes.LibraryManagement.SET_METADATA_PROVIDER_ENABLED); - DontAutoTag(); - Options(options => options.WithTags("Libraries")); - EnableAntiforgery(); - } - - /// - /// Enables or disables a metadata provider of a media library. - /// - /// The request containing the Ids of the media library and of the plugin, and whether the provider is enabled. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(SetLibraryMetadataProviderEnabledRequest request, CancellationToken cancellationToken) - { - await _apiHttpClient.PutAsync(ApiRoutes.Libraries.SET_LIBRARY_METADATA_PROVIDER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); - return JsonSuccess(); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs deleted file mode 100644 index 163d7afe..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class SetMetadataProviderEnabledEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public SetMetadataProviderEnabledEndpointSummary() - { - Summary = "Enables or disables a metadata provider of a media library."; - Description = "Enables or disables the metadata provider of the media library identified by the route."; - RequestParam(r => r.LibraryId, "The Id of the media library whose metadata provider is enabled or disabled. Required."); - RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the metadata. Required."); - RequestParam(r => r.IsEnabled, "Whether the metadata provider should be enabled for the media library, or not. Required."); - - ExampleRequest = new SetLibraryMetadataProviderEnabledRequest( - LibraryId: Guid.NewGuid(), - PluginId: Guid.NewGuid(), - IsEnabled: true - ); - - Response(200, "The metadata provider of the media library is enabled or disabled.", example: new SuccessResponse(true)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx index d3c3df28..990838bb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx @@ -540,11 +540,11 @@ لا يمكن أن يكون معرف الإضافة فارغًا! - - لا يمكن أن تكون قائمة معرفات الإضافات فارغة! + + لا يمكن اختيار الإضافة نفسها أكثر من مرة! - - لا يمكن أن تكون قائمة معرفات الإضافات فارغة! + + الإضافة لا تدعم نوع مكتبة الوسائط! لم يتم العثور على الإضافة! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 7acf27db..d50bb406 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -540,11 +540,11 @@ Die Plugin-ID darf nicht leer sein! - - Die Plugin-ID-Liste darf nicht leer sein! + + Dasselbe Plugin darf nicht mehrfach ausgewählt werden! - - Die Plugin-ID-Liste darf nicht null sein! + + Das Plugin unterstützt den Medienbibliothekstyp nicht! Das Plugin wurde nicht gefunden! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 81d5e56c..4fb7b5ce 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -540,11 +540,11 @@ The plugin Id cannot be empty! - - The plugin Ids list cannot be empty! + + The same plugin cannot be chosen more than once! - - The plugin Ids list cannot be null! + + The plugin does not support the media library type! The plugin was not found! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index b36fedaf..eda9e4c2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -540,11 +540,11 @@ ¡El Id del plugin no puede estar vacío! - - ¡La lista de Ids de plugins no puede estar vacía! + + ¡No se puede elegir el mismo plugin más de una vez! - - ¡La lista de Ids de plugins no puede ser nula! + + ¡El plugin no admite el tipo de biblioteca multimedia! ¡El plugin no fue encontrado! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index fc764a80..21b5f621 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -540,11 +540,11 @@ L'Id du plugin ne peut pas être vide ! - - La liste des Ids de plugins ne peut pas être vide ! + + Le même plugin ne peut pas être choisi plus d'une fois ! - - La liste des Ids de plugins ne peut pas être nulle ! + + Le plugin ne prend pas en charge le type de médiathèque ! Le plugin est introuvable ! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 56c362f1..faab4cbb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -540,11 +540,11 @@ L'Id del plugin non può essere vuoto! - - L'elenco degli Id dei plugin non può essere vuoto! + + Lo stesso plugin non può essere scelto più di una volta! - - L'elenco degli Id dei plugin non può essere nullo! + + Il plugin non supporta il tipo di libreria multimediale! Il plugin non è stato trovato! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 804b2b90..8a4caeeb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -540,11 +540,11 @@ プラグイン ID を空にすることはできません。 - - プラグイン ID のリストを空にすることはできません。 + + 同じプラグインを複数回選択することはできません。 - - プラグイン ID のリストを null にすることはできません。 + + このプラグインはメディアライブラリの種類に対応していません。 プラグインが見つかりませんでした。 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 8d705929..20709fe1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -540,11 +540,11 @@ The plugin Id cannot be empty! - - The plugin Ids list cannot be empty! + + The same plugin cannot be chosen more than once! - - The plugin Ids list cannot be null! + + The plugin does not support the media library type! The plugin was not found! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index ae2450db..cf8669fd 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -540,11 +540,11 @@ Id-ul pluginului nu poate fi gol! - - Lista Id-urilor de pluginuri nu poate fi goala! + + Același plugin nu poate fi ales de mai multe ori! - - Lista Id-urilor de pluginuri nu poate fi nula! + + Pluginul nu suportă tipul bibliotecii media! Pluginul nu a fost gasit! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx index 197e157e..b203e4e0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx @@ -540,11 +540,11 @@ Ідентифікатор плагіна не може бути порожнім! - - Список ідентифікаторів плагінів не може бути порожнім! + + Той самий плагін не можна вибрати більше одного разу! - - Список ідентифікаторів плагінів не може бути порожнім! + + Плагін не підтримує тип медіатеки! Плагін не знайдено! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index cdcf3979..b8ec1f6d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -540,11 +540,11 @@ 插件 Id 不能为空! - - 插件 Id 列表不能为空! + + 同一插件不能被多次选择! - - 插件 Id 列表不能为 null! + + 该插件不支持此媒体库类型! 未找到插件! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx index 472452b6..89ebb567 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx @@ -333,9 +333,6 @@ نقل لأسفل - - تم حفظ الترتيب - مزوّدو البيانات الوصفية المستخدمون لإثراء عناصر هذه المكتبة، بالترتيب الذي يتم تجريبهم به. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx index 3951cc56..9c2ca317 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.de-DE.resx @@ -333,9 +333,6 @@ Nach unten - - Reihenfolge gespeichert - Die Metadatenanbieter, die verwendet werden, um die Elemente dieser Bibliothek anzureichern, in der Reihenfolge, in der sie versucht werden. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx index 69679d6a..8045254d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.en-US.resx @@ -333,9 +333,6 @@ Move down - - Order saved - The metadata providers used to enrich the items of this library, in the order they are tried. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx index 70d5c756..40eb7a05 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.es-ES.resx @@ -333,9 +333,6 @@ Bajar - - Orden guardado - Los proveedores de metadatos utilizados para enriquecer los elementos de esta biblioteca, en el orden en que se prueban. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx index 05c47ce0..60a3c87a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.fr-FR.resx @@ -333,9 +333,6 @@ Descendre - - Ordre enregistré - Les fournisseurs de métadonnées utilisés pour enrichir les éléments de cette bibliothèque, dans l'ordre où ils sont essayés. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx index 6141fb44..e3db91a5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.it-IT.resx @@ -333,9 +333,6 @@ Sposta giù - - Ordine salvato - I fornitori di metadati utilizzati per arricchire gli elementi di questa libreria, nell'ordine in cui vengono provati. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx index 4dcdd3f0..a842698c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ja-JP.resx @@ -333,9 +333,6 @@ 下へ移動 - - 順序を保存しました - このライブラリのアイテムを補完するために使用されるメタデータプロバイダーを、試行する順序で指定します。 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx index 69679d6a..8045254d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.resx @@ -333,9 +333,6 @@ Move down - - Order saved - The metadata providers used to enrich the items of this library, in the order they are tried. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx index 285d7a4f..903099e8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ro-RO.resx @@ -333,9 +333,6 @@ Mută în jos - - Ordine salvată - Furnizorii de metadate folosiți pentru a îmbogăți elementele acestei biblioteci, în ordinea în care sunt încercați. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx index 4de84f09..c5f835d3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.uk-UA.resx @@ -333,9 +333,6 @@ Вниз - - Порядок збережено - Постачальники метаданих, які використовуються для збагачення елементів цієї бібліотеки, у порядку, в якому вони випробовуються. diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx index ca2f34b4..c75d97e5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.zh-CN.resx @@ -333,9 +333,6 @@ 下移 - - 顺序已保存 - 用于丰富此库项目内容的元数据提供程序,按其尝试顺序排列。 diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml index e312d8cc..d656fd66 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml @@ -5,7 +5,10 @@ @using Lumina.Presentation.Web.Common.DTO.Libraries @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization +@using System.Collections.Generic @using System.Security.Claims +@using System.Text.Json +@model LibrariesIndexPageDto @{ // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. @@ -165,58 +168,89 @@ // Create cleanup registry for this view. const cleanupFunctions = []; let isInitialized = false; - const jsLocalizedLibraryScanStatuses = { - Completed: '@_localizer["Completed"]', - Failed: '@_localizer["Failed"]', - Canceled: '@_localizer["Canceled"]', - Cancelling: '@_localizer["Cancelling"]' - }; - const jsLocalizedLibraryScanJobsStatuses = { - DiscoveringFiles: '@_localizer["DiscoveringFiles"]', - ComparingFileHashes: '@_localizer["ComparingFileHashes"]', - HashingFileContents: '@_localizer["HashingFileContents"]', - ExtractingMetadata: '@_localizer["ExtractingMetadata"]', - SavingScanData: '@_localizer["SavingScanData"]', - InvalidatingStaleEnrichment: '@_localizer["InvalidatingStaleEnrichment"]', - EnrichingMetadata: '@_localizer["EnrichingMetadata"]', - ResolvingArtwork: '@_localizer["ResolvingArtwork"]', - Queued: '@_localizer["Queued"]' - }; - const jsLocalizedLibraryTypes = { - Book: '@_localizer["Book"]', - EBook: '@_localizer["EBook"]', - BookSeries: '@_localizer["BookSeries"]', - ComicBook: '@_localizer["ComicBook"]', - ComicSeries: '@_localizer["ComicSeries"]', - Magazine: '@_localizer["Magazine"]', - Manga: '@_localizer["Manga"]', - GraphicNovel: '@_localizer["GraphicNovel"]', - AcademicPaper: '@_localizer["AcademicPaper"]', - SheetMusic: '@_localizer["SheetMusic"]', - Screenplay: '@_localizer["Screenplay"]', - TvShow: '@_localizer["TvShow"]', - Movie: '@_localizer["Movie"]', - FilmSeries: '@_localizer["FilmSeries"]', - FilmFranchise: '@_localizer["FilmFranchise"]', - Concert: '@_localizer["Concert"]', - Documentary: '@_localizer["Documentary"]', - Tutorial: '@_localizer["Tutorial"]', - Personal: '@_localizer["Personal"]', - Anime: '@_localizer["Anime"]', - Youtube: '@_localizer["Youtube"]', - Videoclip: '@_localizer["Videoclip"]', - Music: '@_localizer["Music"]', - AudioBook: '@_localizer["AudioBook"]', - LivePerformance: '@_localizer["LivePerformance"]', - Interview: '@_localizer["Interview"]', - Cover: '@_localizer["Cover"]', - Remix: '@_localizer["Remix"]', - Soundeffect: '@_localizer["Soundeffect"]', - Podcast: '@_localizer["Podcast"]', - RadioShow: '@_localizer["RadioShow"]', - PhotoAlbum: '@_localizer["PhotoAlbum"]', - Other: '@_localizer["Other"]' - }; + // Changing and deleting a media library takes the permission to manage media libraries, or the administrator role, so the edit and delete actions are + // only rendered for the users the server would let through. + const canManageLibraries = @(Model.CanManageLibraries ? "true" : "false"); + // The localized strings used inside this script are injected as JSON, not as raw HTML text: Razor HTML-encodes non-ASCII characters into numeric + // entities, which the browser does not decode inside a script element, and a translation containing a quote, a backtick or "${" would break out of + // the string or template literal it was placed in. JSON escapes them, so the script reads them correctly. + const jsLocalizedLibraryScanStatuses = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["Completed"] = _localizer["Completed"].Value, + ["Failed"] = _localizer["Failed"].Value, + ["Canceled"] = _localizer["Canceled"].Value, + ["Cancelling"] = _localizer["Cancelling"].Value + })); + const jsLocalizedLibraryScanJobsStatuses = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["DiscoveringFiles"] = _localizer["DiscoveringFiles"].Value, + ["ComparingFileHashes"] = _localizer["ComparingFileHashes"].Value, + ["HashingFileContents"] = _localizer["HashingFileContents"].Value, + ["ExtractingMetadata"] = _localizer["ExtractingMetadata"].Value, + ["SavingScanData"] = _localizer["SavingScanData"].Value, + ["InvalidatingStaleEnrichment"] = _localizer["InvalidatingStaleEnrichment"].Value, + ["EnrichingMetadata"] = _localizer["EnrichingMetadata"].Value, + ["ResolvingArtwork"] = _localizer["ResolvingArtwork"].Value, + ["Queued"] = _localizer["Queued"].Value + })); + const jsLocalizedLibraryTypes = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["Book"] = _localizer["Book"].Value, + ["EBook"] = _localizer["EBook"].Value, + ["BookSeries"] = _localizer["BookSeries"].Value, + ["ComicBook"] = _localizer["ComicBook"].Value, + ["ComicSeries"] = _localizer["ComicSeries"].Value, + ["Magazine"] = _localizer["Magazine"].Value, + ["Manga"] = _localizer["Manga"].Value, + ["GraphicNovel"] = _localizer["GraphicNovel"].Value, + ["AcademicPaper"] = _localizer["AcademicPaper"].Value, + ["SheetMusic"] = _localizer["SheetMusic"].Value, + ["Screenplay"] = _localizer["Screenplay"].Value, + ["TvShow"] = _localizer["TvShow"].Value, + ["Movie"] = _localizer["Movie"].Value, + ["FilmSeries"] = _localizer["FilmSeries"].Value, + ["FilmFranchise"] = _localizer["FilmFranchise"].Value, + ["Concert"] = _localizer["Concert"].Value, + ["Documentary"] = _localizer["Documentary"].Value, + ["Tutorial"] = _localizer["Tutorial"].Value, + ["Personal"] = _localizer["Personal"].Value, + ["Anime"] = _localizer["Anime"].Value, + ["Youtube"] = _localizer["Youtube"].Value, + ["Videoclip"] = _localizer["Videoclip"].Value, + ["Music"] = _localizer["Music"].Value, + ["AudioBook"] = _localizer["AudioBook"].Value, + ["LivePerformance"] = _localizer["LivePerformance"].Value, + ["Interview"] = _localizer["Interview"].Value, + ["Cover"] = _localizer["Cover"].Value, + ["Remix"] = _localizer["Remix"].Value, + ["Soundeffect"] = _localizer["Soundeffect"].Value, + ["Podcast"] = _localizer["Podcast"].Value, + ["RadioShow"] = _localizer["RadioShow"].Value, + ["PhotoAlbum"] = _localizer["PhotoAlbum"].Value, + ["Other"] = _localizer["Other"].Value + })); + const jsLocalizedLabels = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["Yes"] = _localizer["Yes"].Value, + ["No"] = _localizer["No"].Value, + ["Completed"] = _localizer["Completed"].Value, + ["Failed"] = _localizer["Failed"].Value, + ["Canceled"] = _localizer["Canceled"].Value, + ["CancelScan"] = _localizer["CancelScan"].Value, + ["Scan"] = _localizer["Scan"].Value, + ["Edit"] = _localizer["Edit"].Value, + ["Remove"] = _localizer["Remove"].Value, + ["DeleteLibraryConfirm"] = _localizer["DeleteLibraryConfirm"].Value, + ["LibraryDeleted"] = _localizer["LibraryDeleted"].Value + })); + + // Escapes a value for use as text or as a quoted attribute value inside markup, since the titles of the libraries are typed by their users. + function escapeHtml(value) { + const div = document.createElement('div'); + div.textContent = value ?? ''; + return div.innerHTML.replace(/"/g, '"'); + } + // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const btnScanAllLibraries = document.getElementById('btn-scan-all-libraries'); const btnCancelLibrariesScan = document.getElementById('btn-cancel-libraries-scan'); @@ -250,13 +284,13 @@ btnScanAllLibraries.style.display = 'block'; tbody.innerHTML = response.map(library => { const editUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.EDIT_LIBRARY, new { id = default(Guid) })' - .replace('/@(default(Guid))', `/${library.id}`); + .replace('/@(default(Guid))', `/${encodeURIComponent(library.id)}`); return ` - - ${library.title} - ${jsLocalizedLibraryTypes[library.libraryType]} - ${library.isEnabled === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} - ${library.isLocked === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} + + ${escapeHtml(library.title)} + ${escapeHtml(jsLocalizedLibraryTypes[library.libraryType] ?? library.libraryType)} + ${escapeHtml(library.isEnabled === true ? jsLocalizedLabels.Yes : jsLocalizedLabels.No)} + ${escapeHtml(library.isLocked === true ? jsLocalizedLabels.Yes : jsLocalizedLabels.No)} - @if (id is not null) - { + + + +
@@ -341,6 +346,23 @@ // Create cleanup registry for this view. const cleanupFunctions = []; + // The localized labels of the rows built by this script, injected as JSON for the same reason as the path part labels below, and so that a translation + // containing a backtick or "${" cannot break out of the template literals that render the rows. + const rowLabels = @Html.Raw(JsonSerializer.Serialize(new Dictionary + { + ["remove"] = _localizer["Remove"].Value, + ["moveUp"] = _localizer["MoveUp"].Value, + ["moveDown"] = _localizer["MoveDown"].Value + })); + + // Escapes a value for use as text or as a quoted attribute value inside markup, since the chosen paths and the names, Ids and extensions of the providers + // are not controlled by this page. + function escapeHtml(value) { + const div = document.createElement('div'); + div.textContent = value ?? ''; + return div.innerHTML.replace(/"/g, '"'); + } + // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const saveSuccess = document.getElementById('save-success'); const btnBackToLibraries = document.getElementById('btn-back-to-libraries'); @@ -374,7 +396,6 @@ const completionThresholdPercentage = inputCompletionThresholdPercentage.value.trim(); const formData = { Id: form.querySelector('[name="Id"]').value || null, - UserId: form.querySelector('[name="UserId"]').value || null, Title: form.querySelector('[name="Title"]').value, LibraryType: form.querySelector('#library-selected-item').getAttribute('data-value'), ContentLocations: Array.from(mediaDirectoriesFormTable.querySelectorAll('.form-table-row span')) @@ -404,7 +425,12 @@ Representation: getPathTemplatePillRepresentation(pill), IsOptional: optional ? optional.checked : false }; - }) + }), + // The provider choices are saved together with the library. A list that could not be loaded is sent as null, so the server keeps + // or reconciles what it has, instead of being told that every provider was left out. + MetadataProviders: areMetadataProvidersLoaded ? getProviderSelections(metadataProvidersTbody, 'metadata-provider-enabled') : null, + ArtworkProviders: areArtworkProvidersLoaded ? getProviderSelections(artworkProvidersTbody, 'artwork-provider-enabled') : null, + BookReaders: areBookReadersLoaded ? getProviderSelections(bookReadersTbody, 'book-reader-enabled') : null }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SAVE_LIBRARY)', formData); if (data) { @@ -428,8 +454,8 @@ if (!isDuplicate) { mediaDirectoriesFormTable.insertAdjacentHTML('beforeend', `
- ${normalizedPath} - @_localizer[ + ${escapeHtml(normalizedPath)} + ${escapeHtml(rowLabels.remove)}
`); } @@ -446,8 +472,8 @@ const path = paths[0]; // Only use the first path. mediaCoverFormTable.insertAdjacentHTML('beforeend', `
- ${path} - @_localizer[ + ${escapeHtml(path)} + ${escapeHtml(rowLabels.remove)}
`); } @@ -494,169 +520,121 @@ }; const id = '@id'; - const metadataProvidersTable = document.getElementById('metadata-providers-table'); - const metadataProvidersTbody = metadataProvidersTable ? metadataProvidersTable.querySelector('tbody') : null; + const metadataProvidersSection = document.getElementById('metadata-providers-section'); + const metadataProvidersTbody = document.getElementById('metadata-providers-table').querySelector('tbody'); + const artworkProvidersSection = document.getElementById('artwork-providers-section'); + const artworkProvidersTbody = document.getElementById('artwork-providers-table').querySelector('tbody'); + const bookReadersSection = document.getElementById('book-readers-section'); + const bookReadersTbody = document.getElementById('book-readers-table').querySelector('tbody'); + // Whether each provider list was loaded for the selected library type. A list that failed to load is not sent when the library is saved. + let areMetadataProvidersLoaded = false; + let areArtworkProvidersLoaded = false; + let areBookReadersLoaded = false; + // Incremented on every load, so that the responses of a load started for a previously selected library type are discarded. + let providersLoadVersion = 0; - // Loads the metadata providers configured for the library, when editing an existing library. - async function loadMetadataProvidersAsync() { - if (!id || !metadataProvidersTbody) return; - const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_METADATA_PROVIDERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. - const response = await callApiGetAsync(url); - if (response && response.length > 0) { - metadataProvidersTbody.innerHTML = response.map((provider, index) => renderMetadataProviderRow(provider, index, response.length)).join(''); + // Loads the metadata providers, artwork providers and book readers of the selected library type. A new library lists the providers available for the + // type, the way a new library of that type starts. An existing library merges its stored configuration with them, the same way the server reconciles + // the configuration when the library is saved: the stored providers that the type still supports keep their state and order, the newly supported + // ones are added disabled after them, and the stored providers that the type no longer supports are left out, so they are never submitted. + async function loadProvidersAsync() { + const libraryType = getSelectedLibraryType(); + const loadVersion = ++providersLoadVersion; + areMetadataProvidersLoaded = false; + areArtworkProvidersLoaded = false; + areBookReadersLoaded = false; + if (!libraryType) { + renderProviders(null, null, null); + return; } + // The Id and the type need to be replaced here, because GetAbsoluteUrl is server side, while the library Id and the selected type are client side. + const encodedLibraryType = encodeURIComponent(libraryType); + const requests = [ + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_METADATA_PROVIDERS, new { libraryType = "Book" })'.replace('/Book', `/${encodedLibraryType}`)), + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS, new { libraryType = "Book" })'.replace('/Book', `/${encodedLibraryType}`)), + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_LIBRARY_TYPE_BOOK_READERS, new { libraryType = "Book" })'.replace('/Book', `/${encodedLibraryType}`)) + ]; + if (id) { + requests.push( + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_METADATA_PROVIDERS, new { libraryId = default(Guid) })'.replace('/@(default(Guid))', `/${id}`)), + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS, new { libraryId = default(Guid) })'.replace('/@(default(Guid))', `/${id}`)), + callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_BOOK_READERS, new { libraryId = default(Guid) })'.replace('/@(default(Guid))', `/${id}`))); + } + const [availableMetadataProviders, availableArtworkProviders, availableBookReaders, storedMetadataProviders, storedArtworkProviders, storedBookReaders] = await Promise.all(requests); + if (loadVersion !== providersLoadVersion) + return; + if (!id) { + renderProviders(availableMetadataProviders, availableArtworkProviders, availableBookReaders); + return; + } + renderProviders( + mergeStoredProviders(availableMetadataProviders, storedMetadataProviders), + mergeStoredProviders(availableArtworkProviders, storedArtworkProviders), + mergeStoredProviders(availableBookReaders, storedBookReaders)); } - // Renders a metadata provider row of the library. - function renderMetadataProviderRow(provider, index, count) { + // Merges the stored configuration of a library with the providers available for the selected type. Returns null when either list could not be + // loaded, so that the list is not submitted and the server keeps what it has. An empty list of available providers is treated the same way: + // while stored providers exist, it means that no loaded plugin currently reports support for the type, not that the user left every provider + // out. Submitting it would tell the server that the whole list is a choice, which deletes the stored rows along with their enablement and + // order, and the next plugin sync would re-add them disabled. + function mergeStoredProviders(availableProviders, storedProviders) { + if (!Array.isArray(availableProviders) || !Array.isArray(storedProviders)) + return null; + if (availableProviders.length === 0 && storedProviders.length > 0) + return null; + const availableProvidersById = new Map(availableProviders.map(provider => [provider.pluginId, provider])); + const keptProviders = storedProviders + .filter(provider => availableProvidersById.has(provider.pluginId)) + .sort((first, second) => (first.rank ?? 0) - (second.rank ?? 0)) + .map(provider => ({ ...availableProvidersById.get(provider.pluginId), isEnabled: provider.isEnabled })); + const keptPluginIds = new Set(keptProviders.map(provider => provider.pluginId)); + return keptProviders.concat(availableProviders.filter(provider => !keptPluginIds.has(provider.pluginId))); + } + + // Renders the provider lists, and shows only the sections whose list has at least one provider. + function renderProviders(metadataProviders, artworkProviders, bookReaders) { + areMetadataProvidersLoaded = Array.isArray(metadataProviders); + areArtworkProvidersLoaded = Array.isArray(artworkProviders); + areBookReadersLoaded = Array.isArray(bookReaders); + const metadataProviderRows = areMetadataProvidersLoaded ? metadataProviders : []; + const artworkProviderRows = areArtworkProvidersLoaded ? artworkProviders : []; + const bookReaderRows = areBookReadersLoaded ? bookReaders : []; + metadataProvidersTbody.innerHTML = metadataProviderRows.map(provider => renderRankedProviderRow(provider, 'metadata-provider')).join(''); + artworkProvidersTbody.innerHTML = artworkProviderRows.map(provider => renderRankedProviderRow(provider, 'artwork-provider')).join(''); + bookReadersTbody.innerHTML = bookReaderRows.map(reader => renderBookReaderRow(reader)).join(''); + refreshMoveButtons(metadataProvidersTbody, 'metadata-provider'); + refreshMoveButtons(artworkProvidersTbody, 'artwork-provider'); + metadataProvidersSection.classList.toggle('hidden', metadataProviderRows.length === 0); + artworkProvidersSection.classList.toggle('hidden', artworkProviderRows.length === 0); + bookReadersSection.classList.toggle('hidden', bookReaderRows.length === 0); + } + + // Renders a metadata or artwork provider row, whose position in the table is the order in which the provider is tried. + function renderRankedProviderRow(provider, classPrefix) { return ` - - ${provider.name} + + ${escapeHtml(provider.name)} - - + + `; } - // On metadata provider move button click, reorders the providers and persists the new order. - async function handleMetadataProviderReorderAsync(e) { - const button = e.target.closest('.metadata-provider-move-up, .metadata-provider-move-down'); - if (!button || !metadataProvidersTbody) return; - const row = button.closest('tr'); - if (button.classList.contains('metadata-provider-move-up')) { - const previousRow = row.previousElementSibling; - if (previousRow) metadataProvidersTbody.insertBefore(row, previousRow); - } else { - const nextRow = row.nextElementSibling; - if (nextRow) metadataProvidersTbody.insertBefore(nextRow, row); - } - await saveMetadataProviderOrderAsync(); - } - - // Persists the current order of the metadata providers of the library. - async function saveMetadataProviderOrderAsync() { - if (!id || !metadataProvidersTbody) return; - const pluginIds = Array.from(metadataProvidersTbody.querySelectorAll('tr[data-provider-plugin-id]')) - .map(row => row.getAttribute('data-provider-plugin-id')); - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.REORDER_METADATA_PROVIDERS)', { libraryId: id, pluginIds: pluginIds }); - if (result.success) { - notificationService.show('@_localizer["OrderSaved"]', NotificationType.SUCCESS); - } - } - - // On metadata provider enabled checkbox change, persists the new state. - async function handleMetadataProviderEnabledChangeAsync(e) { - if (e.target.matches('.metadata-provider-enabled')) { - const row = e.target.closest('tr'); - const pluginId = row.getAttribute('data-provider-plugin-id'); - const isEnabled = e.target.checked; - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_METADATA_PROVIDER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled }); - if (!result.success) { - e.target.checked = !isEnabled; - } - } - }; - - const artworkProvidersTable = document.getElementById('artwork-providers-table'); - const artworkProvidersTbody = artworkProvidersTable ? artworkProvidersTable.querySelector('tbody') : null; - - // Loads the artwork providers configured for the library, when editing an existing library. - async function loadArtworkProvidersAsync() { - if (!id || !artworkProvidersTbody) return; - const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. - const response = await callApiGetAsync(url); - if (response && response.length > 0) { - artworkProvidersTbody.innerHTML = response.map((provider, index) => renderArtworkProviderRow(provider, index, response.length)).join(''); - } - } - - // Renders an artwork provider row of the library. - function renderArtworkProviderRow(provider, index, count) { - return ` - - ${provider.name} - - - - - - - - `; - } - - // On artwork provider move button click, reorders the providers and persists the new order. - async function handleArtworkProviderReorderAsync(e) { - const button = e.target.closest('.artwork-provider-move-up, .artwork-provider-move-down'); - if (!button || !artworkProvidersTbody) return; - const row = button.closest('tr'); - if (button.classList.contains('artwork-provider-move-up')) { - const previousRow = row.previousElementSibling; - if (previousRow) artworkProvidersTbody.insertBefore(row, previousRow); - } else { - const nextRow = row.nextElementSibling; - if (nextRow) artworkProvidersTbody.insertBefore(nextRow, row); - } - await saveArtworkProviderOrderAsync(); - } - - // Persists the current order of the artwork providers of the library. - async function saveArtworkProviderOrderAsync() { - if (!id || !artworkProvidersTbody) return; - const pluginIds = Array.from(artworkProvidersTbody.querySelectorAll('tr[data-provider-plugin-id]')) - .map(row => row.getAttribute('data-provider-plugin-id')); - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.REORDER_ARTWORK_PROVIDERS)', { libraryId: id, pluginIds: pluginIds }); - if (result.success) { - notificationService.show('@_localizer["OrderSaved"]', NotificationType.SUCCESS); - } - } - - // On artwork provider enabled checkbox change, persists the new state. - async function handleArtworkProviderEnabledChangeAsync(e) { - if (e.target.matches('.artwork-provider-enabled')) { - const row = e.target.closest('tr'); - const pluginId = row.getAttribute('data-provider-plugin-id'); - const isEnabled = e.target.checked; - const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_ARTWORK_PROVIDER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled }); - if (!result.success) { - e.target.checked = !isEnabled; - } - } - }; - - const bookReadersTable = document.getElementById('book-readers-table'); - const bookReadersTbody = bookReadersTable ? bookReadersTable.querySelector('tbody') : null; - - // Loads the book readers configured for the library, when editing an existing library. - async function loadBookReadersAsync() { - if (!id || !bookReadersTbody) return; - const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_BOOK_READERS, new { libraryId = default(Guid) })' - .replace('/@(default(Guid))', `/${id}`); // The libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side. - const response = await callApiGetAsync(url); - if (response && response.length > 0) { - bookReadersTbody.innerHTML = response.map(reader => renderBookReaderRow(reader)).join(''); - } - } - - // Renders a book reader row of the library. + // Renders a book reader row. function renderBookReaderRow(reader) { const extensions = (reader.supportedExtensions || []).join(', '); return ` - - ${reader.name} - ${extensions} + + ${escapeHtml(reader.name)} + ${escapeHtml(extensions)}
/// Optional. The Id of the media library. - /// Optional. The Id of the user owning the media library. /// Optional. The title of the media library. /// Optional. The type of the media library. /// Optional. The content locations of the media library. @@ -35,10 +34,12 @@ public class UpdateLibraryCommandFixture /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. + /// Optional. The choices made for the metadata providers of the media library. + /// Optional. The choices made for the artwork providers of the media library. + /// Optional. The choices made for the book readers of the media library. /// The created command. public UpdateLibraryCommand Create( Guid? id = null, - Guid? ownerId = null, string? title = null, string? libraryType = null, string[]? contentLocations = null, @@ -51,11 +52,13 @@ public class UpdateLibraryCommandFixture bool isContentOnSsd = false, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, - LibraryPathTemplatePartDto[]? pathTemplateParts = null) + LibraryPathTemplatePartDto[]? pathTemplateParts = null, + LibraryProviderSelectionDto[]? metadataProviders = null, + LibraryProviderSelectionDto[]? artworkProviders = null, + LibraryProviderSelectionDto[]? bookReaders = null) { return new Faker() .CustomInstantiator(f => new UpdateLibraryCommand( - default, default, default!, default!, @@ -69,10 +72,12 @@ public class UpdateLibraryCommandFixture false, shouldTrackConsumptionProgress, completionThresholdPercentage, + null, + null, + null, null )) .RuleFor(x => x.Id, id ?? Guid.NewGuid()) - .RuleFor(x => x.OwnerId, ownerId ?? Guid.NewGuid()) .RuleFor(x => x.Title, f => title ?? f.Lorem.Word()) .RuleFor(x => x.LibraryType, f => libraryType ?? f.Random.Enum().ToString()) .RuleFor(x => x.ContentLocations, f => contentLocations ?? [f.System.DirectoryPath(), f.System.DirectoryPath(), f.System.DirectoryPath()]) @@ -84,6 +89,9 @@ public class UpdateLibraryCommandFixture .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) .RuleFor(x => x.IsContentOnSsd, isContentOnSsd) .RuleFor(x => x.PathTemplateParts, pathTemplateParts) + .RuleFor(x => x.MetadataProviders, metadataProviders) + .RuleFor(x => x.ArtworkProviders, artworkProviders) + .RuleFor(x => x.BookReaders, bookReaders) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs deleted file mode 100644 index 42ecdbc6..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs +++ /dev/null @@ -1,46 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersCommandFixture -{ - /// - /// Creates a random valid command to reorder the artwork providers of a media library. - /// - /// Optional. The Id of the media library whose artwork providers are reordered. - /// Optional. The plugin Ids in the new order. - /// The created command. - public ReorderLibraryArtworkProvidersCommand Create( - Guid? libraryId = null, - IReadOnlyList? pluginIds = null) - { - return new Faker() - .CustomInstantiator(f => new ReorderLibraryArtworkProvidersCommand( - default, - default!)) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]) - .Generate(); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs deleted file mode 100644 index 6855acd8..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs +++ /dev/null @@ -1,44 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersCommandFixture -{ - /// - /// Creates a random valid command to reorder the metadata providers of a media library. - /// - /// Optional. The Id of the media library whose metadata providers are reordered. - /// Optional. The plugin Ids in the new order. - /// The created command. - public ReorderLibraryMetadataProvidersCommand Create(Guid? libraryId = null, IReadOnlyList? pluginIds = null) - { - return new Faker() - .CustomInstantiator(f => new ReorderLibraryMetadataProvidersCommand( - default, - default!)) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]) - .Generate(); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs deleted file mode 100644 index db917fec..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledCommandFixture -{ - /// - /// Creates a random valid command to enable or disable an artwork provider for a media library. - /// - /// Optional. The Id of the media library whose artwork provider is enabled or disabled. - /// Optional. The Id of the plugin providing the artwork. - /// Whether the artwork provider should be enabled for the media library. - /// The created command. - public SetLibraryArtworkProviderEnabledCommand Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool isEnabled = true) - { - return new Faker() - .CustomInstantiator(f => new SetLibraryArtworkProviderEnabledCommand( - default, - default, - true)) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid()) - .RuleFor(x => x.IsEnabled, isEnabled) - .Generate(); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs deleted file mode 100644 index ef39d0f1..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledCommandFixture -{ - /// - /// Creates a random valid command to enable or disable a book reader for a media library. - /// - /// Optional. The Id of the media library whose book reader is enabled or disabled. - /// Optional. The unique identifier of the plugin providing the book reader. - /// Optional. Whether the book reader should be enabled for the media library. - /// The created . - public SetLibraryBookReaderEnabledCommand Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryBookReaderEnabledCommand(libraryId ?? Guid.NewGuid(), pluginId ?? Guid.NewGuid(), isEnabled ?? true); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs deleted file mode 100644 index c640fb2c..00000000 --- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs +++ /dev/null @@ -1,47 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledCommandFixture -{ - /// - /// Creates a random valid command to enable or disable a metadata provider for a media library. - /// - /// Optional. The Id of the media library whose metadata provider is enabled or disabled. - /// Optional. The Id of the plugin providing the metadata. - /// Whether the metadata provider should be enabled for the media library. - /// The created command. - public SetLibraryMetadataProviderEnabledCommand Create(Guid? libraryId = null, Guid? pluginId = null, bool isEnabled = true) - { - return new Faker() - .CustomInstantiator(f => new SetLibraryMetadataProviderEnabledCommand( - default, - default, - true)) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid()) - .RuleFor(x => x.IsEnabled, isEnabled) - .Generate(); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs new file mode 100644 index 00000000..85c9fb5d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available artwork providers are retrieved. + /// The created . + public GetLibraryTypeArtworkProvidersQuery Create(string? libraryType = null) + { + return new GetLibraryTypeArtworkProvidersQuery(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs new file mode 100644 index 00000000..55779a76 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available book readers are retrieved. + /// The created . + public GetLibraryTypeBookReadersQuery Create(string? libraryType = null) + { + return new GetLibraryTypeBookReadersQuery(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs new file mode 100644 index 00000000..50624d95 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available metadata providers are retrieved. + /// The created . + public GetLibraryTypeMetadataProvidersQuery Create(string? libraryType = null) + { + return new GetLibraryTypeMetadataProvidersQuery(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs index c705b5a7..837b1bf3 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs @@ -32,6 +32,9 @@ public class AddLibraryRequestFixture /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. + /// Optional. The choices made for the metadata providers of the media library. + /// Optional. The choices made for the artwork providers of the media library. + /// Optional. The choices made for the book readers of the media library. /// The created . public AddLibraryRequest Create( string? title = null, @@ -46,7 +49,10 @@ public class AddLibraryRequestFixture bool? isContentOnSsd = null, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, - LibraryPathTemplatePartRequest[]? pathTemplateParts = null) + LibraryPathTemplatePartRequest?[]? pathTemplateParts = null, + LibraryProviderSelectionRequest?[]? metadataProviders = null, + LibraryProviderSelectionRequest?[]? artworkProviders = null, + LibraryProviderSelectionRequest?[]? bookReaders = null) { return new AddLibraryRequest( title ?? _faker.Commerce.Department(), @@ -61,7 +67,10 @@ public class AddLibraryRequestFixture isContentOnSsd ?? false, shouldTrackConsumptionProgress, completionThresholdPercentage, - pathTemplateParts + pathTemplateParts, + metadataProviders, + artworkProviders, + bookReaders ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs new file mode 100644 index 00000000..c8787577 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryProviderSelectionRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the provider or reader. + /// Whether the provider or reader is enabled. + /// Whether the choice carries an enabled state. When , the enabled state is . + /// The created . + public LibraryProviderSelectionRequest Create( + Guid? pluginId = null, + bool isEnabled = true, + bool includeIsEnabled = true) + { + return new LibraryProviderSelectionRequest( + pluginId ?? Guid.NewGuid(), + includeIsEnabled ? isEnabled : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs index 44208473..423d02a8 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs @@ -21,7 +21,6 @@ public class UpdateLibraryRequestFixture /// Creates a random valid . /// /// Optional. The Id of the media library to update. - /// Optional. The Id of the user owning the media library. /// Optional. The title of the media library. /// Optional. The type of the media library. /// Optional. The file system paths of the media library content directories. @@ -35,10 +34,12 @@ public class UpdateLibraryRequestFixture /// Optional. Whether the consumption progress of the media library items should be tracked, or not. /// Optional. The percentage of a media library item that must be consumed for its session to be considered completed. /// Optional. The ordered parts of the path template of the media library. + /// Optional. The choices made for the metadata providers of the media library. + /// Optional. The choices made for the artwork providers of the media library. + /// Optional. The choices made for the book readers of the media library. /// The created . public UpdateLibraryRequest Create( Guid? id = null, - Guid? userId = null, string? title = null, string? libraryType = null, string[]? contentLocations = null, @@ -51,11 +52,13 @@ public class UpdateLibraryRequestFixture bool? isContentOnSsd = null, bool? shouldTrackConsumptionProgress = null, int? completionThresholdPercentage = null, - LibraryPathTemplatePartRequest[]? pathTemplateParts = null) + LibraryPathTemplatePartRequest?[]? pathTemplateParts = null, + LibraryProviderSelectionRequest?[]? metadataProviders = null, + LibraryProviderSelectionRequest?[]? artworkProviders = null, + LibraryProviderSelectionRequest?[]? bookReaders = null) { return new UpdateLibraryRequest( id ?? _faker.Random.Guid(), - userId ?? _faker.Random.Guid(), title ?? _faker.Commerce.Department(), libraryType ?? "EBook", contentLocations ?? [_faker.System.DirectoryPath()], @@ -68,7 +71,10 @@ public class UpdateLibraryRequestFixture isContentOnSsd ?? false, shouldTrackConsumptionProgress, completionThresholdPercentage, - pathTemplateParts + pathTemplateParts, + metadataProviders, + artworkProviders, + bookReaders ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs new file mode 100644 index 00000000..d7e7605a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available artwork providers are retrieved. + /// The created . + public GetLibraryTypeArtworkProvidersRequest Create(string? libraryType = null) + { + return new GetLibraryTypeArtworkProvidersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs new file mode 100644 index 00000000..d542f775 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available book readers are retrieved. + /// The created . + public GetLibraryTypeBookReadersRequest Create(string? libraryType = null) + { + return new GetLibraryTypeBookReadersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs new file mode 100644 index 00000000..18ba5f97 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available metadata providers are retrieved. + /// The created . + public GetLibraryTypeMetadataProvidersRequest Create(string? libraryType = null) + { + return new GetLibraryTypeMetadataProvidersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs deleted file mode 100644 index 8c65fa86..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose artwork providers are reordered. - /// Optional. The plugin Ids in the new order. - /// The created . - public ReorderLibraryArtworkProvidersRequest Create( - Guid? libraryId = null, - IReadOnlyList? pluginIds = null) - { - return new ReorderLibraryArtworkProvidersRequest( - libraryId ?? _faker.Random.Guid(), - pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()] - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs deleted file mode 100644 index a740a144..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose metadata providers are reordered. - /// Optional. The plugin Ids in the new order. - /// The created . - public ReorderLibraryMetadataProvidersRequest Create( - Guid? libraryId = null, - IReadOnlyList? pluginIds = null) - { - return new ReorderLibraryMetadataProvidersRequest( - libraryId ?? _faker.Random.Guid(), - pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()] - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs deleted file mode 100644 index cd7f3dbb..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose artwork provider is enabled or disabled. - /// Optional. The Id of the plugin providing the artwork. - /// Optional. Whether the artwork provider should be enabled. - /// The created . - public SetLibraryArtworkProviderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryArtworkProviderEnabledRequest( - libraryId ?? _faker.Random.Guid(), - pluginId ?? _faker.Random.Guid(), - isEnabled ?? _faker.Random.Bool() - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs deleted file mode 100644 index 68cdb841..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose book reader is enabled or disabled. - /// Optional. The unique identifier of the plugin providing the book reader. - /// Optional. Whether the book reader should be enabled for the media library. - /// The created . - public SetLibraryBookReaderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryBookReaderEnabledRequest(libraryId ?? Guid.NewGuid(), pluginId ?? Guid.NewGuid(), isEnabled ?? true); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs deleted file mode 100644 index 2e47ed9c..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose metadata provider is enabled or disabled. - /// Optional. The Id of the plugin providing the metadata. - /// Optional. Whether the metadata provider should be enabled. - /// The created . - public SetLibraryMetadataProviderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryMetadataProviderEnabledRequest( - libraryId ?? _faker.Random.Guid(), - pluginId ?? _faker.Random.Guid(), - isEnabled ?? _faker.Random.Bool() - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs index 4fcd5780..896eda2f 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs @@ -31,7 +31,6 @@ public class LibraryDtoFixture return new LibraryDto { Id = id ?? Guid.NewGuid(), - UserId = Guid.NewGuid(), Title = title ?? _faker.Commerce.Department(), LibraryType = libraryType ?? _faker.PickRandom("Book", "Video", "Photo"), CoverImage = _faker.Image.PicsumUrl(), diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs new file mode 100644 index 00000000..6f631a1f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryProviderSelectionDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the provider or reader. + /// Optional. Whether the provider or reader is enabled. + /// Whether the choice carries an enabled state. When , the enabled state is . + /// The created . + public LibraryProviderSelectionDto Create( + Guid? pluginId = null, + bool? isEnabled = null, + bool includeIsEnabled = true) + { + return new LibraryProviderSelectionDto + { + PluginId = pluginId ?? Guid.NewGuid(), + IsEnabled = includeIsEnabled ? isEnabled ?? _faker.Random.Bool() : null + }; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs new file mode 100644 index 00000000..c93cdf6f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available artwork providers are retrieved. + /// The created . + public GetLibraryTypeArtworkProvidersRequest Create( + string? libraryType = null) + { + return new GetLibraryTypeArtworkProvidersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs new file mode 100644 index 00000000..4acb383a --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available book readers are retrieved. + /// The created . + public GetLibraryTypeBookReadersRequest Create( + string? libraryType = null) + { + return new GetLibraryTypeBookReadersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs new file mode 100644 index 00000000..2634e21f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available metadata providers are retrieved. + /// The created . + public GetLibraryTypeMetadataProvidersRequest Create( + string? libraryType = null) + { + return new GetLibraryTypeMetadataProvidersRequest(libraryType ?? "Book"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs deleted file mode 100644 index d0cb7a97..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional identifier of the media library. - /// Optional plugin Ids in the new order. - /// A configured instance. - public ReorderLibraryArtworkProvidersRequest Create( - Guid? libraryId = null, - List? pluginIds = null) - { - return new ReorderLibraryArtworkProvidersRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginIds: pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()] - ); - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs deleted file mode 100644 index c52dcdfc..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional identifier of the media library. - /// Optional plugin Ids in the new order. - /// A configured instance. - public ReorderLibraryMetadataProvidersRequest Create( - Guid? libraryId = null, - List? pluginIds = null) - { - return new ReorderLibraryMetadataProvidersRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginIds: pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()] - ); - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs deleted file mode 100644 index 3e1047c5..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs +++ /dev/null @@ -1,45 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The Id of the media library whose book reader is enabled or disabled. - /// Optional. The unique identifier of the plugin providing the book reader. - /// Optional. Whether the book reader should be enabled for the media library. - /// The created . - public SetBookReaderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetBookReaderEnabledRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginId: pluginId ?? Guid.NewGuid(), - IsEnabled: isEnabled ?? true - ); - } - - /// - /// Creates a list of . - /// - /// The number of elements to create. - /// The created list. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs deleted file mode 100644 index db568e49..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional identifier of the media library. - /// Optional identifier of the plugin. - /// Optional value indicating whether the artwork provider is enabled. - /// A configured instance. - public SetLibraryArtworkProviderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryArtworkProviderEnabledRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginId: pluginId ?? Guid.NewGuid(), - IsEnabled: isEnabled ?? _faker.Random.Bool() - ); - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs deleted file mode 100644 index fdf26cb3..00000000 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledRequestFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional identifier of the media library. - /// Optional identifier of the plugin. - /// Optional value indicating whether the metadata provider is enabled. - /// A configured instance. - public SetLibraryMetadataProviderEnabledRequest Create( - Guid? libraryId = null, - Guid? pluginId = null, - bool? isEnabled = null) - { - return new SetLibraryMetadataProviderEnabledRequest( - LibraryId: libraryId ?? Guid.NewGuid(), - PluginId: pluginId ?? Guid.NewGuid(), - IsEnabled: isEnabled ?? _faker.Random.Bool() - ); - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs index da59de5a..c89d7987 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Seed; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Infrastructure.Core.Security; using Microsoft.Extensions.DependencyInjection; using System; @@ -33,6 +35,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable PropertyNameCaseInsensitive = true }; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); private readonly LoginRequestFixture _loginRequestFixture = new(); /// @@ -43,17 +47,18 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable /// /// Creates an HTTP client with authentication headers and a test user /// + /// The permissions granted directly to the test user, if any. /// An HTTP client configured with auth headers - public async Task CreateAuthenticatedClientAsync() + public async Task CreateAuthenticatedClientAsync(params AuthorizationPermission[] permissions) { HttpClient client = CreateClient(); TestUsername = $"testuser_{Guid.NewGuid()}"; - // add the X-Forwarded-For header + // Add the X-Forwarded-For header. client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}"); - // perform authentication - await CreateAndAuthenticateUser(client); + // Perform authentication. + await CreateAndAuthenticateUser(client, permissions); return client; } @@ -62,20 +67,23 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable /// Creates and authenticates a test user. /// /// The HTTP client to configure with auth. + /// The permissions granted directly to the test user. /// The created user entity. - private async Task CreateAndAuthenticateUser(HttpClient client) + private async Task CreateAndAuthenticateUser(HttpClient client, AuthorizationPermission[] permissions) { using IServiceScope scope = Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - // create test user + // Create test user, with the permissions granted directly to it. UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!")); user.TotpSecret = null; + foreach (AuthorizationPermission permission in permissions) + user.UserPermissions.Add(_userPermissionEntityFixture.Create(user, _permissionEntityFixture.Create(permissionName: permission, createdBy: user.Id))); dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - // authenticate user + // Authenticate user. LoginRequest loginRequest = _loginRequestFixture.Create( username: user.Username, password: "TestPass123!", @@ -86,7 +94,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - // set auth header for subsequent requests + // Set auth header for subsequent requests. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); return user; @@ -101,11 +109,11 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable HttpClient client = CreateClient(); TestUsername = $"testuser_{Guid.NewGuid()}"; - // add the X-Forwarded-For header + // Add the X-Forwarded-For header. client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}"); - // create and authenticate admin user + // Create and authenticate admin user. await CreateAndAuthenticateAdminUser(client); return client; @@ -122,20 +130,20 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService(); - // create test user + // Create test user. UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!")); user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - // set up admin permissions and roles + // Set up admin permissions and roles. await dataSeedService.SetDefaultAuthorizationPermissionsAsync(user.Id, CancellationToken.None); await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None); await dataSeedService.SetAdminRolePermissionsAsync(user.Id, CancellationToken.None); await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None); - // authenticate user + // Authenticate user. LoginRequest loginRequest = _loginRequestFixture.Create( username: user.Username, password: "TestPass123!", @@ -146,7 +154,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - // set auth header for subsequent requests + // Set auth header for subsequent requests. client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); return user; diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs index e8f615d3..a4f62d7c 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -10,6 +10,7 @@ using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -32,6 +33,7 @@ public class AddLibraryEndpointTests : IClassFixture candidate.Title == title)); } + [Fact] + public async Task AddLibrary_WhenAProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnValidationProblemAndNotPersist() + { + // Arrange + string title = "Unsupported Provider Library"; + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + metadataProviders: [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + await AssertValidationProblemAsync(response, "PluginNotSupportedForLibraryType"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + + [Fact] + public async Task AddLibrary_WhenAProviderChoiceIsNull_ShouldReturnValidationProblemAndNotPersist() + { + // Arrange + string title = "Null Provider Choice Library"; + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + bookReaders: [null] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + await AssertValidationProblemAsync(response, "PluginIdCannotBeEmpty"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + + [Fact] + public async Task AddLibrary_WhenAPathTemplatePartIsNull_ShouldReturnValidationProblemAndNotPersist() + { + // Arrange + string title = "Null Path Template Part Library"; + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + pathTemplateParts: [null] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + await AssertValidationProblemAsync(response, "PathTemplatePartKindNotSupportedForLibraryType"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + + [Fact] + public async Task AddLibrary_WhenProviderPluginIdsAreDuplicated_ShouldReturnValidationProblemAndNotPersist() + { + // Arrange + string title = "Duplicated Provider Library"; + Guid pluginId = Guid.NewGuid(); + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + bookReaders: [_libraryProviderSelectionRequestFixture.Create(pluginId: pluginId), _libraryProviderSelectionRequestFixture.Create(pluginId: pluginId, isEnabled: false)] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + await AssertValidationProblemAsync(response, "PluginIdsMustBeUnique"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + + [Fact] + public async Task AddLibrary_WhenProviderChoicesAreEmpty_ShouldCreateLibrary() + { + // Arrange + string title = "Empty Provider Choices Library"; + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: title, + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null, + metadataProviders: [], + artworkProviders: [], + bookReaders: [] + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.True(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title)); + } + /// /// Asserts that carries the standard validation problem of the add library route. /// @@ -395,12 +519,12 @@ public class AddLibraryEndpointTests : IClassFixture(); - // clear junction tables first + // Clear junction tables first. await dbContext.Set().ExecuteDeleteAsync(); await dbContext.Set().ExecuteDeleteAsync(); await dbContext.Set().ExecuteDeleteAsync(); - // then clear main tables + // Then clear main tables. await dbContext.Set().ExecuteDeleteAsync(); await dbContext.Set().ExecuteDeleteAsync(); await dbContext.Set().ExecuteDeleteAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index c55d61f2..0bf11ce0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -54,7 +55,7 @@ public class DeleteLibraryEndpointTests : IClassFixture public async Task InitializeAsync() { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); + _client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries); } [Fact] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index d73469a3..7ce5c05b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -41,6 +42,7 @@ public class UpdateLibraryEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -57,7 +59,7 @@ public class UpdateLibraryEndpointTests : IClassFixture public async Task InitializeAsync() { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); + _client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries); } [Fact] @@ -69,7 +71,6 @@ public class UpdateLibraryEndpointTests : IClassFixture(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Original Title", storedLibrary!.Title); + } + + [Fact] + public async Task UpdateLibrary_WhenProviderChoicesAreEmpty_ShouldUpdateTheLibrary() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + title: "Updated Title", + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null, + shouldTrackConsumptionProgress: true, + completionThresholdPercentage: 70, + metadataProviders: [], + artworkProviders: [], + bookReaders: [] + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + response.EnsureSuccessStatusCode(); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Updated Title", storedLibrary!.Title); + } + /// /// Asserts that carries the standard validation problem of the update library route. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..f8e83eea --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType) + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + List? providers = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(providers); + // The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled. + Assert.All(providers!, provider => Assert.False(provider.IsEnabled)); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult() + { + // Arrange + string libraryType = "NotARealLibraryType"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/artwork-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..ea4ab772 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeBookReadersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableReaders(string libraryType) + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + List? readers = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(readers); + // The test host loads no plugins, so no reader supports the type; every reader that is returned starts disabled. + Assert.All(readers!, reader => Assert.False(reader.IsEnabled)); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult() + { + // Arrange + string libraryType = "NotARealLibraryType"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/book-readers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..73af45cb --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType) + { + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + List? providers = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(providers); + // The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled. + Assert.All(providers!, provider => Assert.False(provider.IsEnabled)); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult() + { + // Arrange + string libraryType = "NotARealLibraryType"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/metadata-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs deleted file mode 100644 index 6887dc59..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs +++ /dev/null @@ -1,140 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public ReorderLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task ReorderLibraryArtworkProviders_WhenCalledWithValidData_ShouldReorderTheProviders() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginIdA = Guid.NewGuid(); - Guid pluginIdB = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1); - await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2); - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [pluginIdB, pluginIdA] - ); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - List configurations = await dbContext.LibraryArtworkProviderConfigurations - .Where(config => config.LibraryId == libraryId) - .OrderBy(config => config.Rank) - .ToListAsync(); - Assert.Equal(2, configurations.Count); - Assert.Equal(pluginIdB, configurations[0].PluginId); - Assert.Equal(1, configurations[0].Rank); - Assert.Equal(pluginIdA, configurations[1].PluginId); - Assert.Equal(2, configurations[1].Rank); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a in the database. - /// - /// The Id of the media library. - /// The Id of the plugin. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs deleted file mode 100644 index e71c05ac..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,140 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public ReorderLibraryMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task ReorderLibraryMetadataProviders_WhenCalledWithValidData_ShouldReorderTheProviders() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginIdA = Guid.NewGuid(); - Guid pluginIdB = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1); - await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2); - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [pluginIdB, pluginIdA] - ); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - List configurations = await dbContext.LibraryMetadataProviderConfigurations - .Where(config => config.LibraryId == libraryId) - .OrderBy(config => config.Rank) - .ToListAsync(); - Assert.Equal(2, configurations.Count); - Assert.Equal(pluginIdB, configurations[0].PluginId); - Assert.Equal(1, configurations[0].Rank); - Assert.Equal(pluginIdA, configurations[1].PluginId); - Assert.Equal(2, configurations[1].Rank); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a in the database. - /// - /// The Id of the media library. - /// The Id of the plugin. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs deleted file mode 100644 index a8d33410..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,156 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryArtworkProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task SetLibraryArtworkProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - Assert.Equal(1, configuration.Rank); - } - - [Fact] - public async Task SetLibraryArtworkProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a in the database. - /// - /// The Id of the media library. - /// The Id of the plugin. - /// Whether the provider is enabled. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 5d6bfd50..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,199 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - private readonly UserEntityFixture _userEntityFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryBookReaderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenNoConfigurationExists_ShouldCreateIt() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryBookReaderConfigurationEntity? configuration = await dbContext.LibraryBookReaderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryBookReaderConfigurationEntity configuration = await dbContext.LibraryBookReaderConfigurations - .SingleAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.True(configuration.IsEnabled); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenLibraryIsNotOwned_ShouldReturnForbidden() - { - // Arrange - Guid otherUserId = await SeedOtherUserAsync(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, otherUserId); - Guid pluginId = Guid.NewGuid(); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - HttpClient unauthenticatedClient = _apiFactory.CreateClient(); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - - /// - /// Seeds a library owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary.LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a book reader configuration for the library and plugin. - /// - /// The Id of the library. - /// The Id of the plugin. - /// Whether the book reader is enabled. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryBookReaderConfigurations.Add(_libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a user that is not the authenticated one and returns its Id. - /// - /// The Id of the seeded user. - private async Task SeedOtherUserAsync() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid userId = Guid.NewGuid(); - dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); - await dbContext.SaveChangesAsync(); - return userId; - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index 0eb07d2a..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,156 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime -{ - private HttpClient _client; - private readonly AuthenticatedLuminaApiFactory _apiFactory; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryMetadataProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - _apiFactory = apiFactory; - } - - /// - /// Initializes authenticated API client. - /// - public async Task InitializeAsync() - { - _client = await _apiFactory.CreateAuthenticatedClientAsync(); - } - - [Fact] - public async Task SetLibraryMetadataProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - Assert.Equal(1, configuration.Rank); - } - - [Fact] - public async Task SetLibraryMetadataProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - Guid userId = GetCurrentUserId(); - Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - Guid pluginId = Guid.NewGuid(); - await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations - .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); - Assert.NotNull(configuration); - Assert.True(configuration!.IsEnabled); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a in the database. - /// - /// The Id of the media library. - /// The Id of the plugin. - /// Whether the provider is enabled. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled)); - await dbContext.SaveChangesAsync(); - } - - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - - /// - /// Disposes API factory resources. - /// - public async Task DisposeAsync() - { - await _apiFactory.RemoveTestUserAsync(); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..483c38ec --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + LibraryArtworkProviderDto[] expectedProviders = + [ + _libraryArtworkProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false) + ]; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", expectedProviders); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(1, data.GetArrayLength()); + Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString()); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenCalled_ShouldRequestProvidersFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains($"libraries/artwork-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..a7a62af6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenCalledByAuthenticatedUser_ShouldReturnBookReadersJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + LibraryBookReaderDto[] expectedReaders = + [ + _libraryBookReaderDtoFixture.Create(name: "EPUB Reader", isEnabled: false) + ]; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", expectedReaders); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(1, data.GetArrayLength()); + Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString()); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenCalled_ShouldRequestBookReadersFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains($"libraries/book-readers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..49f27f3b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + LibraryMetadataProviderDto[] expectedProviders = + [ + _libraryMetadataProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false) + ]; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", expectedProviders); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(1, data.GetArrayLength()); + Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString()); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenCalled_ShouldRequestProvidersFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string libraryType = "Book"; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains($"libraries/metadata-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs index af5eeff6..0095e77d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -1,7 +1,10 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -17,6 +20,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage public class LibrariesIndexViewEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -44,8 +48,8 @@ public class LibrariesIndexViewEndpointTests : IClassFixture } [Theory] - [InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // plain page - [InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // query string is kept + [InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // Plain page. + [InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // Query string is kept. public async Task LibrariesIndexView_WhenNavigatedToWithoutAuthentication_ShouldRedirectToLoginWithRequestedPageAsReturnUrl(string requestedUrl, string expectedEncodedReturnUrl) { // Arrange @@ -60,4 +64,45 @@ public class LibrariesIndexViewEndpointTests : IClassFixture Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal($"http://localhost/en-us/auth/login?returnUrl={expectedEncodedReturnUrl}", response.Headers.Location!.ToString()); } + + [Theory] + [InlineData("User", true, "true")] // The permission lets a user manage the libraries they own. + [InlineData("User", false, "false")] // Without the permission, a user cannot change even the libraries they own. + [InlineData("Admin", false, "true")] // An administrator can manage every library, with or without the permission. + public async Task LibrariesIndexView_WhenRendered_ShouldOfferTheEditAndDeleteActionsOnlyToUsersAllowedToManageLibraries(string role, bool hasManagePermission, string expectedCanManageLibraries) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create( + userId: Guid.NewGuid(), + role: role, + permissions: hasManagePermission ? [AuthorizationPermission.CanCreateLibraries] : []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains($"const canManageLibraries = {expectedCanManageLibraries};", content); + } + + [Fact] + public async Task LibrariesIndexView_WhenRenderedInACultureWithNonAsciiLabels_ShouldInjectTheScriptLabelsAsJson() + { + // Arrange + // Razor would encode the non-ASCII letters of a raw label as HTML entities, which the browser shows literally inside a script, while JSON escapes them + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/ro-ro/libraries/manage"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("\"LibraryDeleted\":\"Biblioteca a fost \\u0219tears\\u0103!\"", content); + Assert.DoesNotContain("ștears", content); + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs deleted file mode 100644 index 940c6cf0..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderArtworkProviders; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderArtworkProvidersEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public ReorderArtworkProvidersEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task ReorderArtworkProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [firstPluginId, secondPluginId] - ); - string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/reorder"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-artwork-providers") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs deleted file mode 100644 index 059ebed5..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderMetadataProviders; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderMetadataProvidersEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task ReorderMetadataProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [firstPluginId, secondPluginId] - ); - string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/reorder"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index 121701e4..f06d0cc4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -64,6 +64,43 @@ public class SaveLibraryEndpointTests : IClassFixture Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); } + [Fact] + public async Task SaveLibrary_WhenAProviderChoiceHasNoEnabledState_ShouldForwardItWithoutAState() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid pluginId = Guid.NewGuid(); + LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"); + request.Id = null; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + // The choice is sent without its enabled state, the way a caller that only reorders the providers would send it. + HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") + { + Content = JsonContent.Create(new + { + request.Title, + request.LibraryType, + request.ContentLocations, + MetadataProviders = new[] { new { PluginId = pluginId } } + }) + }; + saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + response.EnsureSuccessStatusCode(); + (string _, object? data) = Assert.Single(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + LibraryDto forwardedLibrary = Assert.IsType(data); + LibraryProviderSelectionDto forwardedChoice = Assert.Single(forwardedLibrary.MetadataProviders!); + Assert.Equal(pluginId, forwardedChoice.PluginId); + Assert.Null(forwardedChoice.IsEnabled); + } + [Fact] public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest() { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs deleted file mode 100644 index 2a2c9995..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetArtworkProviderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetArtworkProviderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetArtworkProviderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetArtworkProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create( - libraryId: libraryId, - pluginId: pluginId, - isEnabled: true - ); - string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-artwork-provider-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 11aa7902..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Common; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetBookReaderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableReaderAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - string expectedEndpoint = $"libraries/{libraryId}/book-readers/{pluginId}/enabled"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } - - [Fact] - public async Task SetBookReaderEnabled_WhenNotAuthenticated_ShouldRedirectToLogin() - { - // Arrange - HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - // Act - HttpResponseMessage response = await anonymousClient.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index ad6752ac..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; - -/// -/// Contains integration tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetMetadataProviderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetMetadataProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create( - libraryId: libraryId, - pluginId: pluginId, - isEnabled: true - ); - string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - using JsonDocument json = JsonDocument.Parse(content); - Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs index 659b8547..b16c27a1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs @@ -9,6 +9,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Common.Interceptors; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.Security; using Microsoft.AspNetCore.Authentication.JwtBearer; @@ -45,6 +46,8 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable private readonly UserEntityFixture _userEntityFixture = new(); private readonly RoleEntityFixture _roleEntityFixture = new(); private readonly UserRoleEntityFixture _userRoleEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; @@ -55,11 +58,11 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable /// public LuminaApiFactory() { - // each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another; + // Each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another; // the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection, - // which would otherwise serialize every request on one connection and cause nested transaction errors between requests + // which would otherwise serialize every request on one connection and cause nested transaction errors between requests. _sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid()); - // keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped + // Keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped. _connection = new SqliteConnection(_sharedInMemoryConnectionString); _connection.Open(); } @@ -202,6 +205,40 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable return (userId, username); } + /// + /// Creates a test user that holds a single permission directly, authenticates it on , and returns its Id and username. + /// + /// The HTTP client to configure with authentication headers. + /// The permission granted to the created user. + /// The Id and username of the created test user. + public async Task<(Guid UserId, string Username)> CreateAndAuthenticateUserWithPermissionAsync(HttpClient client, AuthorizationPermission permission) + { + // A unique X-Forwarded-For isolates rate limiting state per test. + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", GetUniqueTestIp()); + + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + Guid userId = Guid.NewGuid(); + string username = $"testuser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); + + PermissionEntity permissionEntity = _permissionEntityFixture.Create(permissionName: permission); + dbContext.Permissions.Add(permissionEntity); + dbContext.UserPermissions.Add(_userPermissionEntityFixture.Create(user, permissionEntity)); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); + string content = await loginResponse.Content.ReadAsStringAsync(); + LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); + + return (userId, username); + } + /// /// Removes a test user and its owned libraries from the database. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index a400aa53..562f164c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; @@ -60,12 +61,12 @@ public class DeleteLibraryEndpointTests : IClassFixture } [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Libraries--")] // destructive injection + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. public async Task DeleteLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId) { // Arrange - // authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized + // Authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized. HttpClient client = _apiFactory.CreateClient(); Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); await SeedLibraryAsync(userId); @@ -74,10 +75,9 @@ public class DeleteLibraryEndpointTests : IClassFixture HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}"); // Assert - // note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler - // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding - // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) - // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here + // Note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler. + // The observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here). + // That 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here. Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); @@ -86,6 +86,68 @@ public class DeleteLibraryEndpointTests : IClassFixture Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); } + [Fact] + public async Task DeleteLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary() + { + // Arrange + // The created user holds no permission, so it owns the library without being allowed to change it. + HttpClient client = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId)); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + } + + [Fact] + public async Task DeleteLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary() + { + // Arrange + // Ownership and the manage permission are both required, so a user that holds the permission must not delete a library it does not own. + HttpClient client = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + (Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId)); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(attackerUsername); + } + /// /// Seeds a owned by . /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index 2204a24c..d0abcadf 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; @@ -13,6 +14,7 @@ using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http.Json; using System.Text.Json; +using System.Text.Json.Nodes; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary; @@ -49,7 +51,6 @@ public class UpdateLibraryEndpointTests : IClassFixture string libraryId = Guid.NewGuid().ToString(); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: Guid.NewGuid(), - userId: Guid.NewGuid(), title: "Updated Library", libraryType: "EBook", contentLocations: ["C:/Media"], @@ -79,8 +80,8 @@ public class UpdateLibraryEndpointTests : IClassFixture } [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Libraries--")] // destructive injection + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. public async Task UpdateLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle) { // Arrange @@ -90,7 +91,6 @@ public class UpdateLibraryEndpointTests : IClassFixture await SeedLibraryAsync(libraryId, userId); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: libraryId, - userId: userId, title: maliciousTitle, libraryType: "EBook", contentLocations: ["C:/Media"], @@ -106,7 +106,7 @@ public class UpdateLibraryEndpointTests : IClassFixture HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); // Assert - // the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim + // The malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim. Assert.Equal(HttpStatusCode.OK, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); @@ -123,10 +123,10 @@ public class UpdateLibraryEndpointTests : IClassFixture } [Theory] - [InlineData(-1)] // just below the allowed range - [InlineData(101)] // just above the allowed range - [InlineData(int.MinValue)] // lowest possible value - [InlineData(int.MaxValue)] // highest possible value + [InlineData(-1)] // Just below the allowed range. + [InlineData(101)] // Just above the allowed range. + [InlineData(int.MinValue)] // Lowest possible value. + [InlineData(int.MaxValue)] // Highest possible value. public async Task UpdateLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestAndKeepTheStoredSettings(int completionThresholdPercentage) { // Arrange @@ -136,7 +136,6 @@ public class UpdateLibraryEndpointTests : IClassFixture await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: libraryId, - userId: userId, title: "Test Library", libraryType: "EBook", contentLocations: ["C:/Media"], @@ -177,7 +176,6 @@ public class UpdateLibraryEndpointTests : IClassFixture await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: libraryId, - userId: userId, title: "Test Library", libraryType: "EBook", contentLocations: ["C:/Media"], @@ -223,7 +221,6 @@ public class UpdateLibraryEndpointTests : IClassFixture (Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( id: libraryId, - userId: ownerId, title: "Test Library", libraryType: "EBook", contentLocations: ["C:/Media"], @@ -275,6 +272,129 @@ public class UpdateLibraryEndpointTests : IClassFixture await _apiFactory.RemoveTestUserAsync(ownerUsername); } + [Fact] + public async Task UpdateLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary() + { + // Arrange + // Ownership and the manage permission are both required, so a user that holds the permission must not update a library it does not own. + HttpClient client = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, ownerId, title: "Original Title"); + (Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + title: "Updated Title", + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Original Title", storedLibrary!.Title); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(attackerUsername); + } + + [Fact] + public async Task UpdateLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary() + { + // Arrange + // The created user holds no permission, so it owns the library without being allowed to change it. + HttpClient client = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, ownerId, title: "Original Title"); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + title: "Updated Title", + libraryType: "Book", + contentLocations: ["C:/Media"], + coverImage: null + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Original Title", storedLibrary!.Title); + Assert.Equal(LibraryType.EBook, storedLibrary.LibraryType); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + } + + [Fact] + public async Task UpdateLibrary_WhenBodyNamesAnotherOwner_ShouldKeepTheStoredOwner() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, ownerId); + HttpClient client = _apiFactory.CreateClient(); + Guid adminId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + title: "Test Library", + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true + ); + // The request has no owner, so the claimed owner is added to the raw body, the way a crafted request would carry it. + JsonObject body = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject(); + body["userId"] = adminId.ToString(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", body); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal(ownerId, storedLibrary!.UserId); + } + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveAdminUserAsync(adminId); + } + /// /// Asserts that carries the standard validation problem of the update library route. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..c7f32ee1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeArtworkProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryType = "Music"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection. + [InlineData("Music; rm -rf /")] // Command injection. + [InlineData("$(whoami)")] // Command substitution injection. + [InlineData("`whoami`")] // Backtick command injection. + [InlineData("{0}{1}{0}")] // Template/placeholder injection. + [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal. + [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal. + public async Task GetLibraryTypeArtworkProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response + // must stay generic: the failed request leaks no database, filesystem or framework internals. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.StartsWith("/api/v1/libraries/artwork-providers/", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..ea29c351 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeBookReadersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryType = "Music"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection. + [InlineData("Music; rm -rf /")] // Command injection. + [InlineData("$(whoami)")] // Command substitution injection. + [InlineData("`whoami`")] // Backtick command injection. + [InlineData("{0}{1}{0}")] // Template/placeholder injection. + [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal. + [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal. + public async Task GetLibraryTypeBookReaders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response + // must stay generic: the failed request leaks no database, filesystem or framework internals. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.StartsWith("/api/v1/libraries/book-readers/", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..7b5563e3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryTypeMetadataProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryType = "Music"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection. + [InlineData("Music; rm -rf /")] // Command injection. + [InlineData("$(whoami)")] // Command substitution injection. + [InlineData("`whoami`")] // Backtick command injection. + [InlineData("{0}{1}{0}")] // Template/placeholder injection. + [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal. + [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal. + public async Task GetLibraryTypeMetadataProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response + // must stay generic: the failed request leaks no database, filesystem or framework internals. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("UnknownLibraryType", errors!["General.Validation"]); + Assert.StartsWith("/api/v1/libraries/metadata-providers/", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs deleted file mode 100644 index ac511655..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs +++ /dev/null @@ -1,133 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly LuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public ReorderLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task ReorderLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - string libraryId = Guid.NewGuid().ToString(); - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( - libraryId: Guid.NewGuid(), - pluginIds: [Guid.NewGuid()] - ); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", problemDetails["instance"].GetProperty("value").GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Plugins--")] // destructive injection - public async Task ReorderLibraryArtworkProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId) - { - // Arrange - // authenticate with an admin user and seed a library with artwork provider configurations, so valid ids would reach the handler - HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid libraryId = await SeedLibraryAsync(userId); - await SeedConfigurationAsync(libraryId, rank: 1); - await SeedConfigurationAsync(libraryId, rank: 2); - - // Act - // the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization - // before it ever reaches the endpoint handler - HttpResponseMessage response = await client.PutAsJsonAsync( - $"/api/v1/libraries/{libraryId}/artwork-providers/reorder", - new { libraryId, pluginIds = new[] { maliciousPluginId } }); - - // Assert - // note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and - // FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400 - // (pre-existing production bug, not fixed here) - // note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the user that owns the library. - /// The Id of the seeded library. - private async Task SeedLibraryAsync(Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - return libraryId; - } - - /// - /// Seeds a for the library identified by . - /// - /// The Id of the media library. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank)); - await dbContext.SaveChangesAsync(); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs deleted file mode 100644 index d7604735..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,133 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly LuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public ReorderLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task ReorderLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - string libraryId = Guid.NewGuid().ToString(); - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( - libraryId: Guid.NewGuid(), - pluginIds: [Guid.NewGuid()] - ); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", problemDetails["instance"].GetProperty("value").GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Plugins--")] // destructive injection - public async Task ReorderLibraryMetadataProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId) - { - // Arrange - // authenticate with an admin user and seed a library with metadata provider configurations, so valid ids would reach the handler - HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid libraryId = await SeedLibraryAsync(userId); - await SeedConfigurationAsync(libraryId, rank: 1); - await SeedConfigurationAsync(libraryId, rank: 2); - - // Act - // the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization - // before it ever reaches the endpoint handler - HttpResponseMessage response = await client.PutAsJsonAsync( - $"/api/v1/libraries/{libraryId}/metadata-providers/reorder", - new { libraryId = libraryId, pluginIds = new[] { maliciousPluginId } }); - - // Assert - // note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and - // FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400 - // (pre-existing production bug, not fixed here) - // note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the user that owns the library. - /// The Id of the seeded library. - private async Task SeedLibraryAsync(Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - return libraryId; - } - - /// - /// Seeds a for the library identified by . - /// - /// The Id of the media library. - /// The rank of the provider. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, int rank) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank)); - await dbContext.SaveChangesAsync(); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs deleted file mode 100644 index ad92bf3c..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly LuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryArtworkProviderEnabledEndpointTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task SetLibraryArtworkProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - string libraryId = Guid.NewGuid().ToString(); - string pluginId = Guid.NewGuid().ToString(); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Libraries--")] // destructive injection - public async Task SetLibraryArtworkProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) - { - // Arrange - // authenticate with an admin user and seed a library with an artwork provider configuration, so valid ids would reach the handler - HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid libraryId = await SeedLibraryAsync(userId); - await SeedConfigurationAsync(libraryId); - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true); - - // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/artwork-providers/{Guid.NewGuid()}/enabled", request); - - // Assert - // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler - // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding - // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) - // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the user that owns the library. - /// The Id of the seeded library. - private async Task SeedLibraryAsync(Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - return libraryId; - } - - /// - /// Seeds a for the library identified by . - /// - /// The Id of the media library. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false)); - await dbContext.SaveChangesAsync(); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 8a5ccf4c..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,77 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryBookReaderEnabledEndpointTests(LuminaApiFactory apiFactory) - { - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - Assert.DoesNotContain("Exception", content, StringComparison.Ordinal); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE LibraryBookReaderConfigurations--")] // destructive injection - public async Task SetLibraryBookReaderEnabled_WithSQLInjectionInPluginId_ShouldNotLeakDatabaseDetails(string maliciousPluginId) - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: Guid.NewGuid(), pluginId: Guid.NewGuid(), isEnabled: true); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/book-readers/{Uri.EscapeDataString(maliciousPluginId)}/enabled", request); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index 29fe12c0..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.SecurityTests.Common.Setup; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -#endregion - -namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture -{ - private readonly HttpClient _client; - private readonly LuminaApiFactory _apiFactory; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public SetLibraryMetadataProviderEnabledEndpointTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - } - - [Fact] - public async Task SetLibraryMetadataProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() - { - // Arrange - string libraryId = Guid.NewGuid().ToString(); - string pluginId = Guid.NewGuid().ToString(); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - - // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request); - - // Assert - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - - string content = await response.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); - Assert.Equal("Unauthorized", problemDetails["title"].GetString()); - Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString()); - Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); - } - - [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Libraries--")] // destructive injection - public async Task SetLibraryMetadataProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) - { - // Arrange - // authenticate with an admin user and seed a library with a metadata provider configuration, so valid ids would reach the handler - HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid libraryId = await SeedLibraryAsync(userId); - await SeedConfigurationAsync(libraryId); - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true); - - // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/metadata-providers/{Guid.NewGuid()}/enabled", request); - - // Assert - // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler - // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding - // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) - // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Seeds a owned by . - /// - /// The Id of the user that owns the library. - /// The Id of the seeded library. - private async Task SeedLibraryAsync(Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); - await dbContext.SaveChangesAsync(); - return libraryId; - } - - /// - /// Seeds a for the library identified by . - /// - /// The Id of the media library. - /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false)); - await dbContext.SaveChangesAsync(); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs index 90e1620e..fbe67979 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen public class AddLibraryViewEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -39,4 +41,20 @@ public class AddLibraryViewEndpointTests : IClassFixture Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); } + + [Fact] + public async Task AddLibraryView_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/item"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index b0718dd1..ad8bc125 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -17,6 +18,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen public class DeleteLibraryEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -64,6 +66,47 @@ public class DeleteLibraryEndpointTests : IClassFixture Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); } + [Fact] + public async Task DeleteLibrary_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutDeletingTheLibrary() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + + [Fact] + public async Task DeleteLibrary_WhenAnAdministratorLacksTheManagePermission_ShouldForwardTheDeletion() + { + // Arrange + // The API lets administrators delete any library, so the Web must not refuse them for lacking the permission. + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}"); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + /// /// Builds the delete request for the library identified by . /// diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs index 6d9e3879..f39b1aa6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen public class EditLibraryViewEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -41,4 +43,22 @@ public class EditLibraryViewEndpointTests : IClassFixture Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); } + + [Fact] + public async Task EditLibraryView_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutLoadingTheLibrary() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..2b309332 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeArtworkProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("artwork-providers", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. + public async Task GetLibraryTypeArtworkProviders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..065f247d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeBookReaders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("book-readers", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. + public async Task GetLibraryTypeBookReaders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-book-readers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..fe75a189 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryTypeMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("metadata-providers", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("' OR '1'='1")] // Basic SQL injection. + [InlineData("'; DROP TABLE Libraries--")] // Destructive injection. + public async Task GetLibraryTypeMetadataProviders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs deleted file mode 100644 index 2fc62af3..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Headers; -using System.Net.Http.Json; -#endregion - -namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ReorderMetadataProviders; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderMetadataProvidersEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task ReorderMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); - string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - Guid libraryId = Guid.NewGuid(); - HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId); - updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); - - // Act - HttpResponseMessage response = await client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder"); - } - - [Fact] - public async Task ReorderMetadataProviders_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - Guid libraryId = Guid.NewGuid(); - HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder"); - } - - /// - /// Builds the update request that reorders the metadata providers of the library identified by . - /// - /// The Id of the media library. - /// The configured update request. - private HttpRequestMessage CreateUpdateRequest(Guid libraryId) - { - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( - libraryId: libraryId, - pluginIds: [Guid.NewGuid(), Guid.NewGuid()] - ); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - return updateRequest; - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index b47dd931..03761e5f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; @@ -20,6 +22,7 @@ public class SaveLibraryEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -34,7 +37,7 @@ public class SaveLibraryEndpointTests : IClassFixture public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() { // Arrange - _apiFactory.ApiClientStub.Reset(); + ResetApiStub(); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")); @@ -50,7 +53,7 @@ public class SaveLibraryEndpointTests : IClassFixture public async Task SaveLibrary_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequest() { // Arrange - _apiFactory.ApiClientStub.Reset(); + ResetApiStub(); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")); saveRequest.Headers.Remove("RequestVerificationToken"); @@ -64,11 +67,52 @@ public class SaveLibraryEndpointTests : IClassFixture Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); } + [Fact] + public async Task SaveLibrary_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutSaving() + { + // Arrange + ResetApiStub(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + + [Fact] + public async Task SaveLibrary_WhenAnAdministratorLacksTheManagePermission_ShouldForwardTheSave() + { + // Arrange + // The API lets administrators save any library, so the Web must not refuse them for lacking the permission. + ResetApiStub(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"); + request.Id = null; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType)); + HttpRequestMessage saveRequest = CreateSaveRequest(request); + saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries"); + } + [Fact] public async Task SaveLibrary_WhenCalledWithInjectionInLibraryTitle_ShouldRemainSecure() { // Arrange - _apiFactory.ApiClientStub.Reset(); + ResetApiStub(); LibraryDto request = _libraryDtoFixture.Create(title: "'; DROP TABLE Libraries--", libraryType: "Book"); request.Id = null; _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType)); @@ -85,6 +129,18 @@ public class SaveLibraryEndpointTests : IClassFixture Assert.DoesNotContain("Exception", content); } + /// + /// Resets the stubbed API client and restores the authorization state of an administrator with every permission, because the stub is shared by all the tests of the class. + /// + private void ResetApiStub() + { + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create( + userId: Guid.NewGuid(), + role: "Admin", + permissions: Enum.GetValues()); + } + /// /// Builds the save request that sends the given to the library save endpoint. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs deleted file mode 100644 index add45a9f..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,81 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetBookReaderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() - { - // Arrange - HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - // Act - HttpResponseMessage response = await client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); - } - - [Fact] - public async Task SetBookReaderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - string content = await response.Content.ReadAsStringAsync(); - - // Assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index fb13897e..00000000 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System.Diagnostics.CodeAnalysis; -using System.Net; -using System.Net.Http.Headers; -using System.Net.Http.Json; -#endregion - -namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; - -/// -/// Contains security tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetMetadataProviderEnabledEndpointTests : IClassFixture -{ - private readonly LuminaWebFactory _apiFactory; - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - /// Injected Web application factory. - public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory) - { - _apiFactory = apiFactory; - } - - [Fact] - public async Task SetMetadataProviderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); - string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId); - updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); - - // Act - HttpResponseMessage response = await client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"); - } - - [Fact] - public async Task SetMetadataProviderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() - { - // Arrange - _apiFactory.ApiClientStub.Reset(); - AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId); - - // Act - HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); - - // Assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"); - } - - /// - /// Builds the update request that enables the metadata provider of the library identified by and . - /// - /// The Id of the media library. - /// The Id of the plugin providing the metadata. - /// The configured update request. - private HttpRequestMessage CreateUpdateRequest(Guid libraryId, Guid pluginId) - { - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create( - libraryId: libraryId, - pluginId: pluginId, - isEnabled: true - ); - HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled") - { - Content = JsonContent.Create(request) - }; - updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - return updateRequest; - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs index 427a8c83..594d14a9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -1,10 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; @@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; public class AddMediaLibraryRequestMappingTests { private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); + private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new(); private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new(); [Fact] @@ -245,4 +249,85 @@ public class AddMediaLibraryRequestMappingTests Assert.False(result.ShouldTrackConsumptionProgress.Value); Assert.Null(result.CompletionThresholdPercentage); } + + [Fact] + public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder() + { + // Arrange + LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)]; + LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)]; + LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]; + AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + } + + [Fact] + public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Null(result.MetadataProviders); + Assert.Null(result.ArtworkProviders); + Assert.Null(result.BookReaders); + } + + [Fact] + public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId); + Assert.Null(result.MetadataProviders![0].IsEnabled); + Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId); + Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId); + } + + [Fact] + public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: [null]); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!); + Assert.Null(part.Kind); + Assert.Null(part.Representation); + Assert.False(part.IsOptional); + } + + [Fact] + public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull() + { + // Arrange + LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false); + AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [choice]); + + // Act + AddLibraryCommand result = request.ToCommand(); + + // Assert + LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!); + Assert.Equal(choice.PluginId, mappedChoice.PluginId); + Assert.Null(mappedChoice.IsEnabled); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs index 9675c2b9..e160d948 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs @@ -1,10 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; @@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; public class UpdateLibraryRequestMappingTests { private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); + private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new(); private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new(); [Fact] @@ -148,4 +152,85 @@ public class UpdateLibraryRequestMappingTests Assert.False(result.ShouldTrackConsumptionProgress.Value); Assert.Null(result.CompletionThresholdPercentage); } + + [Fact] + public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder() + { + // Arrange + LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)]; + LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)]; + LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]; + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled))); + } + + [Fact] + public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Null(result.MetadataProviders); + Assert.Null(result.ArtworkProviders); + Assert.Null(result.BookReaders); + } + + [Fact] + public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId); + Assert.Null(result.MetadataProviders![0].IsEnabled); + Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId); + Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId); + } + + [Fact] + public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: [null]); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!); + Assert.Null(part.Kind); + Assert.Null(part.Representation); + Assert.False(part.IsOptional); + } + + [Fact] + public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull() + { + // Arrange + LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false); + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [choice]); + + // Act + UpdateLibraryCommand result = request.ToCommand(); + + // Assert + LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!); + Assert.Equal(choice.PluginId, mappedChoice.PluginId); + Assert.Null(mappedChoice.IsEnabled); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs new file mode 100644 index 00000000..79126c8a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersRequestMappingTests +{ + private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music"); + + // Act + GetLibraryTypeArtworkProvidersQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryType, result.LibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs new file mode 100644 index 00000000..76595851 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersRequestMappingTests +{ + private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music"); + + // Act + GetLibraryTypeBookReadersQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryType, result.LibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs new file mode 100644 index 00000000..32629e3b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersRequestMappingTests +{ + private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music"); + + // Act + GetLibraryTypeMetadataProvidersQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryType, result.LibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs deleted file mode 100644 index eb922a18..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersRequestMappingTests -{ - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - - // Act - ReorderLibraryArtworkProvidersCommand result = request.ToCommand(); - - // Assert - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginIds, result.PluginIds); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs deleted file mode 100644 index d88564a1..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersRequestMappingTests -{ - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(Guid.NewGuid(), [Guid.NewGuid(), Guid.NewGuid()]); - - // Act - ReorderLibraryMetadataProvidersCommand result = request.ToCommand(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginIds, result.PluginIds); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs deleted file mode 100644 index b4ce861a..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs +++ /dev/null @@ -1,33 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledRequestMappingTests -{ - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(isEnabled: true); - - // Act - SetLibraryArtworkProviderEnabledCommand result = request.ToCommand(); - - // Assert - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginId, result.PluginId); - Assert.Equal(request.IsEnabled, result.IsEnabled); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs deleted file mode 100644 index cec75047..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs +++ /dev/null @@ -1,34 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledRequestMappingTests -{ - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - - // Act - SetLibraryBookReaderEnabledCommand result = request.ToCommand(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginId, result.PluginId); - Assert.Equal(request.IsEnabled, result.IsEnabled); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs deleted file mode 100644 index 26376d27..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.Plugins; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledRequestMappingTests -{ - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - [Fact] - public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(Guid.NewGuid(), Guid.NewGuid(), true); - - // Act - SetLibraryMetadataProviderEnabledCommand result = request.ToCommand(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.LibraryId); - Assert.Equal(request.PluginId, result.PluginId); - Assert.Equal(request.IsEnabled, result.IsEnabled); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs index ded42481..677d7291 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs @@ -56,6 +56,7 @@ public class AddLibraryCommandHandlerTests private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); private readonly Guid _userId; /// @@ -76,14 +77,14 @@ public class AddLibraryCommandHandlerTests _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully + // Default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.PNG)); _mockLibraryRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); - _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty())); @@ -107,8 +108,8 @@ public class AddLibraryCommandHandlerTests Assert.False(result.IsFailure); Assert.Equal(persistedLibrary.Id, result.Value.Id); await _mockLibraryRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); - await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync( - Arg.Any(), Arg.Is(libraryType => libraryType == Enum.Parse(command.LibraryType)), Arg.Any()); + await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync( + Arg.Any(), Arg.Is(libraryType => libraryType == Enum.Parse(command.LibraryType!)), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Is(true), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); } @@ -157,12 +158,40 @@ public class AddLibraryCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenProviderConfigurationSeedingFails_ShouldReturnErrorWithoutSaving() + public async Task HandleAsync_WhenProviderChoicesAreMade_ShouldConfigureProvidersWithTheChoices() + { + // Arrange + LibraryProviderSelectionDto[] metadataProviders = [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]; + LibraryProviderSelectionDto[] artworkProviders = [_libraryProviderSelectionDtoFixture.Create(isEnabled: false)]; + LibraryProviderSelectionDto[] bookReaders = [_libraryProviderSelectionDtoFixture.Create()]; + AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders); + LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(persistedLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync( + Arg.Any(), + Enum.Parse(command.LibraryType!), + Arg.Is?>(selections => selections == metadataProviders), + Arg.Is?>(selections => selections == artworkProviders), + Arg.Is?>(selections => selections == bookReaders), + Arg.Is(true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfiguringProvidersFails_ShouldReturnErrorWithoutSaving() { // Arrange AddLibraryCommand command = _addLibraryCommandFixture.Create(); - _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure(description: "Failed to seed provider configurations")); + _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to configure provider configurations")); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs index f233599a..d471c6e4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -22,6 +23,7 @@ public class AddLibraryCommandValidatorTests private readonly AddLibraryCommandValidator _validator = new(); private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new(); private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); [Fact] public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() @@ -37,12 +39,14 @@ public class AddLibraryCommandValidatorTests result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); } - [Fact] - public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError() + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) { // Arrange AddLibraryCommand command = _addLibraryCommandFixture.Create(); - command = command with { LibraryType = "UnknownLibraryType" }; + command = command with { LibraryType = libraryType }; // Act List result = _validator.TestValidate(command); @@ -65,6 +69,36 @@ public class AddLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); } + [Theory] + [InlineData("book")] // The casing of the name does not matter. + [InlineData("eBook")] // The casing of the name does not matter. + public void Validate_WhenLibraryTypeDiffersInCasing_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + command = command with { LibraryType = libraryType }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Fact] + public void Validate_WhenLibraryTypeIsTheNumericValueOfADefinedMember_ShouldHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + command = command with { LibraryType = "0" }; // Book + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + [Fact] public void Validate_WhenContentLocationsIsNull_ShouldHaveValidationError() { @@ -220,9 +254,9 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(null)] // an absent kind - [InlineData("")] // an empty kind - [InlineData(" ")] // a whitespace kind + [InlineData(null)] // An absent kind. + [InlineData("")] // An empty kind. + [InlineData(" ")] // A whitespace kind. public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind) { // Arrange @@ -237,9 +271,9 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(null)] // an absent representation - [InlineData("")] // an empty representation - [InlineData(" ")] // a whitespace representation + [InlineData(null)] // An absent representation. + [InlineData("")] // An empty representation. + [InlineData(" ")] // A whitespace representation. public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation) { // Arrange @@ -305,8 +339,8 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(-1)] // just below the allowed range - [InlineData(int.MinValue)] // the lowest possible value + [InlineData(-1)] // Just below the allowed range. + [InlineData(int.MinValue)] // The lowest possible value. public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -323,8 +357,8 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(101)] // just above the allowed range - [InlineData(int.MaxValue)] // the highest possible value + [InlineData(101)] // Just above the allowed range. + [InlineData(int.MaxValue)] // The highest possible value. public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -341,8 +375,8 @@ public class AddLibraryCommandValidatorTests } [Theory] - [InlineData(0)] // the lowest allowed boundary - [InlineData(100)] // the highest allowed boundary + [InlineData(0)] // The lowest allowed boundary. + [InlineData(100)] // The highest allowed boundary. public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -408,4 +442,116 @@ public class AddLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff); result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred); } + + [Fact] + public void Validate_WhenMetadataProviderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMetadataProviderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenArtworkProviderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtworkProviderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + AddLibraryCommand command = _addLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenBookReaderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookReaderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + AddLibraryCommand command = _addLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenProviderChoicesAreValid_ShouldNotHaveProviderValidationErrors() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create( + metadataProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)], + artworkProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)], + bookReaders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenProviderChoicesAreNotProvided_ShouldNotHaveProviderValidationErrors() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs index 7305b45a..fcca21eb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs @@ -14,6 +14,7 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.DeleteLi using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; using System.Collections.Generic; @@ -60,10 +61,12 @@ public class DeleteLibraryCommandHandlerTests _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, the ownership policy allows the deletion, and the provider configurations are removed successfully + // Default stubs: the current user is authenticated, the ownership policy allows the deletion, the user has the manage permission, and the provider configurations are removed successfully. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(true); _mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(Arg.Any(), Arg.Any()) .Returns(Result.Deleted); _mockLibraryRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) @@ -170,6 +173,49 @@ public class DeleteLibraryCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenTheOwnerLacksTheManagePermission_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockProviderConfigurationStore.DidNotReceive().RemoveProviderConfigurationsForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAnAdminWithoutTheManagePermissionDeletesTheLibraryOfAnotherUser_ShouldDeleteIt() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid()); + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(false); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryRepository.Received(1).DeleteByIdAsync(command.Id, Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs index d81846cd..b57afe99 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs @@ -58,6 +58,7 @@ public class UpdateLibraryCommandHandlerTests private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); private readonly Guid _userId; /// @@ -78,15 +79,17 @@ public class UpdateLibraryCommandHandlerTests _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, has the manage permission, the cover image is a valid image, and the provider configurations are reconciled successfully + // Default stubs: the current user is authenticated, owns the library, has the manage permission, the cover image is a valid image, and the provider configurations are configured successfully. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.PNG)); _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); - _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty())); @@ -99,8 +102,8 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryType commandLibraryType = Enum.Parse(command.LibraryType); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryType commandLibraryType = Enum.Parse(command.LibraryType!); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -112,8 +115,8 @@ public class UpdateLibraryCommandHandlerTests Assert.False(result.IsFailure); Assert.Equal(existingLibrary.Id, result.Value.Id); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); - await _mockProviderConfigurationStore.Received(1).ReconcileProviderConfigurationsAsync( - command.Id, Arg.Is(libraryType => libraryType == commandLibraryType), Arg.Any()); + await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync( + command.Id, Arg.Is(libraryType => libraryType == commandLibraryType), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Is(true), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); } @@ -127,7 +130,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: 50); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, shouldTrackConsumptionProgress: false); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -152,7 +155,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Music, shouldTrackConsumptionProgress: false); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) @@ -171,12 +174,34 @@ public class UpdateLibraryCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenLibraryTypeIsUnchanged_ShouldNotReconcileProviderConfigurations() + public async Task HandleAsync_WhenAnAdminUpdatesTheLibraryOfAnotherUser_ShouldKeepTheStoredOwner() + { + // Arrange + Guid ownerId = Guid.NewGuid(); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: ownerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryRepository.Received(1).UpdateAsync( + Arg.Is(library => library.UserId == ownerId), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryTypeIsUnchangedAndNoProviderChoicesAreMade_ShouldNotConfigureProviders() { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - existingLibrary.LibraryType = Enum.Parse(command.LibraryType); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + existingLibrary.LibraryType = Enum.Parse(command.LibraryType!); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -185,21 +210,144 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.False(result.IsFailure); - await _mockProviderConfigurationStore.DidNotReceive().ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()); } [Fact] - public async Task HandleAsync_WhenProviderConfigurationReconciliationFails_ShouldReturnErrorWithoutSaving() + public async Task HandleAsync_WhenProviderChoicesAreMadeAndLibraryTypeIsUnchanged_ShouldConfigureProvidersWithTheChoices() + { + // Arrange + LibraryProviderSelectionDto[] metadataProviders = [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]; + LibraryProviderSelectionDto[] artworkProviders = [_libraryProviderSelectionDtoFixture.Create(isEnabled: false)]; + LibraryProviderSelectionDto[] bookReaders = [_libraryProviderSelectionDtoFixture.Create()]; + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders); + LibraryType commandLibraryType = Enum.Parse(command.LibraryType!); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + existingLibrary.LibraryType = commandLibraryType; + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync( + command.Id, + commandLibraryType, + Arg.Is?>(selections => selections == metadataProviders), + Arg.Is?>(selections => selections == artworkProviders), + Arg.Is?>(selections => selections == bookReaders), + Arg.Is(false), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task HandleAsync_WhenANonOwnerWithTheManagePermissionUpdatesTheLibrary_ShouldReturnNotAuthorizedWithoutChangingAnything(bool hasProviderChoices) + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: hasProviderChoices ? [_libraryProviderSelectionDtoFixture.Create()] : null); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid()); + existingLibrary.LibraryType = Enum.Parse(command.LibraryType!); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync( + Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenANonOwnerWithTheManagePermissionChangesTheLibraryType_ShouldReturnNotAuthorizedWithoutChangingTheConfigurations() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(libraryType: nameof(LibraryType.Book)); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid(), libraryType: LibraryType.Music); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync( + Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheOwnerLacksTheManagePermission_ShouldReturnNotAuthorizedWithoutChangingAnything() { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryType commandLibraryType = Enum.Parse(command.LibraryType); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAnAdminWithoutTheManagePermissionUpdatesTheLibraryOfAnotherUser_ShouldUpdateIt() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid()); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfiguringProvidersFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryType commandLibraryType = Enum.Parse(command.LibraryType!); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); - _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure(description: "Failed to reconcile provider configurations")); + _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to configure provider configurations")); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -215,7 +363,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = null }; - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -234,7 +382,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = "C:/Users/user/cover.jpg" }; - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.CoverImage = null; _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -257,7 +405,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = "C:/Users/user/cover.jpg" }; - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.CoverImage = null; _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -279,7 +427,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = " " }; - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.CoverImage = null; _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -294,12 +442,39 @@ public class UpdateLibraryCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenUserLacksManagePermissionAndCoverImageIsNew_ShouldNotProbeCoverImage() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { CoverImage = @"\\server\share\cover.jpg" }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + existingLibrary.CoverImage = null; + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(false); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockEnvironmentContext.FileTypeService.DidNotReceive() + .GetImageTypeAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCoverImageIsUnchanged_ShouldSkipImageTypeCheck() { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); existingLibrary.CoverImage = command.CoverImage; _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -333,6 +508,28 @@ public class UpdateLibraryCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExistAndUserLacksPermission_ShouldReturnNotFoundWithoutAuthorizing() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) + .Returns(Result.Success(null)); + _mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any()) + .Returns(false); + _mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync( + Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError() { @@ -355,7 +552,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) @@ -395,7 +592,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); command = command with { ContentLocations = [""] }; @@ -415,7 +612,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -434,7 +631,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary), Error.Failure(description: "Failed to retrieve updated library")); @@ -450,7 +647,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary), Result.Success(null)); @@ -486,7 +683,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); LibraryPathPart defaultPart = _libraryPathPartFixture.Create( @@ -524,7 +721,7 @@ public class UpdateLibraryCommandHandlerTests representation: "{0}", isOptional: false); UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [providedDto]); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); LibraryPathPart providedPart = _libraryPathPartFixture.Create( @@ -562,7 +759,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" }; UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -585,7 +782,7 @@ public class UpdateLibraryCommandHandlerTests kind: nameof(LibraryPathPartKind.Artist), representation: "{0}"); UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [validPart]); - LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId); _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType; @@ -611,7 +808,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -641,7 +838,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: 60); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -671,7 +868,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -701,7 +898,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: 50); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -728,7 +925,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Book, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80); @@ -758,7 +955,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: null); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Music, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null); @@ -788,7 +985,7 @@ public class UpdateLibraryCommandHandlerTests completionThresholdPercentage: 65); LibraryEntity existingLibrary = _libraryEntityFixture.Create( id: command.Id, - userId: command.OwnerId, + userId: _userId, libraryType: LibraryType.Music, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs index 572fda36..0a574acf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs @@ -23,6 +23,7 @@ public class UpdateLibraryCommandValidatorTests private readonly UpdateLibraryCommandValidator _validator = new(); private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new(); private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); [Fact] public void Validate_WhenIdIsEmpty_ShouldHaveValidationError() @@ -51,33 +52,6 @@ public class UpdateLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); } - [Fact] - public void Validate_WhenOwnerIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - command = command with { OwnerId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenOwnerIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Users.UserIdCannotBeEmpty); - } - [Fact] public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() { @@ -92,12 +66,14 @@ public class UpdateLibraryCommandValidatorTests result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); } - [Fact] - public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError() + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - command = command with { LibraryType = "UnknownLibraryType" }; + command = command with { LibraryType = libraryType }; // Act List result = _validator.TestValidate(command); @@ -120,6 +96,36 @@ public class UpdateLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); } + [Theory] + [InlineData("book")] // The casing of the name does not matter. + [InlineData("eBook")] // The casing of the name does not matter. + public void Validate_WhenLibraryTypeDiffersInCasing_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { LibraryType = libraryType }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Fact] + public void Validate_WhenLibraryTypeIsTheNumericValueOfADefinedMember_ShouldHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { LibraryType = "0" }; // Book + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + [Fact] public void Validate_WhenContentLocationsIsNull_ShouldHaveValidationError() { @@ -275,9 +281,9 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(null)] // an absent kind - [InlineData("")] // an empty kind - [InlineData(" ")] // a whitespace kind + [InlineData(null)] // An absent kind. + [InlineData("")] // An empty kind. + [InlineData(" ")] // A whitespace kind. public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind) { // Arrange @@ -292,9 +298,9 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(null)] // an absent representation - [InlineData("")] // an empty representation - [InlineData(" ")] // a whitespace representation + [InlineData(null)] // An absent representation. + [InlineData("")] // An empty representation. + [InlineData(" ")] // A whitespace representation. public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation) { // Arrange @@ -360,8 +366,8 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(-1)] // just below the allowed range - [InlineData(int.MinValue)] // the lowest possible value + [InlineData(-1)] // Just below the allowed range. + [InlineData(int.MinValue)] // The lowest possible value. public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -378,8 +384,8 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(101)] // just above the allowed range - [InlineData(int.MaxValue)] // the highest possible value + [InlineData(101)] // Just above the allowed range. + [InlineData(int.MaxValue)] // The highest possible value. public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -396,8 +402,8 @@ public class UpdateLibraryCommandValidatorTests } [Theory] - [InlineData(0)] // the lowest allowed boundary - [InlineData(100)] // the highest allowed boundary + [InlineData(0)] // The lowest allowed boundary. + [InlineData(100)] // The highest allowed boundary. public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage) { // Arrange @@ -463,4 +469,116 @@ public class UpdateLibraryCommandValidatorTests result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff); result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred); } + + [Fact] + public void Validate_WhenMetadataProviderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMetadataProviderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenArtworkProviderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtworkProviderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenBookReaderPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookReaderPluginIdsAreDuplicated_ShouldHaveValidationError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenProviderChoicesAreValid_ShouldNotHaveProviderValidationErrors() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create( + metadataProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)], + artworkProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)], + bookReaders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } + + [Fact] + public void Validate_WhenProviderChoicesAreNotProvided_ShouldNotHaveProviderValidationErrors() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs index 32394ae0..ef3ed900 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs @@ -51,9 +51,10 @@ public class GetLibraryPathTemplatePartsQueryHandlerTests } [Theory] - [InlineData("")] // an absent library type - [InlineData(" ")] // a whitespace library type - [InlineData("NotARealLibraryType")] // an unknown library type + [InlineData("")] // An absent library type. + [InlineData(" ")] // A whitespace library type. + [InlineData("NotARealLibraryType")] // An unknown library type. + [InlineData("999")] // A number that is not a defined library type. public async Task HandleAsync_WhenLibraryTypeIsUnknownOrAbsent_ShouldReturnUnknownLibraryTypeError(string libraryType) { // Arrange diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs deleted file mode 100644 index 30b0c080..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs +++ /dev/null @@ -1,184 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.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.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IValidator _mockValidator; - private readonly ReorderLibraryArtworkProvidersCommandHandler _sut; - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); - private readonly Guid _userId; - - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryArtworkProvidersCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // default stubs: the current user is authenticated and the library ownership policy allows access - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()) - .Returns([]); - _sut = new ReorderLibraryArtworkProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity firstProvider = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); - LibraryArtworkProviderConfigurationEntity secondProvider = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List { firstProvider, secondProvider }); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1), - Arg.Any()); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenAProvidedPluginIsNotConfigured_ShouldSkipIt() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); - Guid unknownPluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List { configuration }); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [unknownPluginId, configuration.PluginId]), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(candidate => candidate.PluginId == configuration.PluginId && candidate.Rank == 2), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() - { - // Arrange - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(Error.Failure(description: "Failed to get configurations")); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs deleted file mode 100644 index cdaa5549..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersCommandValidatorTests -{ - private readonly ReorderLibraryArtworkProvidersCommandValidator _validator = new(); - private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - command = command with { LibraryId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - command = command with { PluginIds = null! }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); - } - - [Fact] - public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - command = command with { PluginIds = [] }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs deleted file mode 100644 index a69c80e9..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ /dev/null @@ -1,144 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.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.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IValidator _mockValidator; - private readonly ReorderLibraryMetadataProvidersCommandHandler _sut; - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new(); - private readonly Guid _userId; - - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryMetadataProvidersCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // default stubs: the current user is authenticated and the library ownership policy allows access - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()) - .Returns([]); - _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntity firstProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); - LibraryMetadataProviderConfigurationEntity secondProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List { firstProvider, secondProvider }); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1), - Arg.Any()); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() - { - // Arrange - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidatorTests.cs deleted file mode 100644 index 8f40ca9a..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidatorTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersCommandValidatorTests -{ - private readonly ReorderLibraryMetadataProvidersCommandValidator _validator = new(); - private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - command = command with { LibraryId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - command = command with { PluginIds = null! }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); - } - - [Fact] - public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - command = command with { PluginIds = [] }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs deleted file mode 100644 index 246bf924..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs +++ /dev/null @@ -1,243 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.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.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IValidator _mockValidator; - private readonly SetLibraryArtworkProviderEnabledCommandHandler _sut; - private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new(); - private readonly Guid _userId; - - /// - /// Fixture for generating test data. - /// - private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryArtworkProviderEnabledCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // default stubs: the current user is authenticated and the library ownership policy allows access - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()) - .Returns([]); - _sut = new SetLibraryArtworkProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns((LibraryArtworkProviderConfigurationEntity?)null); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List()); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 1), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationDoesNotExistAndOthersExist_ShouldAppendAfterTheHighestRank() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns((LibraryArtworkProviderConfigurationEntity?)null); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List - { - _libraryArtworkProviderConfigurationEntityFixture.Create( - libraryId: libraryId, - pluginId: Guid.NewGuid(), - rank: 3, - isEnabled: true) - }); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: false), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => !configuration.IsEnabled && configuration.Rank == 4), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - LibraryArtworkProviderConfigurationEntity existingConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create( - libraryId: Guid.NewGuid(), - pluginId: Guid.NewGuid(), - rank: 2, - isEnabled: false); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any()) - .Returns(existingConfiguration); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), - Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() - { - // Arrange - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenGetByLibraryAndPluginIdFails_ShouldReturnError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns(Error.Failure(description: "Failed to get configuration")); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUpsertFails_ShouldReturnError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns((LibraryArtworkProviderConfigurationEntity?)null); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List()); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Error.Failure(description: "Failed to upsert configuration")); - - // Act - Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs deleted file mode 100644 index df6d5a97..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledCommandValidatorTests -{ - private readonly SetLibraryArtworkProviderEnabledCommandValidator _validator = new(); - private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - command = command with { LibraryId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - command = command with { PluginId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs deleted file mode 100644 index 45b02578..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandlerTests.cs +++ /dev/null @@ -1,210 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.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.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryBookReaderConfigurationRepository _mockLibraryBookReaderConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IBookReaderEnablementCache _mockEnablementCache; - private readonly IValidator _mockValidator; - private readonly SetLibraryBookReaderEnabledCommandHandler _sut; - private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new(); - private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new(); - private readonly Guid _userId; - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryBookReaderEnabledCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockLibraryBookReaderConfigurationRepository = Substitute.For(); - _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockEnablementCache = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // Default stubs: the current user is authenticated and the library ownership policy allows access. - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()).Returns([]); - _mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - _sut = new SetLibraryBookReaderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockEnablementCache, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldInsertNewConfigurationAndPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: false); - _mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any()) - .Returns(Result.From(null)); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => - configuration.LibraryId == command.LibraryId && - configuration.PluginId == command.PluginId && - configuration.IsEnabled == command.IsEnabled), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - _mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledStateAndPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: true); - LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create( - libraryId: command.LibraryId, - pluginId: command.PluginId, - isEnabled: false); - _mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any()) - .Returns(Result.From(existingConfiguration)); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.True(existingConfiguration.IsEnabled); - await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync(existingConfiguration, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - _mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId); - } - - [Fact] - public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenGetConfigurationFails_ShouldReturnErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - Error error = Error.Failure(description: "Failed to get configuration"); - _mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any()) - .Returns(error); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotPersist() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - Error error = Error.Failure(description: "Failed to upsert configuration"); - _mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any()) - .Returns(Result.From(null)); - _mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(error); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(error, result.FirstError); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - _mockEnablementCache.DidNotReceive().Invalidate(Arg.Any(), Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidatorTests.cs deleted file mode 100644 index 2d8b82d1..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandValidatorTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryBookReaderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledCommandValidatorTests -{ - private readonly SetLibraryBookReaderEnabledCommandValidator _validator = new(); - private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(libraryId: Guid.Empty); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(pluginId: Guid.Empty); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs deleted file mode 100644 index d53f845c..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ /dev/null @@ -1,172 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.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.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using ApplicationErrors = Lumina.Application.Common.Errors.Errors; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledCommandHandlerTests -{ - private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; - private readonly IAuthorizationService _mockAuthorizationService; - private readonly ICurrentUserService _mockCurrentUserService; - private readonly IValidator _mockValidator; - private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut; - private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new(); - private readonly Guid _userId; - - /// - /// Fixture for generating test data. - /// - private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryMetadataProviderEnabledCommandHandlerTests() - { - _mockUnitOfWork = Substitute.For(); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockConfigurationRepository = Substitute.For(); - _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockAuthorizationService = Substitute.For(); - _mockCurrentUserService = Substitute.For(); - _mockValidator = Substitute.For>(); - _userId = Guid.NewGuid(); - - // default stubs: the current user is authenticated and the library ownership policy allows access - _mockCurrentUserService.UserId.Returns(_userId); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(true); - _mockValidator.Validate(Arg.Any()) - .Returns([]); - _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) - .Returns((LibraryMetadataProviderConfigurationEntity?)null); - _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(new List()); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 1), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() - { - // Arrange - LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create( - libraryId: Guid.NewGuid(), - pluginId: Guid.NewGuid(), - rank: 2, - isEnabled: false); - _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any()) - .Returns(existingConfiguration); - _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockConfigurationRepository.Received(1).UpsertAsync( - Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), - Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - Guid pluginId = Guid.NewGuid(); - _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) - .Returns(false); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() - { - // Arrange - _mockCurrentUserService.UserId.Returns((Guid?)null); - - // Act - Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(), CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidatorTests.cs deleted file mode 100644 index 15c0aa5c..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidatorTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Application.UnitTests.Common.Setup; -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledCommandValidatorTests -{ - private readonly SetLibraryMetadataProviderEnabledCommandValidator _validator = new(); - private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new(); - - [Fact] - public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - command = command with { LibraryId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - command = command with { PluginId = Guid.Empty }; - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() - { - // Arrange - SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create(); - - // Act - List result = _validator.TestValidate(command); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandlerTests.cs new file mode 100644 index 00000000..9f25ef79 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryHandlerTests.cs @@ -0,0 +1,184 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; + private readonly IValidator _mockValidator; + private readonly GetLibraryTypeArtworkProvidersQueryHandler _sut; + private readonly GetLibraryTypeArtworkProvidersQueryFixture _getLibraryTypeArtworkProvidersQueryFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockCurrentUserService = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); + _mockValidator = Substitute.For>(); + + // Default stubs: the query is valid, the current user is authenticated, no plugin supports the library type, and no plugin is detected. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(Guid.NewGuid()); + _mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(Arg.Any()).Returns([]); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); + + _sut = new GetLibraryTypeArtworkProvidersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.UnknownLibraryType]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.UnknownLibraryType, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedArtworkProviderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedArtworkProviderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPluginsSupportTheLibraryType_ShouldReturnThemDisabledAndRankedInTheSupportedOrder() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(LibraryType.Book).Returns([alphaPluginId, betaPluginId]); + List plugins = [_pluginEntityFixture.Create(betaPluginId, "Beta"), _pluginEntityFixture.Create(alphaPluginId, "Alpha")]; + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(new LibraryArtworkProviderResponse(alphaPluginId, "Alpha", false, 1), result.Value[0]); + Assert.Equal(new LibraryArtworkProviderResponse(betaPluginId, "Beta", false, 2), result.Value[1]); + } + + [Fact] + public async Task HandleAsync_WhenLibraryTypeCasingDiffers_ShouldStillResolveTheLibraryType() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: "music"); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockProviderConfigurationStore.Received(1).GetSupportedArtworkProviderPluginIds(LibraryType.Music); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid unknownPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(LibraryType.Book).Returns([unknownPluginId]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + } + + [Fact] + public async Task HandleAsync_WhenNoPluginSupportsTheLibraryType_ShouldReturnEmptyList() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get plugins"); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidatorTests.cs new file mode 100644 index 00000000..2a08a287 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryValidatorTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersQueryValidatorTests +{ + private readonly GetLibraryTypeArtworkProvidersQueryValidator _validator = new(); + private readonly GetLibraryTypeArtworkProvidersQueryFixture _getLibraryTypeArtworkProvidersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create() with { LibraryType = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + } + + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + [InlineData("0")] // The numeric value of a defined library type, which is not a member name. + [InlineData("")] // Empty. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandlerTests.cs new file mode 100644 index 00000000..4bd8855e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryHandlerTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Reading; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; + private readonly IBookReaderRegistry _mockBookReaderRegistry; + private readonly IValidator _mockValidator; + private readonly GetLibraryTypeBookReadersQueryHandler _sut; + private readonly GetLibraryTypeBookReadersQueryFixture _getLibraryTypeBookReadersQueryFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockCurrentUserService = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); + _mockBookReaderRegistry = Substitute.For(); + _mockValidator = Substitute.For>(); + + // Default stubs: the query is valid, the current user is authenticated, no reader supports the library type, and no plugin is detected. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(Guid.NewGuid()); + _mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(Arg.Any()).Returns([]); + _mockBookReaderRegistry.GetSupportedExtensionsByPluginId().Returns(new Dictionary>()); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); + + _sut = new GetLibraryTypeBookReadersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockBookReaderRegistry, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryTypeCannotBeNull]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryTypeCannotBeNull, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedBookReaderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedBookReaderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenReadersSupportTheLibraryType_ShouldReturnThemDisabledWithTheirNamesAndExtensions() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid epubPluginId = Guid.NewGuid(); + Guid pdfPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(LibraryType.Book).Returns([epubPluginId, pdfPluginId]); + List plugins = [_pluginEntityFixture.Create(pdfPluginId, "PDF Reader"), _pluginEntityFixture.Create(epubPluginId, "EPUB Reader")]; + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); + _mockBookReaderRegistry.GetSupportedExtensionsByPluginId().Returns(new Dictionary> + { + [epubPluginId] = [".epub"], + [pdfPluginId] = [".pdf"] + }); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(epubPluginId, result.Value[0].PluginId); + Assert.Equal("EPUB Reader", result.Value[0].Name); + Assert.Equal(".epub", Assert.Single(result.Value[0].SupportedExtensions)); + Assert.False(result.Value[0].IsEnabled); + Assert.Equal(pdfPluginId, result.Value[1].PluginId); + Assert.Equal("PDF Reader", result.Value[1].Name); + Assert.Equal(".pdf", Assert.Single(result.Value[1].SupportedExtensions)); + Assert.False(result.Value[1].IsEnabled); + } + + [Fact] + public async Task HandleAsync_WhenReaderIsMissingFromDetectedPluginsAndRegistry_ShouldUseEmptyNameAndNoExtensions() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid unknownPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(LibraryType.Book).Returns([unknownPluginId]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryBookReaderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + Assert.Empty(response.SupportedExtensions); + } + + [Fact] + public async Task HandleAsync_WhenNoReaderSupportsTheLibraryType_ShouldReturnEmptyList() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Music)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + _mockProviderConfigurationStore.Received(1).GetSupportedBookReaderPluginIds(LibraryType.Music); + } + + [Fact] + public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get plugins"); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidatorTests.cs new file mode 100644 index 00000000..4c19fb5c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryValidatorTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersQueryValidatorTests +{ + private readonly GetLibraryTypeBookReadersQueryValidator _validator = new(); + private readonly GetLibraryTypeBookReadersQueryFixture _getLibraryTypeBookReadersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create() with { LibraryType = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + } + + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + [InlineData("0")] // The numeric value of a defined library type, which is not a member name. + [InlineData("")] // Empty. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandlerTests.cs new file mode 100644 index 00000000..f979c4c9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryHandlerTests.cs @@ -0,0 +1,184 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; + private readonly IValidator _mockValidator; + private readonly GetLibraryTypeMetadataProvidersQueryHandler _sut; + private readonly GetLibraryTypeMetadataProvidersQueryFixture _getLibraryTypeMetadataProvidersQueryFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockCurrentUserService = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); + _mockValidator = Substitute.For>(); + + // Default stubs: the query is valid, the current user is authenticated, no plugin supports the library type, and no plugin is detected. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(Guid.NewGuid()); + _mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(Arg.Any()).Returns([]); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1))); + + _sut = new GetLibraryTypeMetadataProvidersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.UnknownLibraryType]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.UnknownLibraryType, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedMetadataProviderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + _mockProviderConfigurationStore.DidNotReceive().GetSupportedMetadataProviderPluginIds(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPluginsSupportTheLibraryType_ShouldReturnThemDisabledAndRankedInTheSupportedOrder() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(LibraryType.Book).Returns([alphaPluginId, betaPluginId]); + List plugins = [_pluginEntityFixture.Create(betaPluginId, "Beta"), _pluginEntityFixture.Create(alphaPluginId, "Alpha")]; + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1))); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(new LibraryMetadataProviderResponse(alphaPluginId, "Alpha", false, 1), result.Value[0]); + Assert.Equal(new LibraryMetadataProviderResponse(betaPluginId, "Beta", false, 2), result.Value[1]); + } + + [Fact] + public async Task HandleAsync_WhenLibraryTypeCasingDiffers_ShouldStillResolveTheLibraryType() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: "music"); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockProviderConfigurationStore.Received(1).GetSupportedMetadataProviderPluginIds(LibraryType.Music); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book)); + Guid unknownPluginId = Guid.NewGuid(); + _mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(LibraryType.Book).Returns([unknownPluginId]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryMetadataProviderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + } + + [Fact] + public async Task HandleAsync_WhenNoPluginSupportsTheLibraryType_ShouldReturnEmptyList() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get plugins"); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidatorTests.cs new file mode 100644 index 00000000..30e5d773 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryValidatorTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersQueryValidatorTests +{ + private readonly GetLibraryTypeMetadataProvidersQueryValidator _validator = new(); + private readonly GetLibraryTypeMetadataProvidersQueryFixture _getLibraryTypeMetadataProvidersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError() + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create() with { LibraryType = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + } + + [Theory] + [InlineData("UnknownLibraryType")] // Not a library type. + [InlineData("999")] // A number that is not a defined library type. + [InlineData("0")] // The numeric value of a defined library type, which is not a member name. + [InlineData("")] // Empty. + public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType); + } + + [Theory] + [InlineData("Book")] + [InlineData("music")] // The casing of the type is ignored. + public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType) + { + // Arrange + GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: libraryType); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 702123cc..18192ffa 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -348,8 +348,8 @@ public class ErrorsTests AssertError(DomainErrors.Plugins.PluginIdCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Plugins.PluginSettingsCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Plugins.LibraryIdCannotBeEmpty, ErrorType.Validation); - AssertError(DomainErrors.Plugins.PluginIdsListCannotBeNull, ErrorType.Validation); - AssertError(DomainErrors.Plugins.PluginIdsListCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginIdsMustBeUnique, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginNotSupportedForLibraryType, ErrorType.Validation); AssertError(DomainErrors.Plugins.LibraryMetadataProviderConfigurationNotFound, ErrorType.NotFound); AssertError(DomainErrors.Plugins.PluginArchiveCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Plugins.PluginFileNameCannotBeEmpty, ErrorType.Validation); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs index 937c54c5..a78b2f23 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJobTests.cs @@ -84,10 +84,13 @@ public class MediaLibraryScanProcessorJobTests : IDisposable RegisterScan(firstScanId, LibraryScanJobStatus.Pending); RegisterScan(secondScanId, LibraryScanJobStatus.Pending); TaskCompletionSource releaseFirstScan = new(TaskCreationOptions.RunContinuationsAsynchronously); + // ExecutionStarted is signaled before the callback runs, and resumes the test on another thread, so the test waits for the callback itself to record the scan + TaskCompletionSource firstScanRecorded = new(TaskCreationOptions.RunContinuationsAsynchronously); List startedScanIds = []; FakeMediaLibraryScanDiscoveryJob firstRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: async _ => { startedScanIds.Add(firstScanId.ScanId.Value); + firstScanRecorded.SetResult(); await releaseFirstScan.Task; }); FakeMediaLibraryScanDiscoveryJob secondRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: _ => @@ -102,7 +105,7 @@ public class MediaLibraryScanProcessorJobTests : IDisposable // Act _queue.Writer.TryWrite(firstScanId); _queue.Writer.TryWrite(secondScanId); - await firstRootJob.ExecutionStarted.WaitAsync(s_testTimeout); + await firstScanRecorded.Task.WaitAsync(s_testTimeout); // Assert // The second scan must not start while the job graph of the first one is still executing. diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs index 762ff669..0880b85e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.Management; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Reading; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; @@ -19,6 +20,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Infrastructure.UnitTests.Core.Plugins; @@ -173,7 +175,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenCalled_ShouldRemoveStaleConfigurationsAndAddTheSupportedOnes() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMade_ShouldRemoveStaleConfigurationsAndAddTheSupportedOnes() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -198,7 +200,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Updated); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -339,7 +341,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenBookReaderSupportsTheLibraryType_ShouldAddDisabledConfiguration() + public async Task EnsureProviderConfigurationsAsync_WhenABookReaderSupportsTheLibraryType_ShouldAddADisabledBookReaderConfiguration() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -353,17 +355,20 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Updated); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.False(result.IsFailure); await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( Arg.Is(configuration => configuration.PluginId == pluginId && !configuration.IsEnabled), Arg.Any()); + // The reader is ensured exactly once, since a second ensure in the same scope would not see the staged row and would add a duplicate. + await _mockBookReaderConfigurationRepository.Received(1).GetByLibraryIdAsync(libraryId, Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(Arg.Any(), Arg.Any()); } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldNotAddAnotherOne() + public async Task EnsureProviderConfigurationsAsync_WhenTheBookReaderConfigurationAlreadyExists_ShouldNotAddAnotherBookReaderConfiguration() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -376,7 +381,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.From>([existingConfiguration])); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -384,7 +389,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenNoBookReaderSupportsTheLibraryType_ShouldNotAddConfiguration() + public async Task EnsureProviderConfigurationsAsync_WhenNoBookReaderSupportsTheLibraryType_ShouldNotAddABookReaderConfiguration() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -394,7 +399,7 @@ public class MediaLibraryProviderConfigurationStoreTests MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Movie, ".epub"))); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -403,7 +408,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenReaderDeclaresNoExtension_ShouldNotAddConfiguration() + public async Task EnsureProviderConfigurationsAsync_WhenTheBookReaderDeclaresNoExtension_ShouldNotAddABookReaderConfiguration() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -413,7 +418,7 @@ public class MediaLibraryProviderConfigurationStoreTests MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, supportedExtension: null))); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -421,7 +426,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError() + public async Task EnsureProviderConfigurationsAsync_WhenReadingBookReaderConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -433,14 +438,14 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to read configurations")); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task EnsureBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError() + public async Task EnsureProviderConfigurationsAsync_WhenUpsertingBookReaderConfigurationFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -454,14 +459,14 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to persist the configuration")); // Act - Result result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenCalled_ShouldRemoveStaleAndAddTheSupportedBookReaders() + public async Task ConfigureProvidersAsync_WhenOmittedBookReadersAreReconciled_ShouldRemoveStaleAndAddTheSupportedBookReaders() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -474,6 +479,7 @@ public class MediaLibraryProviderConfigurationStoreTests (alphaPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf")), (betaPluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: alphaPluginId); + StubConfigurations(libraryId, [], [], []); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([existingConfiguration])); _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) @@ -482,7 +488,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Updated); // Act - Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -493,10 +499,11 @@ public class MediaLibraryProviderConfigurationStoreTests Arg.Any()); await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync( Arg.Is(configuration => configuration.PluginId == alphaPluginId), Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToReadTheirConfigurations_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -504,18 +511,19 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + StubConfigurations(libraryId, [], [], []); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Error.Failure(description: "Failed to read configurations")); // Act - Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenDeletingStaleConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToDeleteStaleConfigurations_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -525,20 +533,21 @@ public class MediaLibraryProviderConfigurationStoreTests _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId); + StubConfigurations(libraryId, [], [], []); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([staleConfiguration])); _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) .Returns(Error.Failure(description: "Failed to delete the configurations")); // Act - Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToUpsertAConfiguration_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -546,90 +555,21 @@ public class MediaLibraryProviderConfigurationStoreTests IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); _mockPluginManager.GetPlugins().Returns([plugin]); MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + StubConfigurations(libraryId, [], [], []); _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(Result.From>([])); _mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to persist the configuration")); // Act - Result result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenCalled_ShouldDeleteTheConfigurationsOfTheLibrary() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(Result.Deleted); - MediaLibraryProviderConfigurationStore sut = CreateSut(); - - // Act - Result result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); - _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); - } - - [Fact] - public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenDeletionFails_ShouldReturnError() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) - .Returns(Error.Failure(description: "Failed to delete the configurations")); - MediaLibraryProviderConfigurationStore sut = CreateSut(); - - // Act - Result result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); - } - - [Fact] - public async Task RemoveBookReaderConfigurationsAsync_WhenCalled_ShouldDeleteTheConfigurationsOfThePlugin() - { - // Arrange - Guid pluginId = Guid.NewGuid(); - _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) - .Returns(Result.Deleted); - MediaLibraryProviderConfigurationStore sut = CreateSut(); - - // Act - Result result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockBookReaderConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any()); - _mockEnablementCache.Received(1).InvalidatePlugin(pluginId); - } - - [Fact] - public async Task RemoveBookReaderConfigurationsAsync_WhenDeletionFails_ShouldReturnError() - { - // Arrange - Guid pluginId = Guid.NewGuid(); - _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) - .Returns(Error.Failure(description: "Failed to delete the configurations")); - MediaLibraryProviderConfigurationStore sut = CreateSut(); - - // Act - Result result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - _mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any()); - } - - [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenArtworkConfigurationsAreStale_ShouldDeleteAndAddThem() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndArtworkConfigurationsAreStale_ShouldDeleteAndAddThem() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -654,7 +594,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.Updated); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -666,7 +606,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleArtworkConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndDeletingStaleArtworkConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -683,7 +623,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to delete the configurations")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -780,7 +720,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenMetadataProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndMetadataProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -797,7 +737,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.From>([])); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -806,7 +746,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenArtworkProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndArtworkProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -823,7 +763,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.From>([])); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -832,7 +772,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenReadingMetadataConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndReadingMetadataConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -844,7 +784,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to read configurations")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -853,7 +793,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleMetadataConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndDeletingStaleMetadataConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -868,14 +808,14 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to delete the configurations")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingMetadataConfigurationFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndUpsertingMetadataConfigurationFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -889,7 +829,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to persist the configuration")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -897,7 +837,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenReadingArtworkConfigurationsFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndReadingArtworkConfigurationsFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -911,7 +851,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to read configurations")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -919,7 +859,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingArtworkConfigurationFails_ShouldReturnError() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndUpsertingArtworkConfigurationFails_ShouldReturnError() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -935,7 +875,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Error.Failure(description: "Failed to persist the configuration")); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -943,7 +883,7 @@ public class MediaLibraryProviderConfigurationStoreTests } [Fact] - public async Task ReconcileBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldKeepItWithoutUpserting() + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndBookReaderConfigurationAlreadyExists_ShouldKeepItWithoutUpserting() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -960,7 +900,7 @@ public class MediaLibraryProviderConfigurationStoreTests .Returns(Result.From>([existingConfiguration])); // Act - Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -1010,6 +950,505 @@ public class MediaLibraryProviderConfigurationStoreTests await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); } + [Fact] + public async Task ConfigureProvidersAsync_WhenMetadataProviderChoicesAreMade_ShouldApplyTheirOrderAndEnabledState() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + LibraryMetadataProviderConfigurationEntity alphaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1, isEnabled: true); + StubConfigurations(libraryId, [alphaConfiguration], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: true), new(alphaPluginId, IsEnabled: false)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.LibraryId == libraryId && configuration.Rank == 1 && configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId && configuration.Id == alphaConfiguration.Id && configuration.Rank == 2 && !configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenASupportedMetadataProviderIsNotNamed_ShouldKeepItsStoredStateAfterTheNamedProviders() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + Guid gammaPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta"), CreatePlugin(gammaPluginId, "Gamma")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (gammaPluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + LibraryMetadataProviderConfigurationEntity gammaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, gammaPluginId, 1, isEnabled: true); + StubConfigurations(libraryId, [gammaConfiguration], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: false)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 1 && !configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == gammaPluginId && configuration.Rank == 2 && configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId && configuration.Rank == 3 && !configuration.IsEnabled), + Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenAMetadataProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnErrorWithoutChangingConfigurations() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(Guid.NewGuid(), IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenUpsertingAChosenMetadataProviderFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + StubConfigurations(libraryId, [], [], []); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Upsert failed")); + LibraryProviderSelectionDto[] metadataProviders = [new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenArtworkProviderChoicesAreMadeAndStaleConfigurationsExist_ShouldDeleteTheStaleOnesAndApplyTheChoices() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid supportedPluginId = Guid.NewGuid(); + Guid stalePluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(supportedPluginId, "Alpha"), CreatePlugin(stalePluginId, "Beta")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (supportedPluginId, null, CreateArtworkProvider(LibraryType.Book), null), + (stalePluginId, null, CreateArtworkProvider(LibraryType.Music), null)); + LibraryArtworkProviderConfigurationEntity staleConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, stalePluginId, 1); + StubConfigurations(libraryId, [], [staleConfiguration], []); + LibraryProviderSelectionDto[] artworkProviders = [new(supportedPluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any()); + await _mockArtworkConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == supportedPluginId && configuration.Rank == 1 && configuration.IsEnabled), + Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync( + Arg.Is(configuration => configuration.PluginId == stalePluginId), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenAnArtworkProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Music), null)); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] artworkProviders = [new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreMade_ShouldApplyTheirEnabledStateAndInvalidateTheEnablementCache() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid epubPluginId = Guid.NewGuid(); + Guid pdfPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(epubPluginId, "EPUB Reader"), CreatePlugin(pdfPluginId, "PDF Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (epubPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")), + (pdfPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf"))); + LibraryBookReaderConfigurationEntity pdfConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pdfPluginId, isEnabled: true); + StubConfigurations(libraryId, [], [], [pdfConfiguration]); + LibraryProviderSelectionDto[] bookReaders = [new(epubPluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == epubPluginId && configuration.LibraryId == libraryId && configuration.IsEnabled), + Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == pdfPluginId && configuration.IsEnabled), + Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreMadeAndStaleConfigurationsExist_ShouldDeleteTheStaleOnesAndApplyTheChoices() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid supportedPluginId = Guid.NewGuid(); + Guid stalePluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(supportedPluginId, "EPUB Reader"), CreatePlugin(stalePluginId, "PDF Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (supportedPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")), + (stalePluginId, null, null, CreateBookReader(LibraryType.EBook, ".pdf"))); + LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId, isEnabled: true); + StubConfigurations(libraryId, [], [], [staleConfiguration]); + LibraryProviderSelectionDto[] bookReaders = [new(supportedPluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any()); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == supportedPluginId && configuration.LibraryId == libraryId && configuration.IsEnabled), + Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync( + Arg.Is(configuration => configuration.PluginId == stalePluginId), Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenABookReaderChoiceNamesAnUnsupportedPlugin_ShouldReturnErrorWithoutInvalidatingTheEnablementCache() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub"))); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] bookReaders = [new(Guid.NewGuid(), IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenNoBookReaderChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldNotInvalidateTheEnablementCache() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + StubConfigurations(libraryId, [], [], []); + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenOmittedBookReadersAreReconciled_ShouldRemoveTheStaleReaderAndInvalidateTheEnablementCache() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid stalePluginId = Guid.NewGuid(); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId, isEnabled: true); + StubConfigurations(libraryId, [], [], [staleConfiguration]); + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any()); + _mockEnablementCache.Received(1).InvalidateLibrary(libraryId); + } + + [Fact] + public void GetSupportedMetadataProviderPluginIds_WhenPluginsSupportTheLibraryType_ShouldReturnThemInAlphabeticalOrder() + { + // Arrange + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + Guid unsupportedPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(betaPluginId, "Beta"), CreatePlugin(unsupportedPluginId, "Gamma"), CreatePlugin(alphaPluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (unsupportedPluginId, CreateMetadataProvider(LibraryType.Music), null, null)); + + // Act + IReadOnlyList result = sut.GetSupportedMetadataProviderPluginIds(LibraryType.Book); + + // Assert + Assert.Equal([alphaPluginId, betaPluginId], result); + } + + [Fact] + public void GetSupportedArtworkProviderPluginIds_WhenPluginsSupportTheLibraryType_ShouldReturnThemInAlphabeticalOrder() + { + // Arrange + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + Guid metadataOnlyPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(betaPluginId, "Beta"), CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(metadataOnlyPluginId, "Delta")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, null, CreateArtworkProvider(LibraryType.Music), null), + (betaPluginId, null, CreateArtworkProvider(LibraryType.Music), null), + (metadataOnlyPluginId, CreateMetadataProvider(LibraryType.Music), null, null)); + + // Act + IReadOnlyList result = sut.GetSupportedArtworkProviderPluginIds(LibraryType.Music); + + // Assert + Assert.Equal([alphaPluginId, betaPluginId], result); + } + + [Fact] + public void GetSupportedBookReaderPluginIds_WhenAReaderDeclaresNoFileExtension_ShouldLeaveItOut() + { + // Arrange + Guid epubPluginId = Guid.NewGuid(); + Guid extensionlessPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(epubPluginId, "EPUB Reader"), CreatePlugin(extensionlessPluginId, "Empty Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (epubPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")), + (extensionlessPluginId, null, null, CreateBookReader(LibraryType.Book, null))); + + // Act + IReadOnlyList result = sut.GetSupportedBookReaderPluginIds(LibraryType.Book); + + // Assert + Assert.Equal([epubPluginId], result); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenOnlyBookReaderChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldLeaveTheProviderConfigurationsUntouched() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub"))); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] bookReaders = [new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(Arg.Any(), Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldNotTouchAnyConfiguration() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + StubConfigurations(libraryId, [], [], []); + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenAChoiceHasNoEnabledState_ShouldKeepTheStoredStateAndApplyTheOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + LibraryMetadataProviderConfigurationEntity alphaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1, isEnabled: true); + StubConfigurations(libraryId, [alphaConfiguration], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: null), new(alphaPluginId, IsEnabled: null)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 1 && !configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId && configuration.Rank == 2 && configuration.IsEnabled), + Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenMetadataProviderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] metadataProviders = [new(pluginId, IsEnabled: true), new(pluginId, IsEnabled: false)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenArtworkProviderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null)); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] artworkProviders = [new(pluginId, IsEnabled: true), new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")]; + _mockPluginManager.GetPlugins().Returns(plugins); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub"))); + StubConfigurations(libraryId, [], [], []); + LibraryProviderSelectionDto[] bookReaders = [new(pluginId, IsEnabled: false), new(pluginId, IsEnabled: true)]; + + // Act + Result result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + /// + /// Stubs the stored configurations of a media library, and lets every write to the configuration repositories succeed. + /// + /// The Id of the media library whose configurations are stubbed. + /// The stored metadata provider configurations. + /// The stored artwork provider configurations. + /// The stored book reader configurations. + private void StubConfigurations( + Guid libraryId, + IReadOnlyList metadataConfigurations, + IReadOnlyList artworkConfigurations, + IReadOnlyList bookReaderConfigurations) + { + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()).Returns(Result.From(metadataConfigurations)); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()).Returns(Result.From(artworkConfigurations)); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()).Returns(Result.From(bookReaderConfigurations)); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockArtworkConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()).Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()).Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()).Returns(Result.Deleted); + } + /// /// Creates the store under test wired to the mocked dependencies, optionally registering the providers and book readers of the loaded plugins. /// @@ -1021,11 +1460,11 @@ public class MediaLibraryProviderConfigurationStoreTests foreach ((Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider, IBookReader? bookReader) in pluginServices) { if (metadataProvider is not null) - services.AddKeyedSingleton(pluginId, (_, _) => metadataProvider); + services.AddKeyedSingleton(pluginId, (_, _) => metadataProvider); if (artworkProvider is not null) - services.AddKeyedSingleton(pluginId, (_, _) => artworkProvider); + services.AddKeyedSingleton(pluginId, (_, _) => artworkProvider); if (bookReader is not null) - services.AddKeyedSingleton(pluginId, (_, _) => bookReader); + services.AddKeyedSingleton(pluginId, (_, _) => bookReader); } return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider(), _mockEnablementCache); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index 6e124e1c..e1996439 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -77,8 +77,6 @@ public class PluginDetectionSyncJobTests .Returns(Result.Deleted); _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); - _mockProviderConfigurationStore.EnsureBookReaderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Success); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); _mockServiceProvider.GetService(typeof(IMediaLibraryProviderConfigurationStore)).Returns(_mockProviderConfigurationStore); @@ -229,8 +227,8 @@ public class PluginDetectionSyncJobTests await StartAndWaitForExecutionAsync(sut); // Assert + // A single ensure covers the metadata, artwork and book reader configurations, since a second one before the save would stage duplicates. await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any()); - await _mockProviderConfigurationStore.Received(1).EnsureBookReaderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -239,7 +237,7 @@ public class PluginDetectionSyncJobTests { // Arrange IPlugin previouslyLoadedPlugin = CreatePlugin(Guid.NewGuid(), "My Plugin", new Version(1, 0, 0)); - _mockPluginManager.GetPlugins().Returns([]); // the plugin assembly now fails to load + _mockPluginManager.GetPlugins().Returns([]); // The plugin assembly now fails to load. _mockPluginRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Updated)); PluginLoadErrorDto loadError = _pluginLoadErrorDtoFixture.Create( diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index ee1570b5..ba73fa21 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -44,7 +44,7 @@ public class UpdateLibraryEndpointTests // Arrange UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - LibraryResponse expectedResponse = _libraryResponseFixture.Create(id: request.Id, userId: request.UserId); + LibraryResponse expectedResponse = _libraryResponseFixture.Create(id: request.Id); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -92,7 +92,7 @@ public class UpdateLibraryEndpointTests completionThresholdPercentage: 65); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId))); + .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -101,7 +101,6 @@ public class UpdateLibraryEndpointTests await _mockHandler.Received(1).HandleAsync( Arg.Is(command => command.Id == request.Id && - command.OwnerId == request.UserId && command.Title == request.Title && command.LibraryType == request.LibraryType && command.ContentLocations == request.ContentLocations && @@ -126,7 +125,7 @@ public class UpdateLibraryEndpointTests completionThresholdPercentage: null); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId))); + .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -154,7 +153,7 @@ public class UpdateLibraryEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId)); + return Result.From(_libraryResponseFixture.Create(id: request.Id)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..312dd5f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryTypeArtworkProvidersEndpoint _sut; + private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new(); + private readonly LibraryArtworkProviderResponseFixture _libraryArtworkProviderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithArtworkProviders() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _libraryArtworkProviderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeArtworkProvidersQueryToSender() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList response = _libraryArtworkProviderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryType == request.LibraryType), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..55e68314 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryTypeBookReadersEndpoint _sut; + private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new(); + private readonly LibraryBookReaderResponseFixture _libraryBookReaderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookReaders() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _libraryBookReaderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeBookReadersQueryToSender() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList response = _libraryBookReaderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryType == request.LibraryType), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..727f4e27 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryTypeMetadataProvidersEndpoint _sut; + private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new(); + private readonly LibraryMetadataProviderResponseFixture _libraryMetadataProviderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithMetadataProviders() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _libraryMetadataProviderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeMetadataProvidersQueryToSender() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList response = _libraryMetadataProviderResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(response)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryType == request.LibraryType), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(info => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + info.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, info.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs deleted file mode 100644 index 8a5d82fd..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryArtworkProvidersEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly ReorderLibraryArtworkProvidersEndpoint _sut; - private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryArtworkProvidersEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found."); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); - Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryArtworkProvidersCommandToSender() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginIds.SequenceEqual(request.PluginIds)), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs deleted file mode 100644 index cfb8c07a..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly ReorderLibraryMetadataProvidersEndpoint _sut; - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public ReorderLibraryMetadataProvidersEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("LibraryMetadataProviderConfiguration.NotFound", "The metadata provider configuration was not found."); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); - Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("LibraryMetadataProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The metadata provider configuration was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryMetadataProvidersCommandToSender() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginIds.SequenceEqual(request.PluginIds)), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs deleted file mode 100644 index 6a898b1f..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryArtworkProviderEnabledEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly SetLibraryArtworkProviderEnabledEndpoint _sut; - private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryArtworkProviderEnabledEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found."); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); - Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryArtworkProviderEnabledCommandToSender() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginId == request.PluginId && - command.IsEnabled == request.IsEnabled), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 0eec00c5..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,124 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly SetLibraryBookReaderEnabledEndpoint _sut; - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryBookReaderEnabledEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized"); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemResult = Assert.IsType(result); - Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); - Assert.Equal("application/problem+json", problemResult.ContentType); - Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title); - Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryBookReaderEnabledCommandToSender() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginId == request.PluginId && - command.IsEnabled == request.IsEnabled), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs deleted file mode 100644 index 97f1e840..00000000 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ /dev/null @@ -1,129 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.CQRS; -using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using Lumina.Domain.Common.Primitives; -using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.HttpResults; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledEndpointTests -{ - private readonly ICommandHandler> _mockHandler; - private readonly SetLibraryMetadataProviderEnabledEndpoint _sut; - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetLibraryMetadataProviderEnabledEndpointTests() - { - _mockHandler = Substitute.For>>(); - _sut = FastEndpoints.Factory.Create(_mockHandler); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(Result.Success, okResult.Value); - } - - [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("LibraryMetadataProviderConfiguration.NotFound", "The metadata provider configuration was not found."); - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(expectedError); - - // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); - Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("LibraryMetadataProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The metadata provider configuration was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryMetadataProviderEnabledCommandToSender() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(Result.Success)); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => - command.LibraryId == request.LibraryId && - command.PluginId == request.PluginId && - command.IsEnabled == request.IsEnabled), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - CancellationTokenSource cts = new(); - TaskCompletionSource operationStarted = new(); - TaskCompletionSource cancellationRequested = new(); - - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => Task.Run(async () => - { - operationStarted.SetResult(true); - await cancellationRequested.Task; - callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(Result.Success); - }, callInfo.Arg())); - - // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); - await operationStarted.Task; - cts.Cancel(); - cancellationRequested.SetResult(true); - - // Assert - await Assert.ThrowsAnyAsync(() => operationTask); - } -} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/PermissionAuthorizationHandlerTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/PermissionAuthorizationHandlerTests.cs new file mode 100644 index 00000000..57f80498 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/PermissionAuthorizationHandlerTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Microsoft.AspNetCore.Authorization; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Authorization; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PermissionAuthorizationHandlerTests +{ + private readonly IAuthorizationService _mockAuthorizationService; + private readonly PermissionAuthorizationHandler _sut; + + /// + /// Initializes a new instance of the class. + /// + public PermissionAuthorizationHandlerTests() + { + _mockAuthorizationService = Substitute.For(); + _sut = new PermissionAuthorizationHandler(_mockAuthorizationService); + } + + [Fact] + public async Task HandleAsync_WhenTheUserHoldsTheRequiredPermission_ShouldSucceed() + { + // Arrange + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(true); + AuthorizationHandlerContext context = CreateContext(); + + // Act + await _sut.HandleAsync(context); + + // Assert + Assert.True(context.HasSucceeded); + } + + [Fact] + public async Task HandleAsync_WhenAnAdministratorLacksTheRequiredPermission_ShouldSucceed() + { + // Arrange + // The API lets administrators do what the permission allows even without holding it, so the Web must not deny them. + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(true); + _mockAuthorizationService.HasPermissionAsync(Arg.Any(), Arg.Any()).Returns(false); + AuthorizationHandlerContext context = CreateContext(); + + // Act + await _sut.HandleAsync(context); + + // Assert + Assert.True(context.HasSucceeded); + } + + [Fact] + public async Task HandleAsync_WhenAUserIsNeitherAnAdministratorNorHoldsTheRequiredPermission_ShouldNotSucceed() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync(Arg.Any(), Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(Arg.Any(), Arg.Any()).Returns(false); + AuthorizationHandlerContext context = CreateContext(); + + // Act + await _sut.HandleAsync(context); + + // Assert + Assert.False(context.HasSucceeded); + } + + /// + /// Creates an authorization context that evaluates a requirement for the permission to manage media libraries. + /// + /// The created authorization context. + private static AuthorizationHandlerContext CreateContext() + { + return new AuthorizationHandlerContext([new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)], new ClaimsPrincipal(), resource: null); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..a3d5b4c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeArtworkProvidersEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryTypeArtworkProvidersEndpoint _sut; + private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new(); + private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeArtworkProvidersEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheProviders() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + LibraryArtworkProviderDto[] providers = [.. _libraryArtworkProviderDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(providers); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(providers.Length, data.GetArrayLength()); + Assert.Equal(providers[0].PluginId, data[0].GetProperty("pluginId").GetGuid()); + Assert.Equal(providers[0].Name, data[0].GetProperty("name").GetString()); + Assert.Equal(providers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestTheProvidersFromApiWithSubstitutedLibraryType() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", "Music")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "../plugins"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi() + { + // Arrange + GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs new file mode 100644 index 00000000..8f041d8b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeBookReadersEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryTypeBookReadersEndpoint _sut; + private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new(); + private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeBookReadersEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheReaders() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(readers); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(readers.Length, data.GetArrayLength()); + Assert.Equal(readers[0].PluginId, data[0].GetProperty("pluginId").GetGuid()); + Assert.Equal(readers[0].Name, data[0].GetProperty("name").GetString()); + Assert.Equal(readers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestTheReadersFromApiWithSubstitutedLibraryType() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", "Music")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "../plugins"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi() + { + // Arrange + GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..51fc20bd --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryTypeMetadataProvidersEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryTypeMetadataProvidersEndpoint _sut; + private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new(); + private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryTypeMetadataProvidersEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheProviders() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + LibraryMetadataProviderDto[] providers = [.. _libraryMetadataProviderDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(providers); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(providers.Length, data.GetArrayLength()); + Assert.Equal(providers[0].PluginId, data[0].GetProperty("pluginId").GetGuid()); + Assert.Equal(providers[0].Name, data[0].GetProperty("name").GetString()); + Assert.Equal(providers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestTheProvidersFromApiWithSubstitutedLibraryType() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", "Music")), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "../plugins"); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi() + { + // Arrange + GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(); + CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs new file mode 100644 index 00000000..394c3030 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.Index; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibrariesIndexViewEndpointTests +{ + private readonly IAuthorizationService _mockAuthorizationService; + private readonly LibrariesIndexViewEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public LibrariesIndexViewEndpointTests() + { + _mockAuthorizationService = Substitute.For(); + _sut = Factory.Create(_mockAuthorizationService); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/libraries/manage"; + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserHoldsTheManagePermission_ShouldRenderTheIndexViewWithManagementAllowed() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(true); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result)); + LibrariesIndexPageDto model = Assert.IsType(GetRenderedModel(result)); + Assert.True(model.CanManageLibraries); + await _mockAuthorizationService.Received(1).IsInRoleAsync("Admin", Arg.Any()); + await _mockAuthorizationService.Received(1).HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserIsAnAdministratorWithoutTheManagePermission_ShouldRenderTheIndexViewWithManagementAllowed() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(true); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(false); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result)); + LibrariesIndexPageDto model = Assert.IsType(GetRenderedModel(result)); + Assert.True(model.CanManageLibraries); + await _mockAuthorizationService.DidNotReceive().HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserIsNeitherAnAdministratorNorHoldsTheManagePermission_ShouldRenderTheIndexViewWithManagementDenied() + { + // Arrange + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(false); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result)); + LibrariesIndexPageDto model = Assert.IsType(GetRenderedModel(result)); + Assert.False(model.CanManageLibraries); + } + + /// + /// Reads the private view name of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The name or path of the rendered view. + private static string GetRenderedViewName(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(viewNameField); + return (string)viewNameField.GetValue(viewResult)!; + } + + /// + /// Reads the private model of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The model passed to the rendered view. + private static object? GetRenderedModel(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(modelField); + return modelField.GetValue(viewResult); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index e3f7b830..f1a52d84 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -26,6 +26,7 @@ public class SaveLibraryEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly SaveLibraryEndpoint _sut; private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -76,4 +77,29 @@ public class SaveLibraryEndpointTests using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); } + + [Fact] + public async Task ExecuteAsync_WhenProviderChoicesAreMade_ShouldForwardThemToTheApi() + { + // Arrange + LibraryDto request = _libraryDtoFixture.Create(); + request.Id = null; + request.MetadataProviders = _libraryProviderSelectionDtoFixture.CreateMany(2); + request.ArtworkProviders = []; + request.BookReaders = null; + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_libraryDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.Libraries.ADD_LIBRARY, + Arg.Is(library => + library.MetadataProviders == request.MetadataProviders && + library.ArtworkProviders == request.ArtworkProviders && + library.BookReaders == null), + Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs deleted file mode 100644 index 879cee64..00000000 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Plugins; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled; -using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; -using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; -using Microsoft.AspNetCore.Http; -using NSubstitute; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using EmptyRequest = Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest; -#endregion - -namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.SetBookReaderEnabled; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class SetBookReaderEnabledEndpointTests -{ - private readonly IApiHttpClient _mockApiHttpClient; - private readonly SetBookReaderEnabledEndpoint _sut; - private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new(); - - /// - /// Initializes a new instance of the class. - /// - public SetBookReaderEnabledEndpointTests() - { - _mockApiHttpClient = Substitute.For(); - _sut = Factory.Create(_mockApiHttpClient); - } - - [Fact] - public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJson() - { - // Arrange - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new EmptyRequest()); - - // Act - IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); - string body = await JsonResultTestHelper.GetResponseBodyAsync(result); - - // Assert - using JsonDocument jsonDocument = JsonDocument.Parse(body); - Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); - } - - [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendBookReaderEnabledChangeToApi() - { - // Arrange - SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new EmptyRequest()); - string expectedEndpoint = ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED - .Replace("{libraryId}", request.LibraryId.ToString()) - .Replace("{pluginId}", request.PluginId.ToString()); - - // Act - await _sut.ExecuteAsync(request, CancellationToken.None); - - // Assert - await _mockApiHttpClient.Received(1).PutAsync( - expectedEndpoint, - Arg.Is(payload => - payload.LibraryId == request.LibraryId && - payload.PluginId == request.PluginId && - payload.IsEnabled == request.IsEnabled), - Arg.Any()); - } -}