diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index 2231eb22..f00fa44c 100644 --- a/docs/manual/using-lumina/index.md +++ b/docs/manual/using-lumina/index.md @@ -49,7 +49,9 @@ Opening a book library shows a page with the library title, a search box, a sort - **The alpha picker** jumps to titles starting with a chosen character. It offers All, then the number and symbol keys, then A to Z. You can also press a letter key to filter, and press Escape to clear the filter. - **Pagination** splits the list into pages when you have it enabled, with previous and next buttons and a page indicator. When it is off, the whole list is shown and the count is the total. -Each book is a card with its cover and title. Clicking a card opens the book in the reader; a book can only be opened when a reader for its format is enabled for the library. Right-clicking a card, or using its actions button, opens a menu with **Read** and **View details**. +Each book is a card with its cover and title. Clicking a card opens the book in the reader; a book can only be opened when a reader for its format is enabled for the library. Right-clicking a card, or using its actions button, opens a menu with **Read**, **View details** and **Delete**. + +Deleting a book asks for confirmation and moves it to the library's **Deleted items**, together with the metadata and artwork Lumina stored for it. The file behind it is left untouched. The book stops appearing in the library, and an automatic scan does not add it back. If the file is later removed from disk, the next scan permanently removes the deleted book, including the metadata and artwork kept for it. The **Deleted items** button on the library page lists the deleted books and restores one when you select **Restore**. The book details page offers the same deletion with its **Delete book** button. ## Reading a book diff --git a/docs/technical/api/library/written-content-library/book-library/Api.Books.md b/docs/technical/api/library/written-content-library/book-library/Api.Books.md index 1be6da45..1c4606ca 100644 --- a/docs/technical/api/library/written-content-library/book-library/Api.Books.md +++ b/docs/technical/api/library/written-content-library/book-library/Api.Books.md @@ -26,13 +26,17 @@ - [Get Reading Manifest](#get-reading-manifest) - [Get Reading Manifest Request](#get-reading-manifest-request) - [Get Reading Manifest Response](#get-reading-manifest-response) - - [Get Reading Resource](#get-reading-resource) - - [Get Reading Resource Request](#get-reading-resource-request) - - [Get Reading Resource Response](#get-reading-resource-response) - [Get Reading Section](#get-reading-section) - [Get Reading Section Request](#get-reading-section-request) - [Get Reading Section Response](#get-reading-section-response) + - [Get Reading Resource](#get-reading-resource) + - [Get Reading Resource Request](#get-reading-resource-request) + - [Get Reading Resource Response](#get-reading-resource-response) + - [Get Deleted Books](#get-deleted-books) + - [Get Deleted Books Request](#get-deleted-books-request) + - [Get Deleted Books Response](#get-deleted-books-response) - [Delete Book](#delete-book) + - [Restore Book](#restore-book) ## Book @@ -872,14 +876,64 @@ Returns the binary resource identified by `resourceKey` of the book identified b The response is the raw bytes of the resource, served with the `Content-Type` of the resource and with `X-Content-Type-Options: nosniff`. A resource whose declared media type could be rendered as an active document (for example an SVG) is served as an opaque binary download instead. -### Delete Book +### Get Deleted Books + +#### Get Deleted Books Request ```js -DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId} +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/deleted-items ``` +Returns the books of the media library identified by the route that the user deleted and that can still be restored. The books are ordered by the time they were deleted, most recent first. + +#### Get Deleted Books Response + ```js 200 Ok ``` -Deletes the book identified by the route, together with its stored artwork. +```json +[ + { + "id": "f4c8a9a0-3d77-4e86-9b1a-2f7a5c4b6d31", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "title": "The Fellowship of the Ring", + "originalTitle": null, + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", + "deletedOnUtc": "2026-11-12T10:15:30Z", + "coverPath": "/media/books/tolkien/the-fellowship-of-the-ring/cover.jpg" + } +] +``` + +### Delete Book + +#### Delete Book Request + +```js +DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId} +``` + +#### Delete Book Response + +```js +200 Ok +``` + +Moves the book identified by the route to the deleted items of its media library. The book is no longer listed, read or materialized again by automatic scans, and its metadata and stored artwork are kept so that it can be restored. The deleted row keeps its file system path reserved in the library, so a later scan does not add the file back. The path stays reserved until the book is restored, or until the file disappears from disk and the scan permanently removes the deleted row. + +### Restore Book + +#### Restore Book Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/restore +``` + +#### Restore Book Response + +```js +200 Ok +``` + +Restores the deleted book identified by the route to the catalogue of its media library, together with the metadata and artwork that were kept while it was deleted. The path of the restored book stops being reserved by the deletion state, and the book is returned to the ordinary catalogue reads and scans. diff --git a/docs/technical/requests/library/written-content-library/book-library/books/GetDeletedBooks.http b/docs/technical/requests/library/written-content-library/book-library/books/GetDeletedBooks.http new file mode 100644 index 00000000..04592e3e --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/GetDeletedBooks.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/deleted-items +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/written-content-library/book-library/books/RestoreBook.http b/docs/technical/requests/library/written-content-library/book-library/books/RestoreBook.http new file mode 100644 index 00000000..e84aa2a2 --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/RestoreBook.http @@ -0,0 +1,2 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}/restore +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index 3f009f77..5bc7917e 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -20,6 +20,8 @@ The web client of Lumina is a themed shell: every page is rendered inside the te - [The audio player sub templates](#the-audio-player-sub-templates) - [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu) - [Page Templates](#page-templates) + - [The Books Index Page](#the-books-index-page) + - [The Deleted Items Page](#the-deleted-items-page) - [The Playlist Pages](#the-playlist-pages) - [The Shared Add to Playlist Action](#the-shared-add-to-playlist-action) - [The Album Track Actions Menu](#the-album-track-actions-menu) @@ -161,7 +163,7 @@ Every themed page is identified by a page key that mirrors the path of the corre 1. An explicit mapping in `templates` when the manifest declares the page key. 2. A mirrored template file at `templates/{pageKey}.html`, walking up the scope of the path when the exact mirror does not exist. -When neither an explicit mapping nor a mirrored file exists, the theme has no template for that page, and the application renders its own fallback unstylied Razor view instead. +When neither an explicit mapping nor a mirrored file exists, the theme has no template for that page, and the application renders its own fallback unstyled Razor view instead. For example, the books index page has the page key `library/written-content-library/book-library/books/index`. The engine tries, in order: the explicit `templates` entry for that key, `templates/library/written-content-library/book-library/books/index.html`, then the parent scopes such as `templates/library/written-content-library/book-library/books.html`. When none exists, the application renders the books page view itself. @@ -177,6 +179,7 @@ Known page keys: | `shared/audio-player/queue-item` | The queue item of the audio player bar. | | `shared/audio-player/playlist-item` | The playlist item of the audio player bar. | | `library/written-content-library/book-library/books/index` | The books browsing page. | +| `library/written-content-library/book-library/books/deleted-items` | The deleted items page of a book library, which restores deleted books. | | `playlists/index` | The page that lists and deletes the playlists of the current user. | | `playlists/item` | The page that creates a playlist, or edits, reorders, plays and deletes an existing playlist of the current user. The `isNew` page data field tells the two modes apart. | | `favorites/index` | The page that lists, filters and removes the favorites of the current user across media kinds. | @@ -555,6 +558,69 @@ Page templates are rendered into a content section that the layout wraps. A page {{/scripts}} ``` +#### The Books Index Page + +`library/written-content-library/book-library/books/index` receives a model with the following fields: + +| Field | Content | +| --- | --- | +| `libraryId` | The Id of the library whose books are browsed. | +| `itemsUrl` | The route that returns the books of the library. | +| `settingsUrl` | The route that returns the settings of the current user, which drive pagination and the alpha picker. | +| `readUrl` | The route template of the reader of a book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. | +| `detailsUrl` | The route template of the details page of a book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. | +| `deleteUrl` | The route template that deletes a book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. | +| `deletedBooksUrl` | The route of the deleted items page of the library. | +| `availabilityUrl` | The route template that reports whether a book can be read. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. | +| `strings` | The localized strings of the page, keyed by their resource names. | +| `stringsJson` | The same localized strings serialized as JSON, with camel case keys, for the page script. | + +The page script renders the cards into `books-container` and drives these hooks: + +| Hook | Purpose | +| --- | --- | +| `search-input` and `search-button` | Filter the books by title. | +| `sort-toggle` | Toggle the sort direction. | +| `btn-deleted-books` | Opens the deleted items page of the library. | +| `count-label` | Shows the total number of books or the range of the current page. | +| `alpha-picker` | Filters the books by their first character. | +| `pagination`, `prev-page`, `next-page` and `page-indicator` | Navigate the pages. | +| `no-items` and `no-items-matching` | Show the empty states without and with active filters. | +| `.media-card`, `.card-actions-trigger` and `.card-actions-menu` | Render a book card and its actions menu. | +| `.card-action-delete` | Deletes the book of the card. | + +#### The Deleted Items Page + +`library/written-content-library/book-library/books/deleted-items` lists the books that were deleted from a book library and lets the user restore them. Its fallback is `Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml`. The bundled themes ship their own `templates/library/written-content-library/book-library/books/deleted-items.html`; when a theme has no template for the page, the application renders the fallback view. + +Template resolution walks up the path scopes, so a theme that ships `templates/library/written-content-library/book-library/books.html` without a `deleted-items.html` would render that parent template for this page. A theme that provides a books parent template must also provide the deleted items template. + +Page data: + +| Field | Content | +| --- | --- | +| `libraryId` | The Id of the library whose deleted books are listed. | +| `libraryTitle` | The title of that library. | +| `deletedBooksJson` | The deleted books, serialized as a JSON array. Each item carries `id`, `libraryId`, `title`, `originalTitle`, `path`, `deletedOnUtc` and `coverPath`. | +| `restoreUrl` | The route template that restores a deleted book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book, and `libraryId` is appended as a query parameter. | +| `backUrl` | The route of the books page of the library. | +| `antiforgeryToken` | The anti-forgery request token for the restore POST. | +| `strings` | The localized strings of the page, keyed by their resource names. | +| `stringsJson` | The same localized strings serialized as JSON, with camel case keys, for the page script. | + +The page script drives these hooks: + +| Hook | Purpose | +| --- | --- | +| `btn-back-to-library` | Returns to the books page of the library. | +| `deleted-books-table` | Holds the deleted books. The restore click handler is bound to it. | +| `no-deleted-books` | The empty state, shown when no deleted books remain. | +| `.deleted-book-row` | A deleted book row, carrying the book Id in `data-book-id`. Removed after a successful restore. | +| `.btn-restore-book` | The restore button of a row, carrying the book Id in `data-book-id`. | +| `input[name="__RequestVerificationToken"]` | The anti-forgery token that the restore POST sends. | + +A theme that provides this page must keep these hooks and render the anti-forgery token, or reimplement the restore behavior itself. + #### The Playlist Pages `playlists/index` receives a model with the following fields: diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs index 0cd1b059..31c03f4c 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs @@ -212,6 +212,17 @@ public class BookEntity : IStorageEntity, IAuditableEntity /// public List Ratings { get; set; } = []; + /// + /// Gets or sets a value indicating whether the book was deleted by the user and is waiting to be restored or permanently removed. + /// A deleted book is kept out of every catalogue read and is not materialized again by scans, so that an automatic scan never undoes the deletion. + /// + public bool IsDeleted { get; set; } + + /// + /// Gets or sets the date and time when the book was deleted, or when the book is not deleted. + /// + public DateTime? DeletedOnUtc { get; set; } + /// /// Gets or sets the status of the metadata enrichment of the book. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs index 5c81dd64..6ea9bc85 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs @@ -26,15 +26,53 @@ public interface IBookRepository : IRepository, /// /// Gets the book of the media library identified by that is stored at the provided . /// + /// + /// Soft deleted books are included on purpose, so that the scan deletion strategy can permanently remove a deleted book when its file disappears from disk. + /// /// The Id of the media library whose book is retrieved. /// The file system path of the book to be retrieved. /// Cancellation token that can be used to stop the execution. /// An containing either the stored at the provided path, or an error. Task> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); + /// + /// Gets the soft deleted book identified by . + /// + /// The Id of the soft deleted book to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted , when the book does not exist or is not soft deleted, or an error. + Task> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Gets the soft deleted books of the media library identified by . + /// + /// The Id of the media library whose soft deleted books are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted books, or an error. + Task>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Soft deletes the book identified by , without removing its stored metadata or artwork. + /// + /// The Id of the book to soft delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken); + + /// + /// Restores the soft deleted book identified by . + /// + /// The Id of the book to restore. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken); + /// /// Gets the subset of that is already used by a book of the library identified by . /// + /// + /// Soft deleted books are included on purpose: their paths must still count as taken, so that a scan never materializes a deleted book again. + /// /// The Id of the library whose books are searched. /// The book paths to check. /// Cancellation token that can be used to stop the execution. @@ -83,6 +121,9 @@ public interface IBookRepository : IRepository, /// Resets the enrichment state of the books stored at the provided in the media library identified by /// , so that they are re-enriched, because their content changed since the last scan. /// + /// + /// Soft deleted books are included on purpose: if such a book is restored after its content changed, it must be re-enriched instead of keeping stale metadata. + /// /// The Id of the media library whose books are reset. /// The file system paths of the books whose enrichment state is reset. /// Cancellation token that can be used to stop the execution. @@ -93,6 +134,9 @@ public interface IBookRepository : IRepository, /// Resets the metadata enrichment status of all the books of the media library identified by , /// so that they are re-enriched, because the metadata provider configuration of the library changed. /// + /// + /// Soft deleted books are included on purpose: if such a book is restored after the provider configuration changed, it must be re-enriched with the new providers. + /// /// The Id of the media library whose books are reset. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. @@ -102,6 +146,9 @@ public interface IBookRepository : IRepository, /// Resets the artwork status of all the artwork of the books of the media library identified by , /// so that they are re-resolved, because the artwork provider configuration of the library changed. /// + /// + /// Soft deleted books are included on purpose: if such a book is restored after the provider configuration changed, its artwork must be re-resolved with the new providers. + /// /// The Id of the media library whose artwork is reset. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index b3b5c3ad..40441872 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -258,6 +258,25 @@ public static class BookEntityMapping ); } + /// + /// Converts a deleted to . + /// + /// The deleted repository entity to be converted. + /// The date and time when the book was deleted. + /// The converted deleted book response. + public static DeletedBookResponse ToResponse(this BookEntity repositoryEntity, DateTime deletedOnUtc) + { + return new DeletedBookResponse( + repositoryEntity.Id, + repositoryEntity.LibraryId, + repositoryEntity.Title, + repositoryEntity.OriginalTitle, + repositoryEntity.Path, + deletedOnUtc, + repositoryEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName + ); + } + /// /// Converts to a collection of . /// diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandler.cs index e4cdaef2..8a175995 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandler.cs @@ -1,15 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Domain.Common.Primitives; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; @@ -26,8 +23,6 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary public class DeleteBookCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; - private readonly IBookArtworkService _bookArtworkService; - private readonly ILogger _logger; private readonly IAuthorizationService _authorizationService; private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; @@ -36,22 +31,16 @@ public class DeleteBookCommandHandler : ICommandHandler class. /// /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for removing the artwork of a book. - /// Injected logger used to report the issues encountered while removing the stored artwork. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. public DeleteBookCommandHandler( IUnitOfWork unitOfWork, - IBookArtworkService bookArtworkService, - ILogger logger, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) { _unitOfWork = unitOfWork; - _bookArtworkService = bookArtworkService; - _logger = logger; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; @@ -99,28 +88,9 @@ public class DeleteBookCommandHandler : ICommandHandler getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure) - return getLibraryResult.Errors; - if (getLibraryResult.Value is null) - return DomainErrors.Library.LibraryNotFound; - LibraryEntity library = getLibraryResult.Value; - - // The artwork is stored under the library and author segments, so the author is resolved before the book is removed. - Result> getAuthorsResult = await _unitOfWork.BookRepository - .GetAuthorsDisplayNamesByBookIdsAsync([existingBook.Id], cancellationToken).ConfigureAwait(false); - if (getAuthorsResult.IsFailure) - return getAuthorsResult.Errors; - string authorName = getAuthorsResult.Value.TryGetValue(existingBook.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; - - // Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed. - Result deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, existingBook.Id, library.Title, authorName, existingBook.Title); - if (deleteArtworkResult.IsFailure) - _logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", existingBook.Id, existingBook.Path); - - // Delete the book, whose stored artwork rows and participations are removed by the database cascade. - Result deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false); + // The book is soft deleted, so its metadata, artwork and path stay available until the user restores it or the file disappears from disk. + // Keeping the row is also what makes the deletion survive an automatic scan, because the scan treats its path as already catalogued. + Result deleteBookResult = await _unitOfWork.BookRepository.SoftDeleteByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false); if (deleteBookResult.IsFailure) return deleteBookResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommand.cs new file mode 100644 index 00000000..774bdd2b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; + +/// +/// Command for restoring a deleted book by its Id. +/// +/// The unique identifier of the media library this book belongs to, taken from the route. +/// The unique identifier of the deleted book to restore, taken from the route. +[DebuggerDisplay("BookId: {BookId}")] +public record RestoreBookCommand( + string? LibraryId, + string? BookId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandHandler.cs new file mode 100644 index 00000000..23eab92e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandHandler.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; + +/// +/// Handler for the command to restore a deleted book by its Id. +/// +public class RestoreBookCommandHandler : 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 unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public RestoreBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to restore a deleted book by its Id. + /// + /// The command 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(RestoreBookCommand 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; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid bookId = Guid.Parse(command.BookId!); + + Result getBookResult = await _unitOfWork.BookRepository.GetSoftDeletedByIdAsync(bookId, cancellationToken).ConfigureAwait(false); + if (getBookResult.IsFailure) + return getBookResult.Errors; + if (getBookResult.Value is null) + return DomainErrors.WrittenContent.BookNotFound; + BookEntity existingBook = getBookResult.Value; + + // Resource scoping: the book must belong to the library named by the route, so that a book can never be restored through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (existingBook.LibraryId != libraryId) + return DomainErrors.WrittenContent.BookNotFound; + + // Admins can restore the books of all libraries; for everyone else, only the books of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result restoreBookResult = await _unitOfWork.BookRepository.RestoreSoftDeletedByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false); + if (restoreBookResult.IsFailure) + return restoreBookResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Updated; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandValidator.cs new file mode 100644 index 00000000..09a02a33 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; + +/// +/// Validates the needed validation rules for . +/// +public class RestoreBookCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreBookCommandValidator() + { + // Validates the identifier of the media library that owns the book, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the deleted book, taken from the route. + RuleFor(command => command.BookId) + .NotEmpty() + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + RuleFor(command => command.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(command => command.BookId is not null && command.BookId.Length > 0) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQuery.cs new file mode 100644 index 00000000..5901c471 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQuery.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; + +/// +/// Query for getting the deleted books of a media library. +/// +/// The unique identifier of the media library whose deleted books are retrieved, taken from the route. +public record GetDeletedBooksQuery( + string? LibraryId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryHandler.cs new file mode 100644 index 00000000..02ee6c62 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryHandler.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; + +/// +/// Handler for the query to get the deleted books of a media library. +/// +public class GetDeletedBooksQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetDeletedBooksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the deleted books of a media library. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// An containing either the deleted books, or an error. + public async Task>> HandleAsync(GetDeletedBooksQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see all libraries; for everyone else, only the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getDeletedBooksResult = await _unitOfWork.BookRepository.GetSoftDeletedByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getDeletedBooksResult.IsFailure) + return getDeletedBooksResult.Errors; + + return Result.From>([.. getDeletedBooksResult.Value.Select(book => book.ToResponse(book.DeletedOnUtc ?? book.CreatedOnUtc))]); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryValidator.cs new file mode 100644 index 00000000..df81bdfd --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryValidator.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; + +/// +/// Validates the needed validation rules for . +/// +public class GetDeletedBooksQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetDeletedBooksQueryValidator() + { + // Validates the identifier of the media library whose deleted books are retrieved, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/DeletedBookResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/DeletedBookResponse.cs new file mode 100644 index 00000000..7fc51398 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/DeletedBookResponse.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a book that the user deleted and can restore. +/// +/// The unique identifier of the book. +/// The unique identifier of the media library the book belongs to. +/// The title of the book. +/// The original title of the book, when it differs from the current one. +/// The file system path of the book. +/// The date and time when the book was deleted. +/// The relative path of the stored cover image of the book, when it has one. +public record DeletedBookResponse( + Guid Id, + Guid LibraryId, + string Title, + string? OriginalTitle, + string Path, + DateTime DeletedOnUtc, + string? CoverPath +); diff --git a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs index 10031f61..506a50d7 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs @@ -149,6 +149,13 @@ public class BookConfiguration : IEntityTypeConfiguration builder.Property(book => book.MetadataProvider) .HasMaxLength(100) .HasColumnOrder(40); + builder.Property(book => book.IsDeleted) + .IsRequired() + .HasDefaultValue(false) + .HasColumnOrder(41); + builder.Property(book => book.DeletedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(42); builder.HasMany(book => book.Contributors) .WithOne() @@ -226,5 +233,8 @@ public class BookConfiguration : IEntityTypeConfiguration builder.HasIndex(book => new { book.LibraryId, book.Path }) .IsUnique(); // the same physical book on disk cannot appear twice in the same library builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus }); + // The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the + // index follows the same order and no temporary B-tree is needed for the sort. + builder.HasIndex(book => new { book.LibraryId, book.IsDeleted, book.DeletedOnUtc, book.Title, book.Id }); } } diff --git a/src/Lumina.DataAccess/Common/Migrations/20261114173431_AddsBookDeletionState.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261114173431_AddsBookDeletionState.Designer.cs new file mode 100644 index 00000000..3370e8a9 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261114173431_AddsBookDeletionState.Designer.cs @@ -0,0 +1,3916 @@ +// +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("20261114173431_AddsBookDeletionState")] + partial class AddsBookDeletionState + { + /// + 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("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + 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("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(41); + + 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.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id"); + + 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/20261114173431_AddsBookDeletionState.cs b/src/Lumina.DataAccess/Common/Migrations/20261114173431_AddsBookDeletionState.cs new file mode 100644 index 00000000..6aeb4f68 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261114173431_AddsBookDeletionState.cs @@ -0,0 +1,59 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsBookDeletionState : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "DeletedOnUtc", + table: "Books", + type: "TEXT", + nullable: true) + .Annotation("Relational:ColumnOrder", 42); + + migrationBuilder.AddColumn( + name: "IsDeleted", + table: "Books", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 41); + + // This migration introduces both deletion columns together, so a database coming from an older schema has no deleted books to backfill. + // The statement is kept for databases that were created by an intermediate build that already had IsDeleted. + migrationBuilder.Sql(""" + UPDATE Books + SET DeletedOnUtc = COALESCE(UpdatedOnUtc, CreatedOnUtc) + WHERE IsDeleted = 1 AND DeletedOnUtc IS NULL; + """); + + migrationBuilder.CreateIndex( + name: "IX_Books_LibraryId_IsDeleted_DeletedOnUtc_Title_Id", + table: "Books", + columns: new[] { "LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Books_LibraryId_IsDeleted_DeletedOnUtc_Title_Id", + table: "Books"); + + migrationBuilder.DropColumn( + name: "DeletedOnUtc", + table: "Books"); + + migrationBuilder.DropColumn( + name: "IsDeleted", + table: "Books"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index d1761391..e4311226 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -1913,6 +1913,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(32); + b.Property("DeletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + b.Property("Description") .HasMaxLength(2000) .HasColumnType("TEXT") @@ -1936,6 +1940,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(27); + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(41); + b.Property("LCCN") .HasColumnType("TEXT") .HasColumnOrder(23); @@ -2067,6 +2077,8 @@ namespace Lumina.DataAccess.Common.Migrations b.HasIndex("LibraryId", "Path") .IsUnique(); + b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id"); + b.ToTable("Books", (string)null); }); diff --git a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index e782bd58..a1d8ce5c 100644 --- a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Specifications; using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications; @@ -38,14 +39,17 @@ internal sealed class BookRepository : IBookRepository private static readonly MethodInfo s_substringMethod = typeof(string).GetMethod(nameof(string.Substring), [typeof(int)])!; private readonly LuminaDbContext _luminaDbContext; + private readonly IDateTimeProvider _dateTimeProvider; /// /// Initializes a new instance of the class. /// /// Injected Entity Framework DbContext. - public BookRepository(LuminaDbContext luminaDbContext) + /// Injected provider for the current UTC time, used to stamp deletions deterministically. + public BookRepository(LuminaDbContext luminaDbContext, IDateTimeProvider dateTimeProvider) { _luminaDbContext = luminaDbContext; + _dateTimeProvider = dateTimeProvider; } /// @@ -88,7 +92,7 @@ internal sealed class BookRepository : IBookRepository /// An containing either a , or an error. public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - IQueryable query = _luminaDbContext.Books; + IQueryable query = _luminaDbContext.Books.Where(book => !book.IsDeleted); if (!shouldTrackEntities) query = query.AsNoTracking(); if (shouldIncludeNavigationProperties) @@ -119,7 +123,7 @@ internal sealed class BookRepository : IBookRepository /// An containing either a , or an error. public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - IQueryable booksQuery = _luminaDbContext.Books; + IQueryable booksQuery = _luminaDbContext.Books.Where(book => !book.IsDeleted); if (!shouldTrackEntities) booksQuery = booksQuery.AsNoTracking(); if (shouldIncludeNavigationProperties) @@ -202,7 +206,7 @@ internal sealed class BookRepository : IBookRepository return Errors.Library.FilterMustIncludeLibraryId; // The lightweight read models are retrieved without tracking by default, because they are never modified by the caller. - IQueryable booksQuery = _luminaDbContext.Books; + IQueryable booksQuery = _luminaDbContext.Books.Where(book => !book.IsDeleted); if (!shouldTrackEntities) booksQuery = booksQuery.AsNoTracking(); if (shouldIncludeNavigationProperties) @@ -272,6 +276,10 @@ internal sealed class BookRepository : IBookRepository /// /// Gets the book of the media library identified by that is stored at the provided . /// + /// + /// Soft deleted books are included on purpose: when the file disappears from disk, the scan deletion strategy must be able to permanently + /// remove a book that the user had already deleted, instead of leaving its soft deleted row behind. + /// /// The Id of the media library whose book is retrieved. /// The file system path of the book to be retrieved. /// Cancellation token that can be used to stop the execution. @@ -287,9 +295,83 @@ internal sealed class BookRepository : IBookRepository .FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false); } + /// + /// Gets the soft deleted book identified by . + /// + /// The Id of the soft deleted book to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted , when the book does not exist or is not soft deleted, or an error. + public async Task> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + return await _luminaDbContext.Books + .Include(book => book.Artwork) + .AsSplitQuery() + .FirstOrDefaultAsync(book => book.Id == id && book.IsDeleted, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the soft deleted books of the media library identified by . + /// + /// The Id of the media library whose soft deleted books are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the soft deleted books, or an error. + public async Task>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Books + .AsNoTracking() + .Include(book => book.Artwork) + .AsSplitQuery() + .Where(book => book.LibraryId == libraryId && book.IsDeleted) + // The deletion time is stored when the book is deleted, so later writes to the hidden row cannot change the order of the deleted items. + // Every deleted row carries a deletion time after the backfill and the delete operation. All terms sort descending, so the + // (LibraryId, IsDeleted, DeletedOnUtc, Title, Id) index can be scanned backwards and the database does not build a temporary B-tree. + .OrderByDescending(book => book.DeletedOnUtc) + .ThenByDescending(book => book.Title) + .ThenByDescending(book => book.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Soft deletes the book identified by , without removing its stored metadata or artwork. + /// + /// The Id of the book to soft delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + BookEntity? book = await _luminaDbContext.Books.FirstOrDefaultAsync(repositoryBook => repositoryBook.Id == id, cancellationToken).ConfigureAwait(false); + if (book is null || book.IsDeleted) + return Errors.WrittenContent.BookNotFound; + + book.IsDeleted = true; + book.DeletedOnUtc = _dateTimeProvider.UtcNow; + return Result.Updated; + } + + /// + /// Restores the soft deleted book identified by . + /// + /// The Id of the book to restore. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken) + { + BookEntity? book = await _luminaDbContext.Books.FirstOrDefaultAsync(repositoryBook => repositoryBook.Id == id, cancellationToken).ConfigureAwait(false); + if (book is null || !book.IsDeleted) + return Errors.WrittenContent.BookNotFound; + + book.IsDeleted = false; + book.DeletedOnUtc = null; + return Result.Updated; + } + /// /// Gets the subset of that is already used by a book of the library identified by . /// + /// + /// Soft deleted books are included on purpose: their paths must still count as taken, so that a scan never materializes a book that the user + /// deleted back into the catalogue. + /// /// The Id of the library whose books are searched. /// The book paths to check. /// Cancellation token that can be used to stop the execution. @@ -331,6 +413,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Contributors) .AsSplitQuery() .Where(book => book.LibraryId == libraryId + && !book.IsDeleted && book.MetadataStatus != MetadataStatus.Enriched && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) .OrderBy(book => book.Path) @@ -347,7 +430,7 @@ internal sealed class BookRepository : IBookRepository public async Task> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) { return await _luminaDbContext.Books - .CountAsync(book => book.LibraryId == libraryId && book.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); + .CountAsync(book => book.LibraryId == libraryId && !book.IsDeleted && book.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); } /// @@ -368,6 +451,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Artwork) .AsSplitQuery() .Where(book => book.LibraryId == libraryId + && !book.IsDeleted && !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched) && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) .OrderBy(book => book.Path) @@ -385,6 +469,7 @@ internal sealed class BookRepository : IBookRepository { return await _luminaDbContext.Books .CountAsync(book => book.LibraryId == libraryId + && !book.IsDeleted && !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched), cancellationToken) .ConfigureAwait(false); } @@ -393,6 +478,9 @@ internal sealed class BookRepository : IBookRepository /// Resets the enrichment state of the books stored at the provided in the media library identified by /// , so that they are re-enriched, because their content changed since the last scan. /// + /// + /// Soft deleted books are included on purpose: if such a book is restored after its content changed, it must be re-enriched instead of keeping stale metadata. + /// /// The Id of the media library whose books are reset. /// The file system paths of the books whose enrichment state is reset. /// Cancellation token that can be used to stop the execution. @@ -426,6 +514,9 @@ internal sealed class BookRepository : IBookRepository /// Resets the metadata enrichment status of all the books of the media library identified by , /// so that they are re-enriched, because the metadata provider configuration of the library changed. /// + /// + /// Soft deleted books are included on purpose: if such a book is restored after the provider configuration changed, it must be re-enriched with the new providers. + /// /// The Id of the media library whose books are reset. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. @@ -443,6 +534,9 @@ internal sealed class BookRepository : IBookRepository /// Resets the artwork status of all the artwork of the books of the media library identified by , /// so that they are re-resolved, because the artwork provider configuration of the library changed. /// + /// + /// Soft deleted books are included on purpose: if such a book is restored after the provider configuration changed, its artwork must be re-resolved with the new providers. + /// /// The Id of the media library whose artwork is reset. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. @@ -514,7 +608,7 @@ internal sealed class BookRepository : IBookRepository const int LOOKUP_CHUNK_SIZE = 500; foreach (Guid[] chunk in bookIds.Chunk(LOOKUP_CHUNK_SIZE)) { - IQueryable query = _luminaDbContext.Books.AsNoTracking(); + IQueryable query = _luminaDbContext.Books.AsNoTracking().Where(book => !book.IsDeleted); if (shouldIncludeNavigationProperties) { query = query @@ -570,20 +664,29 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Ratings) .Include(book => book.Contributors) .AsSplitQuery() - .FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(book => book.Id == data.Id && !book.IsDeleted, cancellationToken).ConfigureAwait(false); if (foundBook is null) return Errors.WrittenContent.BookNotFound; - // The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself. The audit columns are - // only ever written by the auditing interceptor, which is why the copier restores them after copying the editable values. + // The stored enrichment, identity and deletion columns are never overwritten by an edit: they are owned by the scan, by the record itself + // and by the explicit delete and restore operations. The audit columns are only ever written by the auditing interceptor, which is why the + // copier restores them after copying the editable values. Guid libraryId = foundBook.LibraryId; string path = foundBook.Path; + bool isDeleted = foundBook.IsDeleted; + DateTime? deletedOnUtc = foundBook.DeletedOnUtc; MetadataStatus metadataStatus = foundBook.MetadataStatus; DateTime? lastMetadataUpdateUtc = foundBook.LastMetadataUpdateUtc; string? metadataProvider = foundBook.MetadataProvider; EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundBook, data); foundBook.LibraryId = libraryId; foundBook.Path = path; + foundBook.IsDeleted = isDeleted; + foundBook.DeletedOnUtc = deletedOnUtc; + // The deletion state is owned by the explicit delete and restore operations. Clearing the modified flags keeps it out of the UPDATE statement, + // so an edit that raced with a delete can never write the deletion state back and resurrect the book. + _luminaDbContext.Entry(foundBook).Property(book => book.IsDeleted).IsModified = false; + _luminaDbContext.Entry(foundBook).Property(book => book.DeletedOnUtc).IsModified = false; foundBook.MetadataStatus = metadataStatus; foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc; foundBook.MetadataProvider = metadataProvider; diff --git a/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs index 9afaf0c8..5a7319f4 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Favorites/FavoriteRepository.cs @@ -25,8 +25,9 @@ namespace Lumina.DataAccess.Core.Repositories.Favorites; /// /// /// A favorite references its media item by kind and Id without a foreign key, so reading a page of favorites resolves the display data of -/// the referenced items with one batched query per media kind present in the page, and a favorite whose item no longer exists is kept -/// without display data. Duplicate favorites of the same user on the same item are rejected by the unique (UserId, MediaKind, MediaItemId) index. +/// the referenced items with one batched query per media kind present in the page. A favorite whose item no longer exists, or whose book +/// was soft deleted, is kept without display data. Duplicate favorites of the same user on the same item are rejected by the unique +/// (UserId, MediaKind, MediaItemId) index. /// internal sealed class FavoriteRepository : IFavoriteRepository { @@ -127,7 +128,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false), FavoriteMediaKind.Book => await _luminaDbContext.Books .AsNoTracking() - .Where(book => book.Id == mediaItemId) + .Where(book => book.Id == mediaItemId && !book.IsDeleted) .Select(book => (Guid?)book.LibraryId) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false), _ => null, @@ -350,7 +351,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository // the same author the book listing shows, and the Id is the tiebreaker between authors that share a display name. rows = await _luminaDbContext.Books .AsNoTracking() - .Where(book => requestedIds.Contains(book.Id)) + .Where(book => requestedIds.Contains(book.Id) && !book.IsDeleted) .Select(book => new DisplayRow( book.Id, book.LibraryId, diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index f6a29ab7..5ef3399c 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -13,6 +13,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.Repositories.BookLibrary; using Lumina.DataAccess.Core.Repositories.Favorites; @@ -42,6 +43,7 @@ namespace Lumina.DataAccess.Core.UoW; public class UnitOfWork : IUnitOfWork, IDisposable { private readonly LuminaDbContext _luminaDbContext; + private readonly IDateTimeProvider _dateTimeProvider; private IDbContextTransaction? _transaction; private IPermissionRepository? _permissionRepository; @@ -131,7 +133,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable { get { - _bookRepository ??= new BookRepository(_luminaDbContext); + _bookRepository ??= new BookRepository(_luminaDbContext, _dateTimeProvider); return _bookRepository; } } @@ -449,9 +451,11 @@ public class UnitOfWork : IUnitOfWork, IDisposable /// Initializes a new instance of the class. /// /// Injected Entity Framework DbContext. - public UnitOfWork(LuminaDbContext luminaDbContext) + /// Injected provider for the current UTC time, passed to the repositories that stamp their own timestamps. + public UnitOfWork(LuminaDbContext luminaDbContext, IDateTimeProvider dateTimeProvider) { _luminaDbContext = luminaDbContext; + _dateTimeProvider = dateTimeProvider; } /// diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs index 64b98635..36a435ab 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs @@ -13,6 +13,8 @@ public static partial class ApiRoutes public const string GET_BOOK_BY_ID = "/libraries/{libraryId}/books/{bookId}"; public const string GET_BOOKS = "/libraries/{libraryId}/books"; public const string GET_BOOKS_LITE = "/libraries/{libraryId}/books/lite"; + public const string GET_DELETED_BOOKS = "/libraries/{libraryId}/books/deleted-items"; + public const string RESTORE_BOOK = "/libraries/{libraryId}/books/{bookId}/restore"; public const string ADD_BOOK = "/libraries/{libraryId}/books"; public const string UPDATE_BOOK = "/libraries/{libraryId}/books/{bookId}"; public const string DELETE_BOOK = "/libraries/{libraryId}/books/{bookId}"; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs index f9773595..4141cd10 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs @@ -19,9 +19,9 @@ public class DeleteBookEndpointSummary : Summary +/// API endpoint for the /libraries/{libraryId}/books/deleted-items route. +/// +public class GetDeletedBooksEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getDeletedBooksQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get deleted books queries. + public GetDeletedBooksEndpoint(IQueryHandler>> getDeletedBooksQueryHandler) + { + _getDeletedBooksQueryHandler = getDeletedBooksQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Books.GET_DELETED_BOOKS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the deleted books of the library identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifier of the library from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getDeletedBooksQueryHandler.HandleAsync(new GetDeletedBooksQuery(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointSummary.cs new file mode 100644 index 00000000..378dd48d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointSummary.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedBooksEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetDeletedBooksEndpointSummary() + { + Summary = "Retrieves the deleted books of a media library."; + Description = "Returns the books of the media library identified by the route that the user deleted and that can still be restored, ordered by the time they were deleted, most recent first. The list is returned to an Admin, who can see the deleted books of all libraries, or to the owner of the library."; + + ResponseParam(response => response.Id, "The Id of the deleted book."); + ResponseParam(response => response.LibraryId, "The Id of the media library the deleted book belongs to."); + ResponseParam(response => response.Title, "The title of the deleted book."); + ResponseParam(response => response.OriginalTitle, "The original title of the deleted book, if different from the current title."); + ResponseParam(response => response.Path, "The file system path of the deleted book."); + ResponseParam(response => response.DeletedOnUtc, "The date and time when the book was deleted."); + ResponseParam(response => response.CoverPath, "The path of the cover image of the deleted book, if available."); + + Response(200, "The deleted books are returned.", + example: new DeletedBookResponse[] + { + new( + Id: Guid.Parse("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + Title: "The Fellowship of the Ring", + OriginalTitle: "The Fellowship of the Ring", + Path: "/media/libraries/books/the-fellowship-of-the-ring.epub", + DeletedOnUtc: DateTime.UtcNow, + CoverPath: "/media/books/tolkien/the-fellowship-of-the-ring/cover.jpg" + ), + new( + Id: Guid.Parse("2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + Title: "The Two Towers", + OriginalTitle: "The Two Towers", + Path: "/media/libraries/books/the-two-towers.epub", + DeletedOnUtc: DateTime.UtcNow.AddMinutes(-30), + CoverPath: "/media/books/tolkien/the-two-towers/cover.jpg" + ) + } + ); + + 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/{Guid.NewGuid()}/books/deleted-items" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items" + } + } + ); + + 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.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items", + 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/{Guid.NewGuid()}/books/deleted-items", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs new file mode 100644 index 00000000..714dc75f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// API endpoint for the /libraries/{libraryId}/books/{bookId}/restore route. +/// +public class RestoreBookEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _restoreBookCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling restore book commands. + public RestoreBookEndpoint(ICommandHandler> restoreBookCommandHandler) + { + _restoreBookCommandHandler = restoreBookCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Books.RESTORE_BOOK); + Version(1); + DontCatchExceptions(); + } + + /// + /// Restores the deleted book identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); + Result result = await _restoreBookCommandHandler.HandleAsync(new RestoreBookCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointSummary.cs new file mode 100644 index 00000000..87fd7e95 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointSummary.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreBookEndpointSummary() + { + Summary = "Restores a deleted book."; + Description = "Restores the deleted book identified by the route to the catalogue of its media library, together with the metadata and artwork that were kept while it was deleted. The book is restored by an Admin, who can restore the books of all libraries, or by the owner of the library of the book."; + + Response(200, "The book was successfully restored."); + + 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/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore" + } + } + ); + + 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.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested deleted book does not exist, or is not deleted.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "BookNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore", + 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/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "BookIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index fc164c3c..b4e90cf8 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip differ diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index 188876ab..8413c6e3 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip differ diff --git a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/DeletedBookDto.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/DeletedBookDto.cs new file mode 100644 index 00000000..5d888b4d --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/DeletedBookDto.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Data transfer object for a book that the user deleted and can restore. +/// +/// The Id of the deleted book. +/// The Id of the media library the deleted book belongs to. +/// The title of the deleted book. +/// The original title of the deleted book, when it differs from the current one. +/// The file system path of the deleted book. +/// The date and time when the book was deleted. +/// The relative path of the stored cover image of the deleted book, when it has one. +[DebuggerDisplay("Title: {Title}")] +public sealed record DeletedBookDto( + Guid Id, + Guid LibraryId, + string Title, + string? OriginalTitle, + string Path, + DateTime DeletedOnUtc, + string? CoverPath +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/DeletedBooksPageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/DeletedBooksPageDto.cs new file mode 100644 index 00000000..dcf1f3c0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/DeletedBooksPageDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Data transfer object carrying the data needed by the deleted items page of a book library. +/// +/// The media library whose deleted books are shown. +/// The deleted books of the media library, ordered by the time they were deleted, most recent first. +public sealed record DeletedBooksPageDto( + LibraryDto Library, + IReadOnlyList DeletedBooks +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs index 1dbdba05..677abcd5 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs @@ -13,6 +13,9 @@ public static partial class ApiRoutes public const string GET_BOOKS_LITE = "libraries/{libraryId}/books/lite"; public const string GET_BOOK = "libraries/{libraryId}/books/{bookId}"; public const string UPDATE_BOOK = "libraries/{libraryId}/books/{bookId}"; + public const string DELETE_BOOK = "libraries/{libraryId}/books/{bookId}"; + public const string GET_DELETED_BOOKS = "libraries/{libraryId}/books/deleted-items"; + public const string RESTORE_BOOK = "libraries/{libraryId}/books/{bookId}/restore"; public const string UPDATE_BOOK_COVER = "libraries/{libraryId}/books/{bookId}/cover"; public const string GET_BOOK_READING_MANIFEST = "libraries/{libraryId}/books/{bookId}/reading/manifest"; public const string GET_BOOK_READING_AVAILABILITY = "libraries/{libraryId}/books/{bookId}/reading/availability"; diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs index ba998f99..30ed0735 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs @@ -15,6 +15,9 @@ public static partial class WebRoutes public const string EDIT_BOOK = "{culture}/library/written-content-library/books-library/books/{bookId}"; public const string GET_BOOK_DETAILS = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-book"; public const string SAVE_BOOK = "{culture}/library/written-content-library/books-library/books/{bookId}/api-save-book"; + public const string DELETE_BOOK = "{culture}/library/written-content-library/books-library/books/{bookId}/api-delete-book"; + public const string DELETED_BOOKS = "{culture}/library/written-content-library/books-library/books/deleted-items"; + public const string RESTORE_BOOK = "{culture}/library/written-content-library/books-library/books/{bookId}/api-restore-book"; public const string UPDATE_BOOK_COVER = "{culture}/library/written-content-library/books-library/books/{bookId}/api-update-cover"; public const string READ = "{culture}/library/written-content-library/books-library/books/{bookId}/read"; public const string GET_READING_MANIFEST = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpoint.cs new file mode 100644 index 00000000..ba563b39 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpoint.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-delete-book route. +/// +public class DeleteBookEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public DeleteBookEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Books.DELETE_BOOK); + DontAutoTag(); + Options(options => options.WithTags("Books")); + EnableAntiforgery(); + } + + /// + /// Deletes the book identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The book is identified by the {bookId} route value and the owning library by the {libraryId} query string; both ids are + // normalized to Guids before they are substituted into the upstream URL, so that a crafted value can never escape its URL + // segment, and an unparseable id is reported by the API as a missing id. + string routeBookId = HttpContext.Request.RouteValues["bookId"]?.ToString() ?? string.Empty; + string bookId = Guid.TryParse(routeBookId, out Guid parsedBookId) ? parsedBookId.ToString() : Guid.Empty.ToString(); + string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); + string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); + + await _apiHttpClient.DeleteAsync(ApiRoutes.Books.DELETE_BOOK.Replace("{libraryId}", libraryId).Replace("{bookId}", bookId), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs new file mode 100644 index 00000000..08405df3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteBookEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteBookEndpointSummary() + { + Summary = "Deletes a book."; + Description = "Moves the book identified by the route to the deleted items of its library, where its metadata and stored artwork are kept so that the deletion can be undone."; + + Response(200, "The book was moved to the deleted items of its library."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpoint.cs new file mode 100644 index 00000000..dcf394e6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpoint.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/deleted-items route. +/// +public class DeletedBooksViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Library.WrittenContentLibrary.BookLibrary.Books.DeletedItems"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "library/written-content-library/book-library/books/deleted-items"; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly IApiHttpClient _apiHttpClient; + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public DeletedBooksViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _apiHttpClient = apiHttpClient; + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.DELETED_BOOKS); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Displays the deleted books of a media library, rendered by the active theme with a fallback to the Razor view. + /// + /// The request containing the Id of the media library whose deleted books are shown. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBooksViewRequest request, CancellationToken cancellationToken) + { + if (request.LibraryId is null) + return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!); + + LibraryDto library = await _apiHttpClient.GetAsync( + ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); + DeletedBookDto[] deletedBooks = await _apiHttpClient.GetAsync( + ApiRoutes.Books.GET_DELETED_BOOKS.Replace("{libraryId}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); + + // The page restores books, which submit through the form anti-forgery token, so a fresh token must be issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + + string title = _localizer["Title"].Value; + string backUrl = (_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX) ?? string.Empty) + "?libraryId=" + request.LibraryId.Value; + Dictionary strings = ThemePageDataFactory.CreateLocalizedStrings(_localizer); + // The themed page script reads the localized strings through camel case keys, and they are serialized as JSON so that quotes and + // apostrophes in translations never terminate the JavaScript string literals of the template. + string stringsJson = JsonSerializer.Serialize(strings.ToDictionary( + entry => JsonNamingPolicy.CamelCase.ConvertName(entry.Key), + entry => entry.Value)); + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["libraryId"] = request.LibraryId.Value.ToString(), + ["libraryTitle"] = library.Title ?? string.Empty, + ["deletedBooksJson"] = JsonSerializer.Serialize(deletedBooks, s_camelCaseJsonOptions), + ["restoreUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.RESTORE_BOOK, new { bookId = default(Guid) }) ?? string.Empty, + ["backUrl"] = backUrl, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = strings, + ["stringsJson"] = stringsJson + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml", + new DeletedBooksPageDto(library, deletedBooks), + new Dictionary { ["Title"] = title }); + + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = title }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointSummary.cs new file mode 100644 index 00000000..fdfcf634 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeletedBooksViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeletedBooksViewEndpointSummary() + { + Summary = "Renders the deleted items page of a book library."; + Description = "Renders the page that lists the books the user deleted from a book library and lets the user restore them."; + + Response(200, "The deleted items page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs index 7e68cfb8..c958c33b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs @@ -105,6 +105,7 @@ public class EditBookViewEndpoint : BaseEndpoint ["libraryId"] = book.LibraryId.ToString(), ["antiforgeryToken"] = antiforgeryTokens.RequestToken, ["saveUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { bookId = default(Guid) }) ?? string.Empty, + ["deleteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, new { bookId = default(Guid) }) ?? string.Empty, ["coverUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.UPDATE_BOOK_COVER, new { bookId = default(Guid) }) ?? string.Empty, ["backUrl"] = (_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX) ?? string.Empty) + "?libraryId=" + book.LibraryId, ["bookJson"] = JsonSerializer.Serialize(book, s_camelCaseJsonOptions), diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs index 8f7ff097..1b6562f1 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -9,11 +9,12 @@ using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Common; using Lumina.Presentation.Web.Core.Themes; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Localization; using System; using System.Collections.Generic; +using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; #endregion @@ -76,6 +77,13 @@ public class BooksIndexViewEndpoint : BaseEndpoint return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!); LibraryDto library = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); + Dictionary strings = ThemePageDataFactory.CreateLocalizedStrings(_localizer); + // The themed page script reads the localized strings through camel case keys, and they are serialized as JSON so that quotes and + // apostrophes in translations never terminate the JavaScript string literals of the template. + string stringsJson = JsonSerializer.Serialize(strings.ToDictionary( + entry => JsonNamingPolicy.CamelCase.ConvertName(entry.Key), + entry => entry.Value)); + ThemePageDto pageModel = new() { PageKey = VIEW_PAGE_KEY, @@ -88,8 +96,11 @@ public class BooksIndexViewEndpoint : BaseEndpoint ["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty, ["readUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) }) ?? string.Empty, ["detailsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) }) ?? string.Empty, + ["deleteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, new { bookId = default(Guid) }) ?? string.Empty, + ["deletedBooksUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.DELETED_BOOKS) ?? string.Empty, ["availabilityUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) }) ?? string.Empty, - ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + ["strings"] = strings, + ["stringsJson"] = stringsJson } }; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs new file mode 100644 index 00000000..79203ddf --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-restore-book route. +/// +public class RestoreBookEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RestoreBookEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Books.RESTORE_BOOK); + DontAutoTag(); + Options(options => options.WithTags("Books")); + EnableAntiforgery(); + } + + /// + /// Restores the deleted book identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The book is identified by the {bookId} route value and the owning library by the {libraryId} query string; both ids are + // normalized to Guids before they are substituted into the upstream URL, so that a crafted value can never escape its URL + // segment, and an unparseable id is reported by the API as a missing id. + string routeBookId = HttpContext.Request.RouteValues["bookId"]?.ToString() ?? string.Empty; + string bookId = Guid.TryParse(routeBookId, out Guid parsedBookId) ? parsedBookId.ToString() : Guid.Empty.ToString(); + string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); + string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); + + await _apiHttpClient.PostAsync( + ApiRoutes.Books.RESTORE_BOOK.Replace("{libraryId}", libraryId).Replace("{bookId}", bookId), + new Web.Common.Requests.Common.EmptyRequest(), + cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isRestored = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointSummary.cs new file mode 100644 index 00000000..669638a7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreBookEndpointSummary() + { + Summary = "Restores a deleted book."; + Description = "Restores the deleted book identified by the route to the catalogue of its library, together with the metadata and artwork that were kept while it was deleted."; + + Response(200, "The book was restored."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ar-SA.resx new file mode 100644 index 00000000..7eabaa8f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ar-SA.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + العناصر المحذوفة + + + العودة إلى المكتبة + + + لا توجد عناصر محذوفة في هذه المكتبة. + + + الكتاب + + + تاريخ الحذف + + + استعادة + + + تمت استعادة الكتاب. + + + تعذرت استعادة الكتاب. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.de-DE.resx new file mode 100644 index 00000000..4e480339 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.de-DE.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Gelöschte Elemente + + + Zurück zur Bibliothek + + + In dieser Bibliothek gibt es keine gelöschten Elemente. + + + Buch + + + Gelöscht am + + + Wiederherstellen + + + Das Buch wurde wiederhergestellt. + + + Das Buch konnte nicht wiederhergestellt werden. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.en-US.resx new file mode 100644 index 00000000..7e3b8420 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.en-US.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Deleted items + + + Back to library + + + There are no deleted items in this library. + + + Book + + + Deleted on + + + Restore + + + The book was restored. + + + The book could not be restored. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.es-ES.resx new file mode 100644 index 00000000..b7cf0353 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.es-ES.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Elementos eliminados + + + Volver a la biblioteca + + + No hay elementos eliminados en esta biblioteca. + + + Libro + + + Eliminado el + + + Restaurar + + + El libro se ha restaurado. + + + El libro no se ha podido restaurar. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.fr-FR.resx new file mode 100644 index 00000000..fa0da913 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.fr-FR.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Éléments supprimés + + + Retour à la bibliothèque + + + Cette bibliothèque ne contient aucun élément supprimé. + + + Livre + + + Supprimé le + + + Restaurer + + + Le livre a été restauré. + + + Le livre n'a pas pu être restauré. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.it-IT.resx new file mode 100644 index 00000000..0c90a93f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.it-IT.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Elementi eliminati + + + Torna alla biblioteca + + + Non ci sono elementi eliminati in questa biblioteca. + + + Libro + + + Eliminato il + + + Ripristina + + + Il libro è stato ripristinato. + + + Non è stato possibile ripristinare il libro. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ja-JP.resx new file mode 100644 index 00000000..bb068460 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ja-JP.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 削除済みアイテム + + + ライブラリに戻る + + + このライブラリに削除済みアイテムはありません。 + + + 本 + + + 削除日 + + + 復元 + + + 本が復元されました。 + + + 本を復元できませんでした。 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.resx new file mode 100644 index 00000000..7e3b8420 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Deleted items + + + Back to library + + + There are no deleted items in this library. + + + Book + + + Deleted on + + + Restore + + + The book was restored. + + + The book could not be restored. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ro-RO.resx new file mode 100644 index 00000000..ad189ab7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.ro-RO.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Elemente șterse + + + Înapoi la bibliotecă + + + Nu există elemente șterse în această bibliotecă. + + + Carte + + + Șters la + + + Restaurează + + + Cartea a fost restaurată. + + + Cartea nu a putut fi restaurată. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.uk-UA.resx new file mode 100644 index 00000000..48c42de0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.uk-UA.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Видалені елементи + + + Повернутися до бібліотеки + + + У цій бібліотеці немає видалених елементів. + + + Книга + + + Видалено + + + Відновити + + + Книгу відновлено. + + + Не вдалося відновити книгу. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.zh-CN.resx new file mode 100644 index 00000000..21443fce --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.zh-CN.resx @@ -0,0 +1,39 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 已删除项目 + + + 返回图书馆 + + + 此库中没有已删除项目。 + + + 图书 + + + 删除时间 + + + 恢复 + + + 图书已恢复。 + + + 无法恢复图书。 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx index d3ef82d9..33ad1231 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx @@ -57,4 +57,16 @@ عرض التفاصيل + + حذف + + + هل أنت متأكد من أنك تريد حذف هذا العنصر؟ + + + تعذر حذف العنصر. + + + العناصر المحذوفة + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx index af0edfce..9b90f101 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx @@ -57,4 +57,16 @@ Details anzeigen + + Löschen + + + Möchten Sie dieses Element wirklich löschen? + + + Das Element konnte nicht gelöscht werden. + + + Gelöschte Elemente + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx index 7effa290..4c555aad 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx @@ -57,4 +57,16 @@ View details + + Delete + + + Are you sure you want to delete this item? + + + The item could not be deleted. + + + Deleted items + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx index a9f6ee25..d4e8fe8a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx @@ -57,4 +57,16 @@ Ver detalles + + Eliminar + + + ¿Seguro que quieres eliminar este elemento? + + + No se ha podido eliminar el elemento. + + + Elementos eliminados + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx index 29e1131e..21e0d664 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx @@ -57,4 +57,16 @@ Voir les détails + + Supprimer + + + Voulez-vous vraiment supprimer cet élément ? + + + L'élément n'a pas pu être supprimé. + + + Éléments supprimés + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx index 4ba88908..a5222c99 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx @@ -57,4 +57,16 @@ Visualizza dettagli + + Elimina + + + Sei sicuro di voler eliminare questo elemento? + + + Non è stato possibile eliminare l'elemento. + + + Elementi eliminati + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx index 87fc1d44..dd54ebb9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx @@ -57,4 +57,16 @@ 詳細を表示 + + 削除 + + + この項目を削除してもよろしいですか? + + + 項目を削除できませんでした。 + + + 削除済みアイテム + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx index 7effa290..4c555aad 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx @@ -57,4 +57,16 @@ View details + + Delete + + + Are you sure you want to delete this item? + + + The item could not be deleted. + + + Deleted items + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx index 49c172e6..c6ab7900 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx @@ -57,4 +57,16 @@ Vezi detalii + + Șterge + + + Sigur doriți să ștergeți acest element? + + + Elementul nu a putut fi șters. + + + Elemente șterse + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx index 32a25ba4..8972c9e1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx @@ -57,4 +57,16 @@ Переглянути деталі + + Видалити + + + Ви впевнені, що хочете видалити цей елемент? + + + Не вдалося видалити елемент. + + + Видалені елементи + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx index 5b5e8e0f..f8cf6dcb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx @@ -57,4 +57,16 @@ 查看详情 + + 删除 + + + 确定要删除此项目吗? + + + 无法删除该项目。 + + + 已删除项目 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx index 4f656122..552adbfb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx @@ -1084,4 +1084,16 @@ إضافة وسم + + حذف الكتاب + + + تم حذف الكتاب. + + + هل أنت متأكد من أنك تريد حذف هذا العنصر؟ + + + تعذر حذف العنصر. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx index f1f7d6b3..9d77b677 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx @@ -1084,4 +1084,16 @@ Schlagwort hinzufügen + + Buch löschen + + + Das Buch wurde gelöscht. + + + Möchten Sie dieses Element wirklich löschen? + + + Das Element konnte nicht gelöscht werden. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx index 74c6b4b1..5dcdd2e5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx @@ -1084,4 +1084,16 @@ Add tag + + Delete book + + + The book was deleted. + + + Are you sure you want to delete this item? + + + The item could not be deleted. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx index da9d9f76..38c6d124 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx @@ -1084,4 +1084,16 @@ Añadir etiqueta + + Eliminar libro + + + El libro se ha eliminado. + + + ¿Seguro que quieres eliminar este elemento? + + + El elemento no se ha podido eliminar. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx index dbd947a3..c736b831 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx @@ -1084,4 +1084,16 @@ Ajouter une étiquette + + Supprimer le livre + + + Le livre a été supprimé. + + + Voulez-vous vraiment supprimer cet élément ? + + + L'élément n'a pas pu être supprimé. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx index 49563b81..da54e758 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx @@ -1084,4 +1084,16 @@ Aggiungi etichetta + + Elimina libro + + + Il libro è stato eliminato. + + + Sei sicuro di voler eliminare questo elemento? + + + Non è stato possibile eliminare l'elemento. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx index c4e14af4..392a94a4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx @@ -1084,4 +1084,16 @@ タグを追加 + + 本を削除 + + + 本が削除されました。 + + + この項目を削除してもよろしいですか? + + + 項目を削除できませんでした。 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx index 32921a56..cd50688c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx @@ -1083,4 +1083,16 @@ Add tag + + Delete book + + + The book was deleted. + + + Are you sure you want to delete this item? + + + The item could not be deleted. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx index 6308c039..d4ad4a1e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx @@ -1084,4 +1084,16 @@ Adaugă etichetă + + Șterge cartea + + + Cartea a fost ștearsă. + + + Sigur doriți să ștergeți acest element? + + + Elementul nu a putut fi șters. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx index 2ec59fb9..ac11ec59 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx @@ -1084,4 +1084,16 @@ Додати тег + + Видалити книгу + + + Книгу видалено. + + + Ви впевнені, що хочете видалити цей елемент? + + + Не вдалося видалити елемент. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx index 9795406a..720a9569 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx @@ -1084,4 +1084,16 @@ 添加标签 + + 删除图书 + + + 图书已删除。 + + + 确定要删除此项目吗? + + + 无法删除该项目。 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml index acc9b416..8ab3ec42 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/ManagePermissions.cshtml @@ -127,7 +127,7 @@ const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.UPDATE_USER_AUTHORIZATION)', formData); if (result.success) - notificationService.show('@_localizer["UserAuthorizationUpdated"]', NotificationType.SUCCESS); + notificationService.show(@Json.Serialize(_localizer["UserAuthorizationUpdated"].Value), NotificationType.SUCCESS); } async function fetchUserRoleAsync(userId) { @@ -178,7 +178,7 @@ // Users dropdown change. if (e.target.closest('#authorization-users-combobox .enlightenment-option')) { var selectedUserId = e.target.dataset.value; - document.querySelector('#authorization-roles-combobox .enlightenment-selected-text').textContent = '@_localizer["SelectARole"]'; + document.querySelector('#authorization-roles-combobox .enlightenment-selected-text').textContent = @Json.Serialize(_localizer["SelectARole"].Value); document.querySelectorAll("input[name='authorization-permissions-permissions']").forEach(input => input.checked = false); roleIdInput.value = ''; userIdInput.value = ''; diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml index 048c0efb..95455ad5 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/ManageRoles.cshtml @@ -112,7 +112,7 @@ { success: (await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.CREATE_ROLE)', formData)) !== undefined }; if (result.success) { await fetchRolesAsync(); - notificationService.show(isRoleSelected ? '@_localizer["RoleUpdated"]' : '@_localizer["RoleCreated"]', NotificationType.SUCCESS); + notificationService.show(isRoleSelected ? @Json.Serialize(_localizer["RoleUpdated"].Value) : @Json.Serialize(_localizer["RoleCreated"].Value), NotificationType.SUCCESS); } } @@ -136,7 +136,7 @@ }); // Update the text of the toggle button of the combobox. - document.querySelector('.enlightenment-selected-text').textContent = '@_localizer["SelectARole"]'; + document.querySelector('.enlightenment-selected-text').textContent = @Json.Serialize(_localizer["SelectARole"].Value); // All permissions should be "unchecked". document.querySelectorAll("input[name='authorization-role-permissions']") @@ -147,7 +147,7 @@ btnDeleteRole.classList.add('hidden'); // The "update" button should be "create". - btnConfirmRole.textContent = '@_localizer["CreateRole"]'; + btnConfirmRole.textContent = @Json.Serialize(_localizer["CreateRole"].Value); // The input for the role name should also have its text emptied. txtRoleName.value = ''; @@ -195,12 +195,12 @@ // On delete role button click. const handleBtnDeleteRoleClick = async function(e) { // Ask the user for confirmation before deleting the role. - if (await dialogService.show('@_localizer["DeleteRoleConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { + if (await dialogService.show(@Json.Serialize(_localizer["DeleteRoleConfirm"].Value), jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Admin.DELETE_ROLE, new { roleId = default(Guid) })'; const success = await callApiDeleteAsync(url.replace('/@(default(Guid))', `/${roleIdInput.value}`)); // roleId needs to be replaced here, because GetAbsoluteUrl is server side, roleId is client side. if (success) { await fetchRolesAsync(); - notificationService.show('@_localizer["RoleDeleted"]', NotificationType.SUCCESS); + notificationService.show(@Json.Serialize(_localizer["RoleDeleted"].Value), NotificationType.SUCCESS); } } }; @@ -218,13 +218,13 @@ if (roleId) { btnDeleteRole.classList.remove('hidden'); btnDeleteRole.classList.add('inline'); - btnConfirmRole.textContent = '@_localizer["UpdateRole"]'; + btnConfirmRole.textContent = @Json.Serialize(_localizer["UpdateRole"].Value); roleIdInput.value = roleId; } else { roleIdInput.value = ''; btnDeleteRole.classList.remove('inline'); btnDeleteRole.classList.add('hidden'); - btnConfirmRole.textContent = '@_localizer["CreateRole"]'; + btnConfirmRole.textContent = @Json.Serialize(_localizer["CreateRole"].Value); } } }; diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Plugins.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Plugins.cshtml index 5f263628..8483eaa7 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Plugins.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Plugins.cshtml @@ -181,7 +181,7 @@ const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Plugins.UPDATE_PLUGIN_SETTINGS)'; const result = await callApiPutAsync(url, { pluginId: pluginId, settings: settings }); if (result.success) { - notificationService.show('@_localizer["SettingsSaved"]', NotificationType.SUCCESS); + notificationService.show(@Json.Serialize(_localizer["SettingsSaved"].Value), NotificationType.SUCCESS); } } }; @@ -205,10 +205,10 @@ body: formData }); if (response.ok) { - notificationService.show('@_localizer["PluginUploadedRestartRequired"]', NotificationType.SUCCESS); + notificationService.show(@Json.Serialize(_localizer["PluginUploadedRestartRequired"].Value), NotificationType.SUCCESS); uploadInput.value = ''; } else { - notificationService.show('@_localizer["UploadFailed"]', NotificationType.ERROR); + notificationService.show(@Json.Serialize(_localizer["UploadFailed"].Value), NotificationType.ERROR); } } diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml index de2ad4d5..e3cd5c4f 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml @@ -166,29 +166,29 @@ It keeps the DOM contract the client script binds to, without any images or colo // Localized strings. const schedulerStrings = { - noJobs: '@_localizer["NoJobs"]', - daily: '@_localizer["DailySchedule"]', - interval: '@_localizer["IntervalSchedule"]', - startup: '@_localizer["StartupSchedule"]', - jobStarted: '@_localizer["JobStarted"]', - jobRemoved: '@_localizer["JobRemoved"]', - jobStopped: '@_localizer["JobStopped"]', - jobFired: '@_localizer["JobFired"]', - jobAdded: '@_localizer["JobAdded"]', - jobNotFound: '@_localizer["JobNotFound"]', - jobAlreadyRunning: '@_localizer["JobAlreadyRunning"]', + noJobs: @Json.Serialize(_localizer["NoJobs"].Value), + daily: @Json.Serialize(_localizer["DailySchedule"].Value), + interval: @Json.Serialize(_localizer["IntervalSchedule"].Value), + startup: @Json.Serialize(_localizer["StartupSchedule"].Value), + jobStarted: @Json.Serialize(_localizer["JobStarted"].Value), + jobRemoved: @Json.Serialize(_localizer["JobRemoved"].Value), + jobStopped: @Json.Serialize(_localizer["JobStopped"].Value), + jobFired: @Json.Serialize(_localizer["JobFired"].Value), + jobAdded: @Json.Serialize(_localizer["JobAdded"].Value), + jobNotFound: @Json.Serialize(_localizer["JobNotFound"].Value), + jobAlreadyRunning: @Json.Serialize(_localizer["JobAlreadyRunning"].Value), taskTypeNames: { - ScanMediaLibraries: '@_localizer["TaskType.ScanMediaLibraries"]', - CleanTemporaryFiles: '@_localizer["TaskType.CleanTemporaryFiles"]', - RepairThemes: '@_localizer["TaskType.RepairThemes"]', - CleanScheduledJobExecutionHistory: '@_localizer["TaskType.CleanScheduledJobExecutionHistory"]', - TechnicalDataCleanup: '@_localizer["TaskType.TechnicalDataCleanup"]' + ScanMediaLibraries: @Json.Serialize(_localizer["TaskType.ScanMediaLibraries"].Value), + CleanTemporaryFiles: @Json.Serialize(_localizer["TaskType.CleanTemporaryFiles"].Value), + RepairThemes: @Json.Serialize(_localizer["TaskType.RepairThemes"].Value), + CleanScheduledJobExecutionHistory: @Json.Serialize(_localizer["TaskType.CleanScheduledJobExecutionHistory"].Value), + TechnicalDataCleanup: @Json.Serialize(_localizer["TaskType.TechnicalDataCleanup"].Value) }, statusNames: { - Added: '@_localizer["Status.Added"]', - Active: '@_localizer["Status.Active"]', - Running: '@_localizer["Status.Running"]', - Completed: '@_localizer["Status.Completed"]' + Added: @Json.Serialize(_localizer["Status.Added"].Value), + Active: @Json.Serialize(_localizer["Status.Active"].Value), + Running: @Json.Serialize(_localizer["Status.Running"].Value), + Completed: @Json.Serialize(_localizer["Status.Completed"].Value) } }; @@ -365,7 +365,7 @@ It keeps the DOM contract the client script binds to, without any images or colo ${escapeHtml(job.name)} ${schedulerStrings.taskTypeNames[job.taskType] ?? job.taskType} ${scheduleLabel} - ${isInterval ? job.intervalMinutes + ' ' + '@_localizer["MinutesShort"]' : '-'} + ${isInterval ? job.intervalMinutes + ' ' + @Json.Serialize(_localizer["MinutesShort"].Value) : '-'} ${isDaily ? String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0') : '-'} ${schedulerStrings.statusNames[job.status] ?? job.status} ${formatDateTime(job.lastStartedOnUtc)} @@ -381,11 +381,11 @@ It keeps the DOM contract the client script binds to, without any images or colo const isRunning = job.status === 'Running'; const isActive = job.status === 'Active'; const canStop = isActive || isRunning; - actionsDiv.appendChild(createActionButton('@_localizer["Start"]', () => startJobAsync(job.id), canStop)); - actionsDiv.appendChild(createActionButton('@_localizer["Stop"]', () => stopJobAsync(job.id), !canStop)); - actionsDiv.appendChild(createActionButton('@_localizer["Fire"]', () => fireJobAsync(job.id), isRunning)); + actionsDiv.appendChild(createActionButton(@Json.Serialize(_localizer["Start"].Value), () => startJobAsync(job.id), canStop)); + actionsDiv.appendChild(createActionButton(@Json.Serialize(_localizer["Stop"].Value), () => stopJobAsync(job.id), !canStop)); + actionsDiv.appendChild(createActionButton(@Json.Serialize(_localizer["Fire"].Value), () => fireJobAsync(job.id), isRunning)); // The cycle of a job that was started must be stopped before the job can be removed. - actionsDiv.appendChild(createActionButton('@_localizer["Remove"]', () => removeJobAsync(job.id), canStop)); + actionsDiv.appendChild(createActionButton(@Json.Serialize(_localizer["Remove"].Value), () => removeJobAsync(job.id), canStop)); actionsCell.appendChild(actionsDiv); row.appendChild(actionsCell); @@ -679,7 +679,7 @@ It keeps the DOM contract the client script binds to, without any images or colo } async function removeJobAsync(jobId) { - if (await dialogService.show('@_localizer["RemoveJobConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { + if (await dialogService.show(@Json.Serialize(_localizer["RemoveJobConfirm"].Value), jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { const removed = await callApiDeleteAsync(getJobActionUrl(removeJobUrlTemplate, jobId)); if (removed) notificationService.show(schedulerStrings.jobRemoved, NotificationType.SUCCESS); @@ -697,7 +697,7 @@ It keeps the DOM contract the client script binds to, without any images or colo minute: scheduleType === 'DailyAtHourAndMinute' ? Number(jobMinuteInput.value) : null }; if (!payload.name) { - notificationService.show('@_localizer["JobNameRequired"]', NotificationType.ERROR); + notificationService.show(@Json.Serialize(_localizer["JobNameRequired"].Value), NotificationType.ERROR); return; } const response = await callApiPostAsync(addJobUrl, payload); diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml index b8754b66..bff55b5a 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml @@ -180,7 +180,7 @@ const button = event.target.closest('.delete-theme-button'); if (!button) return; - if (await dialogService.show('@_localizer["DeleteThemeConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { + if (await dialogService.show(@Json.Serialize(_localizer["DeleteThemeConfirm"].Value), jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { await callApiDeleteAsync(button.dataset.url); refreshPageContent(); } @@ -238,7 +238,7 @@ if (response.ok) refreshPageContent(); else - notificationService.show('@_localizer["UploadFailed"]', NotificationType.ERROR); + notificationService.show(@Json.Serialize(_localizer["UploadFailed"].Value), NotificationType.ERROR); } // Opens the file picker when the upload button is clicked. diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml index cc63e49b..54d04c59 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml @@ -103,20 +103,20 @@ }; const jsLocalizedStrings = { - all: '@_localizer["All"]', - items: '@_localizer["Items"]', - of: '@_localizer["Of"]', - page: '@_localizer["Page"]', - sortAscending: '@_localizer["SortAscending"]', - sortDescending: '@_localizer["SortDescending"]', - viewDetails: '@_localizer["ViewDetails"]', - actions: '@_localizer["Actions"]', - play: '@_localizer["Play"]', - shuffle: '@_localizer["Shuffle"]', - deleteItem: '@_localizer["Delete"]', - deleteConfirm: '@_localizer["DeleteConfirm"]', - deleteFailed: '@_localizer["DeleteFailed"]', - addToPlaylist: '@_localizer["AddToPlaylist"]' + all: @Json.Serialize(_localizer["All"].Value), + items: @Json.Serialize(_localizer["Items"].Value), + of: @Json.Serialize(_localizer["Of"].Value), + page: @Json.Serialize(_localizer["Page"].Value), + sortAscending: @Json.Serialize(_localizer["SortAscending"].Value), + sortDescending: @Json.Serialize(_localizer["SortDescending"].Value), + viewDetails: @Json.Serialize(_localizer["ViewDetails"].Value), + actions: @Json.Serialize(_localizer["Actions"].Value), + play: @Json.Serialize(_localizer["Play"].Value), + shuffle: @Json.Serialize(_localizer["Shuffle"].Value), + deleteItem: @Json.Serialize(_localizer["Delete"].Value), + deleteConfirm: @Json.Serialize(_localizer["DeleteConfirm"].Value), + deleteFailed: @Json.Serialize(_localizer["DeleteFailed"].Value), + addToPlaylist: @Json.Serialize(_localizer["AddToPlaylist"].Value) }; function buildItemsUrl() { diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml index 378344c2..825ab0d2 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml @@ -975,23 +975,23 @@ // The localized labels of the release types, keyed by their canonical enum name. const releaseTypeLabels = { - 'Album': '@_localizer["Album"].Value', - 'Broadcast': '@_localizer["Broadcast"].Value', - 'Ep': '@_localizer["Ep"].Value', - 'Other': '@_localizer["Other"].Value', - 'Single': '@_localizer["Single"].Value', - 'AudioDrama': '@_localizer["AudioDrama"].Value', - 'AudioBook': '@_localizer["AudioBook"].Value', - 'Compilation': '@_localizer["Compilation"].Value', - 'DjMix': '@_localizer["DjMix"].Value', - 'Demo': '@_localizer["Demo"].Value', - 'FieldRecording': '@_localizer["FieldRecording"].Value', - 'Interview': '@_localizer["Interview"].Value', - 'Live': '@_localizer["Live"].Value', - 'Mixtape': '@_localizer["Mixtape"].Value', - 'Remix': '@_localizer["Remix"].Value', - 'Soundtrack': '@_localizer["Soundtrack"].Value', - 'SpokenWord': '@_localizer["SpokenWord"].Value' + 'Album': @Json.Serialize(_localizer["Album"].Value), + 'Broadcast': @Json.Serialize(_localizer["Broadcast"].Value), + 'Ep': @Json.Serialize(_localizer["Ep"].Value), + 'Other': @Json.Serialize(_localizer["Other"].Value), + 'Single': @Json.Serialize(_localizer["Single"].Value), + 'AudioDrama': @Json.Serialize(_localizer["AudioDrama"].Value), + 'AudioBook': @Json.Serialize(_localizer["AudioBook"].Value), + 'Compilation': @Json.Serialize(_localizer["Compilation"].Value), + 'DjMix': @Json.Serialize(_localizer["DjMix"].Value), + 'Demo': @Json.Serialize(_localizer["Demo"].Value), + 'FieldRecording': @Json.Serialize(_localizer["FieldRecording"].Value), + 'Interview': @Json.Serialize(_localizer["Interview"].Value), + 'Live': @Json.Serialize(_localizer["Live"].Value), + 'Mixtape': @Json.Serialize(_localizer["Mixtape"].Value), + 'Remix': @Json.Serialize(_localizer["Remix"].Value), + 'Soundtrack': @Json.Serialize(_localizer["Soundtrack"].Value), + 'SpokenWord': @Json.Serialize(_localizer["SpokenWord"].Value) }; // The order in which the release type groups are displayed, from the most common to the least common. const releaseTypeOrder = ['Album', 'Compilation', 'Ep', 'Live', 'Remix', 'Single', 'Soundtrack', 'Broadcast', 'AudioDrama', 'AudioBook', 'Demo', 'DjMix', 'FieldRecording', 'Interview', 'Mixtape', 'SpokenWord', 'Other']; diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml new file mode 100644 index 00000000..57b79adc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml @@ -0,0 +1,140 @@ +@* + FALLBACK DELETED ITEMS VIEW - READ BEFORE EDITING + + This view is the application fallback of the deleted items page of a book library, rendered only when the + active theme does not provide its own template for the page. It keeps the DOM contract and the client script + the theme template mirrors, so that restoring a deleted book keeps working even without the theme. + + /library/written-content-library/books-library/books/deleted-items?libraryId=... +*@ + +@using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary +@using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization + +@{ + // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); + var libraryId = Model.Library.Id?.ToString() ?? string.Empty; +} + +@inject IViewLocalizer _localizer +@inject IUrlService _urlService + +@model DeletedBooksPageDto + +@Html.AntiForgeryToken() + +
+
+
+
+
+ +
+
+

@_localizer["Title"]

+
+

@_localizer["NoDeletedItems"]

+ + + + + + + + + + @foreach (DeletedBookDto book in Model.DeletedBooks) + { + + + + + + } + +
@_localizer["BookTitle"]@_localizer["DeletedOn"]
@book.Title@book.DeletedOnUtc.ToString("g") + +
+
+
+ +@section Scripts { + + +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml index c4c87525..c85a8506 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml @@ -39,6 +39,7 @@ +
@@ -63,10 +64,14 @@ const cleanupFunctions = []; let isInitialized = false; let requestSequence = 0; + // Book Ids whose deletion request is already in flight, so a second click cannot send a duplicate request. + const booksBeingDeleted = new Set(); const libraryId = '@(Model.Id ?? Guid.Empty)'; const readUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) })'; const detailsUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) })'; + const deleteUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, new { bookId = default(Guid) })'; + const deletedBooksUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.DELETED_BOOKS)'; const availabilityUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) })'; // 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 booksContainer = document.getElementById('books-container'); @@ -75,6 +80,7 @@ const searchInput = document.getElementById('search-input'); const searchButton = document.getElementById('search-button'); const sortToggle = document.getElementById('sort-toggle'); + const btnDeletedBooks = document.getElementById('btn-deleted-books'); const countLabel = document.getElementById('count-label'); const alphaPicker = document.getElementById('alpha-picker'); const pagination = document.getElementById('pagination'); @@ -95,16 +101,19 @@ }; const jsLocalizedStrings = { - all: '@_localizer["All"]', - items: '@_localizer["Items"]', - of: '@_localizer["Of"]', - page: '@_localizer["Page"]', - sortAscending: '@_localizer["SortAscending"]', - sortDescending: '@_localizer["SortDescending"]', - readerUnavailable: '@_localizer["ReaderUnavailable"]', - readerDisabled: '@_localizer["ReaderDisabled"]', - read: '@_localizer["Read"]', - viewDetails: '@_localizer["ViewDetails"]' + all: @Json.Serialize(_localizer["All"].Value), + items: @Json.Serialize(_localizer["Items"].Value), + of: @Json.Serialize(_localizer["Of"].Value), + page: @Json.Serialize(_localizer["Page"].Value), + sortAscending: @Json.Serialize(_localizer["SortAscending"].Value), + sortDescending: @Json.Serialize(_localizer["SortDescending"].Value), + readerUnavailable: @Json.Serialize(_localizer["ReaderUnavailable"].Value), + readerDisabled: @Json.Serialize(_localizer["ReaderDisabled"].Value), + read: @Json.Serialize(_localizer["Read"].Value), + viewDetails: @Json.Serialize(_localizer["ViewDetails"].Value), + deleteItem: @Json.Serialize(_localizer["Delete"].Value), + deleteConfirm: @Json.Serialize(_localizer["DeleteConfirm"].Value), + deleteFailed: @Json.Serialize(_localizer["DeleteFailed"].Value) }; // Builds the URL of the retrieval endpoint, from the current state. @@ -213,17 +222,23 @@ menu.setAttribute('role', 'menu'); menu.innerHTML = ` ${jsLocalizedStrings.read} - ${jsLocalizedStrings.viewDetails}`; + ${jsLocalizedStrings.viewDetails} + ${jsLocalizedStrings.deleteItem}`; // Menu entries navigate through the same AJAX navigation used by the nav-links, so that the persistent chrome keeps running. + // The delete entry does not navigate, it deletes the book and reloads the list in place. menu.addEventListener('click', async event => { + const deleteItem = event.target.closest('.card-action-delete'); const menuItem = event.target.closest('a[role="menuitem"]'); if (!menuItem) return; event.preventDefault(); event.stopImmediatePropagation(); closeCardMenus(); - await updateContentAsync(menuItem.href, true); + if (deleteItem) + await deleteBookAsync(book.id, deleteItem); + else + await updateContentAsync(menuItem.href, true); }); // The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click. @@ -327,6 +342,33 @@ } } + // Deletes the book after confirmation, then reloads the list. + async function deleteBookAsync(bookId, actionElement) { + if (booksBeingDeleted.has(bookId)) + return; + booksBeingDeleted.add(bookId); + if (actionElement) { + actionElement.classList.add('disabled'); + actionElement.setAttribute('aria-disabled', 'true'); + } + try { + if (await dialogService.show(jsLocalizedStrings.deleteConfirm, jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) !== DialogButton.YES) + return; + const url = deleteUrlTemplate.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${encodeURIComponent(libraryId)}`; + const success = await callApiDeleteAsync(url); + if (success) + await loadItemsAsync(); + else + notificationService.show(jsLocalizedStrings.deleteFailed, NotificationType.ERROR); + } finally { + booksBeingDeleted.delete(bookId); + if (actionElement?.isConnected) { + actionElement.classList.remove('disabled'); + actionElement.removeAttribute('aria-disabled'); + } + } + } + // Updates the count label: total items when pagination is off, displayed range out of total when it is on. function updateCountLabel(response) { if (!countLabel) @@ -440,6 +482,11 @@ } } + // Navigates to the deleted items page of the library. + async function handleDeletedBooksAsync() { + await updateContentAsync(`${deletedBooksUrl}?libraryId=${encodeURIComponent(libraryId)}`, true); + } + // Navigates to the previous page. function handlePrevPageClick() { state.currentPage = Math.max(1, state.currentPage - 1); @@ -468,6 +515,7 @@ bindEventHandler(searchButton, 'click', handleSearch); bindEventHandler(searchInput, 'keydown', handleSearchKeydown); bindEventHandler(sortToggle, 'click', handleSortToggle); + bindEventHandler(btnDeletedBooks, 'click', handleDeletedBooksAsync); bindEventHandler(prevPageButton, 'click', handlePrevPageClick); bindEventHandler(nextPageButton, 'click', handleNextPageClick); document.addEventListener('keydown', handleAlphaKeydown); @@ -480,6 +528,7 @@ unbindEventHandler(searchButton, 'click', handleSearch); unbindEventHandler(searchInput, 'keydown', handleSearchKeydown); unbindEventHandler(sortToggle, 'click', handleSortToggle); + unbindEventHandler(btnDeletedBooks, 'click', handleDeletedBooksAsync); unbindEventHandler(prevPageButton, 'click', handlePrevPageClick); unbindEventHandler(nextPageButton, 'click', handleNextPageClick); document.removeEventListener('keydown', handleAlphaKeydown); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml index 0a76120b..43c2789e 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml @@ -527,6 +527,7 @@
+
@@ -545,6 +546,7 @@ const libraryId = '@libraryId'; const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)'; const saveUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`); + const deleteUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`); const coverUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.UPDATE_BOOK_COVER, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}`; // 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. @@ -554,6 +556,7 @@ const btnChangeCover = document.getElementById('btn-change-cover'); const btnBackToLibrary = document.getElementById('btn-back-to-library'); const btnSaveBook = document.getElementById('btn-save-book'); + const btnDeleteBook = document.getElementById('btn-delete-book'); const isbnsBody = document.getElementById('isbns-body'); const contributorsBody = document.getElementById('contributors-body'); const ratingsBody = document.getElementById('ratings-body'); @@ -570,6 +573,9 @@ coverSaved: @Json.Serialize(_localizer["CoverSaved"].Value), saveFailed: @Json.Serialize(_localizer["SaveFailed"].Value), coverUploadFailed: @Json.Serialize(_localizer["CoverUploadFailed"].Value), + bookDeleted: @Json.Serialize(_localizer["BookDeleted"].Value), + deleteConfirm: @Json.Serialize(_localizer["DeleteConfirm"].Value), + deleteFailed: @Json.Serialize(_localizer["DeleteFailed"].Value), noCover: @Json.Serialize(_localizer["NoCover"].Value), remove: @Json.Serialize(_localizer["Remove"].Value) }; @@ -698,6 +704,18 @@ } } + // Deletes the book after confirmation, then returns to the library page. + async function handleDeleteAsync() { + if (await dialogService.show(jsLocalizedStrings.deleteConfirm, jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) !== DialogButton.YES) + return; + const success = await callApiDeleteAsync(`${deleteUrl}?libraryId=${encodeURIComponent(libraryId)}`); + if (success) { + notificationService.show(jsLocalizedStrings.bookDeleted, NotificationType.SUCCESS); + await handleBackToLibraryAsync(); + } else + notificationService.show(jsLocalizedStrings.deleteFailed, NotificationType.ERROR); + } + // Opens the file picker that chooses the new cover image. function handleChangeCoverClick() { coverInput.click(); @@ -880,6 +898,7 @@ // Add listeners. btnSaveBook.addEventListener('click', handleSaveAsync); + btnDeleteBook.addEventListener('click', handleDeleteAsync); btnBackToLibrary.addEventListener('click', handleBackToLibraryAsync); btnChangeCover.addEventListener('click', handleChangeCoverClick); coverInput.addEventListener('change', handleCoverChangeAsync); @@ -898,6 +917,7 @@ // Register cleanup for these listeners. cleanupFunctions.push(() => { btnSaveBook.removeEventListener('click', handleSaveAsync); + btnDeleteBook.removeEventListener('click', handleDeleteAsync); btnBackToLibrary.removeEventListener('click', handleBackToLibraryAsync); btnChangeCover.removeEventListener('click', handleChangeCoverClick); coverInput.removeEventListener('change', handleCoverChangeAsync); diff --git a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml index 77316861..5cc427e0 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml @@ -409,7 +409,7 @@ }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData); if (data && data.isUpdated === true) { - notificationService.show('@_localizer["SettingsSaved"]', NotificationType.SUCCESS); + notificationService.show(@Json.Serialize(_localizer["SettingsSaved"].Value), NotificationType.SUCCESS); // The player lives in the layout and is not recreated by the navigation manager, so the saved playback and // VU meter settings are handed to it directly instead of waiting for a full page reload. if (window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance && typeof window.LuminaAudioPlayer.instance.reloadPreferencesAsync === 'function') diff --git a/src/Lumina.slnx b/src/Lumina.slnx index 0def3ed3..fa3ab402 100644 --- a/src/Lumina.slnx +++ b/src/Lumina.slnx @@ -249,6 +249,8 @@ + + diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs index 2fa6e5b2..ea61b73a 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs @@ -33,6 +33,8 @@ public class BookEntityFixture /// Optional. The file system path of the book. /// Optional. The title of the book. /// Optional. The original title of the book. + /// Optional. The date and time when the book was deleted. Only used when the book is marked as deleted. + /// Optional. Whether the book is marked as deleted. /// Whether the owned metadata collections (Tags, Genres, ISBNs, Ratings) should be included, or forced to empty collections. /// The created . public BookEntity Create( @@ -41,6 +43,8 @@ public class BookEntityFixture string? path = null, string? title = null, string? originalTitle = null, + DateTime? deletedOnUtc = null, + bool isDeleted = false, bool includeMetadata = true) { int releaseYear = Random.Shared.Next(2000, 2010); @@ -83,6 +87,8 @@ public class BookEntityFixture .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") .RuleFor(x => x.ISBNs, f => includeMetadata ? _isbnEntityFixture.CreateMany(f.Random.Number(1, 5)) : []) .RuleFor(x => x.Ratings, f => includeMetadata ? _bookRatingEntityFixture.CreateMany(f.Random.Number(1, 5)) : []) + .RuleFor(x => x.IsDeleted, isDeleted) + .RuleFor(x => x.DeletedOnUtc, f => isDeleted ? (deletedOnUtc ?? f.Date.Recent()) : null) .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandFixture.cs new file mode 100644 index 00000000..36209080 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the book belongs to, taken from the route. + /// Optional. The Id of the deleted book to restore, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the book Id should be included, or forced to . + /// The created . + public RestoreBookCommand Create( + string? libraryId = null, + string? bookId = null, + bool includeLibraryId = true, + bool includeBookId = true) + { + return new RestoreBookCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeBookId ? (bookId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// 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.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryFixture.cs new file mode 100644 index 00000000..4fbaacaf --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedBooksQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose deleted books are retrieved, taken from the route. + /// Whether the library Id should be included, or forced to . + /// The created . + public GetDeletedBooksQuery Create( + string? libraryId = null, + bool includeLibraryId = true) + { + return new GetDeletedBooksQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// 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.Contracts.Fixtures/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/DeletedBookResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/DeletedBookResponseFixture.cs new file mode 100644 index 00000000..a397f85d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/DeletedBookResponseFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeletedBookResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the deleted book. + /// Optional. The Id of the media library the deleted book belongs to. + /// Optional. The title of the deleted book. + /// Optional. The original title of the deleted book. + /// Optional. The file system path of the deleted book. + /// Optional. The date and time when the book was deleted. + /// Optional. The path of the cover image of the deleted book. + /// Whether the original title should be included, or forced to . + /// Whether the cover path should be included, or forced to . + /// The created . + public DeletedBookResponse Create( + Guid? id = null, + Guid? libraryId = null, + string? title = null, + string? originalTitle = null, + string? path = null, + DateTime? deletedOnUtc = null, + string? coverPath = null, + bool includeOriginalTitle = true, + bool includeCoverPath = true) + { + return new DeletedBookResponse( + id ?? _faker.Random.Guid(), + libraryId ?? _faker.Random.Guid(), + title ?? _faker.Lorem.Sentence(3), + includeOriginalTitle ? (originalTitle ?? _faker.Lorem.Sentence(3)) : null, + path ?? _faker.System.FilePath(), + deletedOnUtc ?? _faker.Date.Recent(), + includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null + ); + } + + /// + /// Creates a list of 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/DTO/WrittenContentLibrary/BookLibrary/DeletedBookDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/DeletedBookDtoFixture.cs new file mode 100644 index 00000000..73302566 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/DeletedBookDtoFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedBookDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The Id of the deleted book. + /// Optional. The Id of the media library the deleted book belongs to. + /// Optional. The title of the deleted book. + /// Optional. The original title of the deleted book. + /// Optional. The file system path of the deleted book. + /// Optional. The date and time when the book was deleted. + /// Optional. The relative path of the stored cover image of the deleted book. + /// Whether the original title should be included, or forced to . + /// Whether the cover path should be included, or forced to . + /// The created . + public DeletedBookDto Create( + Guid? id = null, + Guid? libraryId = null, + string? title = null, + string? originalTitle = null, + string? path = null, + DateTime? deletedOnUtc = null, + string? coverPath = null, + bool includeOriginalTitle = true, + bool includeCoverPath = true) + { + return new DeletedBookDto( + Id: id ?? _faker.Random.Guid(), + LibraryId: libraryId ?? _faker.Random.Guid(), + Title: title ?? _faker.Lorem.Sentence(), + OriginalTitle: includeOriginalTitle ? (originalTitle ?? _faker.Lorem.Sentence()) : null, + Path: path ?? _faker.System.FilePath(), + DeletedOnUtc: deletedOnUtc ?? _faker.Date.Recent(), + CoverPath: includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null + ); + } + + /// + /// 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.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs index b8acbc83..08234b18 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -51,7 +51,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); Guid libraryId = Guid.NewGuid(); BookEntity changedBook = _bookEntityFixture.Create(); @@ -91,7 +91,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); Guid libraryId = Guid.NewGuid(); BookEntity book = _bookEntityFixture.Create(); @@ -120,7 +120,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); Guid libraryId = Guid.NewGuid(); BookEntity enrichedBook = _bookEntityFixture.Create(); @@ -155,7 +155,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); Guid libraryId = Guid.NewGuid(); BookEntity book = _bookEntityFixture.Create(); @@ -189,7 +189,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity book = _bookEntityFixture.Create(); @@ -214,7 +214,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); Guid libraryId = Guid.NewGuid(); BookEntity existingBook = _bookEntityFixture.Create(); @@ -244,7 +244,7 @@ public class BookRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)]; book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)]; @@ -278,7 +278,7 @@ public class BookRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)]; book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)]; @@ -315,7 +315,7 @@ public class BookRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); Guid keptMediaContributorId = Guid.NewGuid(); BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId); @@ -348,7 +348,7 @@ public class BookRepositoryTests Guid userId = Guid.NewGuid(); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); Guid keptMediaContributorId = Guid.NewGuid(); BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId); @@ -380,7 +380,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); book.Tags = [_tagEntityFixture.Create(name: $"noop-book-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-book-tag-two-{Guid.NewGuid():N}")]; @@ -429,7 +429,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); string keptTagName = $"remove-book-tag-{Guid.NewGuid():N}"; string keptGenreName = $"remove-book-genre-{Guid.NewGuid():N}"; @@ -483,7 +483,7 @@ public class BookRepositoryTests anchorConnection.Open(); using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); Guid libraryId = Guid.NewGuid(); BookEntity bookOfLibrary = _bookEntityFixture.Create(); @@ -513,7 +513,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); context.Books.Add(_bookEntityFixture.Create(includeMetadata: false)); await context.SaveChangesAsync(); @@ -533,7 +533,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity firstBook = _bookEntityFixture.Create(includeMetadata: false); BookEntity secondBook = _bookEntityFixture.Create(includeMetadata: false); BookEntity thirdBook = _bookEntityFixture.Create(includeMetadata: false); @@ -559,7 +559,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); book.Tags = [_tagEntityFixture.Create(name: "HiddenTag")]; @@ -600,7 +600,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-include-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); book.Tags = [_tagEntityFixture.Create(name: "LoadedTag"), _tagEntityFixture.Create(name: "SecondLoadedTag")]; @@ -635,7 +635,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-boundary-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); const int BOOK_COUNT = 500; List books = CreateBooks(BOOK_COUNT); context.Books.AddRange(books); @@ -661,7 +661,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); const int BOOK_COUNT = 501; List books = CreateBooks(BOOK_COUNT); context.Books.AddRange(books); @@ -687,7 +687,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-min-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); MediaContributorEntity firstAuthor = _mediaContributorEntityFixture.Create(displayName: "Zoe Author"); MediaContributorEntity secondAuthor = _mediaContributorEntityFixture.Create(displayName: "Alice Author"); @@ -717,7 +717,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-requested-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity requestedBook = _bookEntityFixture.Create(includeMetadata: false); BookEntity bookNotRequested = _bookEntityFixture.Create(includeMetadata: false); MediaContributorEntity requestedAuthor = _mediaContributorEntityFixture.Create(displayName: "Requested Author"); @@ -746,7 +746,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); BookEntity book = _bookEntityFixture.Create(includeMetadata: false); MediaContributorEntity author = _mediaContributorEntityFixture.Create(); context.Books.Add(book); @@ -772,7 +772,7 @@ public class BookRepositoryTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext context = CreateContext(anchorConnection); - BookRepository sut = new(context); + BookRepository sut = new(context, Substitute.For()); const int BOOK_COUNT = 501; List books = CreateBooks(BOOK_COUNT); MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Shared Author"); diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Favorites/FavoriteRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Favorites/FavoriteRepositoryTests.cs index 5843f725..2e8dcc4f 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Favorites/FavoriteRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Favorites/FavoriteRepositoryTests.cs @@ -348,6 +348,30 @@ public class FavoriteRepositoryTests Assert.Equal((Guid?)expectedLibraryId, result.Value); } + [Fact] + public async Task GetMediaItemLibraryIdAsync_WhenTheBookIsSoftDeleted_ShouldReturnSuccessWithNull() + { + // Arrange + using SqliteConnection anchorConnection = CreateAnchorConnection("library-id-deleted-book"); + using LuminaDbContext context = CreateContext(anchorConnection); + FavoriteRepository sut = new(context); + BookEntity deletedBook = _bookEntityFixture.Create( + libraryId: Guid.NewGuid(), + path: $"/books/{Guid.NewGuid()}.epub", + isDeleted: true, + includeMetadata: false); + context.Books.Add(deletedBook); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetMediaItemLibraryIdAsync(FavoriteMediaKind.Book, deletedBook.Id, CancellationToken.None); + + // Assert + // A deleted book is hidden from the catalogue, so adding it to favorites is rejected as if the book did not exist. + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + [Fact] public async Task GetMediaItemLibraryIdAsync_WhenTheMediaItemDoesNotExist_ShouldReturnSuccessWithNull() { @@ -853,6 +877,38 @@ public class FavoriteRepositoryTests Assert.Null(item.Display); } + [Fact] + public async Task GetAllForUserAsync_WhenTheFavoritedBookIsDeleted_ShouldKeepTheFavoriteWithoutDisplayData() + { + // Arrange + using SqliteConnection anchorConnection = CreateAnchorConnection("list-deleted-book"); + using LuminaDbContext context = CreateContext(anchorConnection); + FavoriteRepository sut = new(context); + Guid userId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + BookEntity deletedBook = _bookEntityFixture.Create( + libraryId: libraryId, + path: $"/books/{Guid.NewGuid()}.epub", + title: "Deleted Book", + isDeleted: true, + includeMetadata: false); + FavoriteEntity favorite = CreateFavorite(userId, FavoriteMediaKind.Book, deletedBook.Id); + context.Books.Add(deletedBook); + context.Favorites.Add(favorite); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetAllForUserAsync(userId, FavoriteMediaKind.Book, paginationData: null, cancellationToken: CancellationToken.None); + + // Assert + // A deleted book is hidden from the catalogue, so its favorite must fall back to the unavailable state instead of exposing its display data. + Assert.False(result.IsFailure); + FavoriteItemDto item = Assert.Single(result.Value.Data); + Assert.Equal(favorite.Id, item.Favorite.Id); + Assert.Null(item.Display); + } + [Theory] [InlineData(FavoriteMediaKind.Video)] // planned kind, so no display data can be resolved yet [InlineData(FavoriteMediaKind.Photo)] // planned kind, so no display data can be resolved yet diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs index bcdede01..842b146f 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs @@ -47,7 +47,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); // Act await sut.BeginTransactionAsync(CancellationToken.None); @@ -67,7 +67,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); // Act @@ -95,7 +95,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); // Act await sut.CommitTransactionAsync(CancellationToken.None); @@ -115,7 +115,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); // Act @@ -142,7 +142,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); // Act await sut.RollbackTransactionAsync(CancellationToken.None); @@ -162,7 +162,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); // Act await sut.BeginTransactionAsync(CancellationToken.None); @@ -183,7 +183,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); // Act sut.Dispose(); @@ -203,7 +203,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); Guid libraryId = Guid.NewGuid(); BookEntity firstBook = _bookEntityFixture.Create(); firstBook.LibraryId = libraryId; @@ -237,7 +237,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); // Act IFavoriteRepository firstRepository = sut.FavoriteRepository; @@ -259,7 +259,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); Guid userId = Guid.NewGuid(); dbContext.Users.Add(_userEntityFixture.Create(id: userId)); Result userSaveResult = await sut.SaveChangesAsync(CancellationToken.None); @@ -303,7 +303,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); Guid userId = Guid.NewGuid(); UserEntity user = _userEntityFixture.Create(id: userId); FavoriteEntity favorite = _favoriteEntityFixture.Create( @@ -337,7 +337,7 @@ public class UnitOfWorkTests { using (dbContext) { - UnitOfWork sut = new(dbContext); + UnitOfWork sut = new(dbContext, Substitute.For()); dbContext.Users.Add(_userEntityFixture.Create(id: userId)); Guid mediaItemId = Guid.NewGuid(); // The fixture populates the update audit columns, so the test also proves the interceptor owns them on insert. diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs index cdf76a2f..50f3405e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs @@ -6,9 +6,10 @@ using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Art using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -21,6 +22,7 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Http; +using System.Net.Http.Json; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -64,7 +66,7 @@ public class DeleteBookEndpointTests : IClassFixture(); - Assert.Null(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId)); + BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId); + Assert.NotNull(book); + Assert.True(book!.IsDeleted); } [Fact] - public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldRemoveTheArtworkAndTheStoredCoverFile() + public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldKeepTheArtworkAndTheStoredCoverFileForRestore() { // Arrange Guid userId = GetCurrentUserId(); @@ -98,9 +102,45 @@ public class DeleteBookEndpointTests : IClassFixture(); - Assert.Null(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId)); - Assert.Null(await dbContext.Books.SelectMany(book => book.Artwork).FirstOrDefaultAsync(artwork => artwork.BookId == bookId)); - Assert.False(File.Exists(fullCoverPath)); + BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId); + Assert.NotNull(book); + Assert.True(book!.IsDeleted); + Assert.NotNull(await dbContext.Books.SelectMany(book => book.Artwork).FirstOrDefaultAsync(artwork => artwork.BookId == bookId)); + Assert.True(File.Exists(fullCoverPath)); + } + + [Fact] + public async Task DeleteBook_WhenBookIsSoftDeleted_ShouldHideItFromTheCatalogueAndReadingEndpoints() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId); + HttpResponseMessage deleteResponse = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}"); + deleteResponse.EnsureSuccessStatusCode(); + + // Act + HttpResponseMessage booksResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books"); + HttpResponseMessage booksLiteResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite"); + HttpResponseMessage bookResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}"); + HttpResponseMessage availabilityResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability"); + HttpResponseMessage manifestResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest"); + HttpResponseMessage sectionResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/section-1"); + HttpResponseMessage resourceResponse = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/resource-1"); + + // Assert + PaginatedResponse? books = await booksResponse.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(books); + Assert.Equal(0, books!.Count); + Assert.Empty(books.Data); + PaginatedResponse? booksLite = await booksLiteResponse.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(booksLite); + Assert.Equal(0, booksLite!.Count); + Assert.Empty(booksLite.Data); + await AssertNotFoundAsync(bookResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}"); + await AssertNotFoundAsync(availabilityResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability"); + await AssertNotFoundAsync(manifestResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest"); + await AssertNotFoundAsync(sectionResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/section-1"); + await AssertNotFoundAsync(resourceResponse, "BookNotFound", $"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/resource-1"); } [Fact] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs new file mode 100644 index 00000000..f4aff934 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs @@ -0,0 +1,179 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedBooksEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDeletedBooksEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetDeletedBooks_WhenLibraryHasDeletedBooks_ShouldReturnOnlyTheDeletedBooks() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + BookEntity deletedBook = await SeedBookAsync(libraryId, isDeleted: true, title: "Deleted Book"); + await SeedBookAsync(libraryId, isDeleted: false, title: "Active Book"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + DeletedBookResponse[]? books = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(books); + Assert.Single(books); + Assert.Equal(deletedBook.Id, books![0].Id); + Assert.Equal("Deleted Book", books[0].Title); + } + + [Fact] + public async Task GetDeletedBooks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/books/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task GetDeletedBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task GetDeletedBooks_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + /// + /// Seeds an ebook library 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 book in the provided library. + /// + /// The Id of the library that owns the book. + /// Whether the book is soft deleted. + /// The title of the book. + /// The seeded book. + private async Task SeedBookAsync(Guid libraryId, bool isDeleted, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: $"/books/{Guid.NewGuid():N}.epub", title: title, isDeleted: isDeleted, includeMetadata: false); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return book; + } + + /// + /// Seeds a user distinct from the authenticated test user 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/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs new file mode 100644 index 00000000..c640a193 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -0,0 +1,188 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; +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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task RestoreBook_WhenDeletedBookBelongsToAnOwnedLibrary_ShouldRestoreTheBook() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId); + Assert.NotNull(book); + Assert.False(book!.IsDeleted); + } + + [Fact] + public async Task RestoreBook_WhenBookIsNotDeleted_ShouldReturnBookNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, isDeleted: false); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreBook_WhenBookIsRestoredThroughDifferentLibrary_ShouldReturnBookNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (_, Guid bookId) = await SeedLibraryAndBookAsync(userId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task RestoreBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherLibraryId, Guid otherBookId) = await SeedLibraryAndBookAsync(otherUserId, isDeleted: true); + + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/books/{otherBookId}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Fact] + public async Task RestoreBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task RestoreBook_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity() + { + // Act + HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/not-a-guid/books/not-a-guid/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + } + + /// + /// Seeds an ebook library owned by and a book belonging to it. + /// + /// The Id of the user that owns the library. + /// Whether the seeded book is soft deleted. + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: $"/books/{Guid.NewGuid():N}.epub", isDeleted: isDeleted, includeMetadata: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return (libraryId, book.Id); + } + + /// + /// Seeds a user distinct from the authenticated test user 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/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs index a5329fea..deb99adf 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -66,6 +66,27 @@ public class GetThemeTemplateEndpointTests : IClassFixture(_jsonOptions); + Assert.NotNull(result); + Assert.Equal(themeId, result!.Theme.ThemeId); + Assert.Contains("btn-back-to-library", result.Template); + Assert.Contains("restoreUrlTemplate", result.Template); + } + [Fact] public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnNotFound() { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs new file mode 100644 index 00000000..51f3e9d6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; +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; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteBookEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteBookEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteBook_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/books/{bookId}"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId, libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + 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($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + [Fact] + public async Task DeleteBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId, libraryId); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + [Fact] + public async Task DeleteBook_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid(), Guid.NewGuid()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + /// + /// Builds the delete request for the book identified by the route, with the owning library passed through the query string. + /// + /// The route Id of the book to delete. + /// The Id of the media library the book belongs to. + /// The configured delete request. + private static HttpRequestMessage CreateDeleteRequest(Guid bookId, Guid libraryId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-delete-book?libraryId={libraryId}") + { + // The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs new file mode 100644 index 00000000..dba210e2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedBooksViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly DeletedBookDtoFixture _deletedBookDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeletedBooksViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeletedBooksView_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderDeletedBooksPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books"); + DeletedBookDto deletedBook = _deletedBookDtoFixture.Create(libraryId: libraryId, title: "Deleted Book"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/deleted-items", new[] { deletedBook }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains("Deleted Book", content); + Assert.Contains("deleted-books-table", content); + Assert.Contains($"libraries/{libraryId}/books/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task DeletedBooksView_WhenDeletedBookTitleContainsMarkup_ShouldEncodeIt() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books"); + DeletedBookDto deletedBook = _deletedBookDtoFixture.Create(libraryId: libraryId, title: ""); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/deleted-items", new[] { deletedBook }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("<script>alert", content); + Assert.DoesNotContain("", content); + } + + [Fact] + public async Task DeletedBooksView_WhenTheApiReturnsForbidden_ShouldRedirectWithoutLeakingDetails() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Books"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library); + string endpoint = $"libraries/{libraryId}/books/deleted-items"; + _apiFactory.ApiClientStub.RegisterGetException(endpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"), + HttpStatusCode.Forbidden, + endpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // A browser navigation that the API forbids is redirected to the access denied page, without rendering any of the forbidden data. + Assert.Equal(HttpStatusCode.Found, response.StatusCode); + Assert.NotNull(response.Headers.Location); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task DeletedBooksView_WhenCalledWithoutLibraryId_ShouldRedirectToHome() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/written-content-library/books-library/books/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/en-us", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs index e86bfe77..b657aa36 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookL using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; 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; @@ -50,5 +49,6 @@ public class EditBookViewEndpointTests : IClassFixture Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); Assert.Contains("A book", content); + Assert.Contains("btn-delete-book", content); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs index eb02aaee..b0297b4a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -50,9 +50,33 @@ public class BooksIndexViewEndpointTests : IClassFixture Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); Assert.Contains("search-input", content); + Assert.Contains("card-action-delete", content); Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled); } + [Fact] + public async Task BooksIndex_WhenTheCultureUsesApostrophes_ShouldSerializeTheLocalizedStringsAsJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Livres"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/fr-fr/library/written-content-library/books-library/books?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + // The apostrophes and accents are JSON-escaped, so the translations stay valid JavaScript string literals. + Assert.Contains("deleteFailed: \"L", content); + Assert.Contains("deleteConfirm: \"", content); + Assert.DoesNotContain("deleteFailed: '", content); + Assert.DoesNotContain("deleteConfirm: '", content); + } + [Fact] public async Task BooksIndex_WhenCalledByAuthenticatedUserWithoutLibraryId_ShouldRedirectToHome() { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs new file mode 100644 index 00000000..27aa079d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreBookEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RestoreBook_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/books/{bookId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId, libraryId); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + 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.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean()); + Assert.Contains($"libraries/{libraryId}/books/{bookId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint)); + } + + [Fact] + public async Task RestoreBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + _apiFactory.ApiClientStub.Reset(); + HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId, libraryId); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + [Fact] + public async Task RestoreBook_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + /// + /// Builds the restore request for the book identified by the route, with the owning library passed through the query string. + /// + /// The route Id of the book to restore. + /// The Id of the media library the book belongs to. + /// The configured restore request. + private static HttpRequestMessage CreateRestoreRequest(Guid bookId, Guid libraryId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-restore-book?libraryId={libraryId}") + { + // The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs new file mode 100644 index 00000000..9ae7c61c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedBooksEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly List _seededUsernames = []; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetDeletedBooksEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetDeletedBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // 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("Unauthorized", problemDetails["title"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetDeletedBooks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/deleted-items"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + [Fact] + public async Task GetDeletedBooks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedBook() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + const string TITLE = "Secret Deleted Book"; + const string PATH = "/private/deleted-book.epub"; + const string COVER_PATH = "/private/deleted-book-cover.jpg"; + (Guid libraryId, _) = await SeedLibraryAndDeletedBookAsync(victimUserId, TITLE, PATH, COVER_PATH); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books/deleted-items"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal); + Assert.DoesNotContain(PATH, content, StringComparison.Ordinal); + Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds an ebook library owned by , together with a deleted book and its cover. + /// + /// The Id of the user that owns the library. + /// The title of the deleted book. + /// The file system path of the deleted book. + /// The stored cover path of the deleted book. + /// The Id of the seeded library and the seeded book. + private async Task<(Guid libraryId, BookEntity book)> SeedLibraryAndDeletedBookAsync(Guid userId, string title, string path, string coverPath) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: path, title: title, isDeleted: true, includeMetadata: false); + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath)]; + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.EBook, contentLocations: [])); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return (libraryId, book); + } + + /// + /// Removes the users created by the tests. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs new file mode 100644 index 00000000..6baed8ff --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -0,0 +1,165 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly List _seededUsernames = []; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreBookEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task RestoreBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore"; + + // Act + HttpResponseMessage response = await _client.PostAsync(url, null); + + // 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("Unauthorized", problemDetails["title"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task RestoreBook_WithSQLInjectionInRouteIds_ShouldNotCorruptOrLeakData(string maliciousId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/books/{Uri.EscapeDataString(maliciousId)}/restore", null); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + } + + [Fact] + public async Task RestoreBook_WhenBookBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (Guid libraryId, Guid bookId) = await SeedLibraryAndDeletedBookAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/restore", null); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId); + Assert.NotNull(book); + Assert.True(book!.IsDeleted); + } + + [Fact] + public async Task RestoreBook_WhenBookIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + (Guid ownLibraryId, _) = await SeedLibraryAndDeletedBookAsync(actingUserId, isDeleted: false); + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimBookId) = await SeedLibraryAndDeletedBookAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/books/{victimBookId}/restore", null); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookEntity? victimBook = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == victimBookId); + Assert.NotNull(victimBook); + Assert.True(victimBook!.IsDeleted); + } + + /// + /// Seeds an ebook library owned by , together with a book in the requested deletion state. + /// + /// The Id of the user that owns the library. + /// Whether the seeded book is soft deleted. + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndDeletedBookAsync(Guid userId, bool isDeleted = true) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: $"/books/{Guid.NewGuid():N}.epub", isDeleted: isDeleted, includeMetadata: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.EBook, contentLocations: [])); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return (libraryId, book.Id); + } + + /// + /// Removes the users created by the tests. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs new file mode 100644 index 00000000..1157ea6d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; +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.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteBookEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteBookEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task DeleteBook_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverDeleteAnotherBook(string maliciousId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/books/{normalizedId}"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(maliciousId, libraryId.ToString()); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{libraryId}/books/{normalizedId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task DeleteBook_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{normalizedId}/books/{bookId}"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId.ToString(), maliciousLibraryId); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{normalizedId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + [Fact] + public async Task DeleteBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId.ToString(), libraryId.ToString()); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + [Fact] + public async Task DeleteBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + /// + /// Builds the delete request for the book identified by the route, with the owning library passed through the query string. + /// + /// The raw route value of the book Id. + /// The raw query value of the library Id. + /// The configured delete request. + private static HttpRequestMessage CreateDeleteRequest(string bookId, string libraryId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-delete-book?libraryId={Uri.EscapeDataString(libraryId)}") + { + // The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs new file mode 100644 index 00000000..76b01b3a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks; +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.WrittenContentLibrary.BookLibrary.Books.DeletedBooks; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedBooksViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeletedBooksViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeletedBooksView_WhenNotAuthenticated_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs new file mode 100644 index 00000000..292466e5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; +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.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreBookEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RestoreBook_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherBook(string maliciousId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/books/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, libraryId.ToString()); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{libraryId}/books/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint)); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RestoreBook_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid bookId = Guid.NewGuid(); + string normalizedId = Guid.Empty.ToString(); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{normalizedId}/books/{bookId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId.ToString(), maliciousLibraryId); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains($"libraries/{normalizedId}/books/{bookId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint)); + } + + [Fact] + public async Task RestoreBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + _apiFactory.ApiClientStub.Reset(); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + [Fact] + public async Task RestoreBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Act + HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.PostRequests); + } + + /// + /// Builds the restore request for the book identified by the route, with the owning library passed through the query string. + /// + /// The raw route value of the book Id. + /// The raw query value of the library Id. + /// The configured restore request. + private static HttpRequestMessage CreateRestoreRequest(string bookId, string libraryId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-restore-book?libraryId={Uri.EscapeDataString(libraryId)}") + { + // The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandlerTests.cs index 7fff63c6..de2fa382 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandlerTests.cs @@ -1,23 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook; using Lumina.Domain.Common.Primitives; -using Microsoft.Extensions.Logging; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -35,9 +29,6 @@ public class DeleteBookCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly IBookRepository _mockBookRepository; - private readonly ILibraryRepository _mockLibraryRepository; - private readonly IBookArtworkService _mockBookArtworkService; - private readonly ILogger _mockLogger; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; @@ -45,7 +36,6 @@ public class DeleteBookCommandHandlerTests private readonly Guid _userId; private readonly DeleteBookCommandFixture _deleteBookCommandFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); - private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -54,37 +44,30 @@ public class DeleteBookCommandHandlerTests { _mockUnitOfWork = Substitute.For(); _mockBookRepository = Substitute.For(); - _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); - _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); - _mockBookArtworkService = Substitute.For(); - _mockLogger = Substitute.For>(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the book has no author, the library exists, the artwork deletion succeeds, the book deletion succeeds and saving changes succeeds. + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the book exists, + // marking it as deleted succeeds, and saving changes succeeds. _mockValidator.Validate(Arg.Any()).Returns([]); _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(_ => Result.From(_libraryEntityFixture.Create())); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary())); - _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - _mockBookRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_bookEntityFixture.Create(includeMetadata: false))); + _mockBookRepository.SoftDeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); _mockUnitOfWork.SaveChangesAsync(Arg.Any()) .Returns(Result.Success); - _sut = new DeleteBookCommandHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + _sut = new DeleteBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } [Fact] - public async Task HandleAsync_WhenBookExists_ShouldDeleteBookAndReturnDeleted() + public async Task HandleAsync_WhenBookExists_ShouldSoftDeleteBookAndReturnDeleted() { // Arrange DeleteBookCommand command = _deleteBookCommandFixture.Create(); @@ -100,42 +83,12 @@ public class DeleteBookCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); - // The stored artwork of the book is removed before the book row, so that no artwork file is orphaned. - Received.InOrder(() => - { - _mockBookArtworkService.DeleteBookArtwork(libraryId, bookId, Arg.Any(), Arg.Any(), book.Title); - _mockBookRepository.DeleteByIdAsync(bookId, Arg.Any()); - }); - await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any()); + await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); } - [Fact] - public async Task HandleAsync_WhenBookHasAnAuthor_ShouldDeleteTheArtworkUnderTheAuthorSegments() - { - // Arrange - DeleteBookCommand command = _deleteBookCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid bookId = Guid.Parse(command.BookId!); - BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false); - LibraryEntity library = _libraryEntityFixture.Create(id: libraryId); - _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(library)); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [bookId] = "J.R.R. Tolkien" })); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - _mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId, bookId, library.Title, "J.R.R. Tolkien", book.Title); - } - [Fact] public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() { @@ -151,8 +104,7 @@ public class DeleteBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(DomainErrors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -187,7 +139,7 @@ public class DeleteBookCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -251,14 +203,12 @@ public class DeleteBookCommandHandlerTests Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting() + public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving() { // Arrange DeleteBookCommand command = _deleteBookCommandFixture.Create(); @@ -267,7 +217,7 @@ public class DeleteBookCommandHandlerTests BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false); _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + _mockBookRepository.SoftDeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); // Act @@ -276,101 +226,7 @@ public class DeleteBookCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() - { - // Arrange - DeleteBookCommand command = _deleteBookCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid bookId = Guid.Parse(command.BookId!); - BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false); - _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(_ => Result.From(null)); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); - _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenAuthorLookupFails_ShouldReturnErrorWithoutDeleting() - { - // Arrange - DeleteBookCommand command = _deleteBookCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid bookId = Guid.Parse(command.BookId!); - BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false); - _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(book)); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenArtworkDeletionFails_ShouldStillDeleteTheBook() - { - // Arrange - DeleteBookCommand command = _deleteBookCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid bookId = Guid.Parse(command.BookId!); - BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false); - _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(book)); - _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure(description: "Failed to delete the artwork")); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - // A stale cover file must not prevent the book from being removed. - Assert.False(result.IsFailure); - Assert.Equal(Result.Deleted, result.Value); - await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenDeleteBookFails_ShouldReturnErrorWithoutSaving() - { - // Arrange - DeleteBookCommand command = _deleteBookCommandFixture.Create(); - Guid libraryId = Guid.Parse(command.LibraryId!); - Guid bookId = Guid.Parse(command.BookId!); - BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false); - _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) - .Returns(Result.From(book)); - _mockBookRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) - .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any()); + await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -393,6 +249,6 @@ public class DeleteBookCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); - await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any()); + await _mockBookRepository.Received(1).SoftDeleteByIdAsync(bookId, Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandHandlerTests.cs new file mode 100644 index 00000000..8efc8df4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandHandlerTests.cs @@ -0,0 +1,253 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly RestoreBookCommandHandler _sut; + private readonly Guid _userId; + private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreBookCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, the deleted + // book exists, restoring it succeeds, and saving changes succeeds. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_bookEntityFixture.Create(isDeleted: true, includeMetadata: false))); + _mockBookRepository.RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Success); + + _sut = new RestoreBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenDeletedBookExists_ShouldRestoreBookAndReturnUpdated() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid bookId = Guid.Parse(command.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false); + _mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any()) + .Returns(Result.From(book)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.WrittenContent.BookIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); + await _mockBookRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.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 _mockBookRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookRepositoryFails_ShouldReturnFailureResultWithoutRestoring() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + _mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletedBookDoesNotExist_ShouldReturnBookNotFoundError() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + _mockBookRepository.GetSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + Guid bookId = Guid.Parse(command.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid(), isDeleted: true, includeMetadata: false); + _mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any()) + .Returns(Result.From(book)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid bookId = Guid.Parse(command.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false); + _mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any()) + .Returns(Result.From(book)); + _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 _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockBookRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid bookId = Guid.Parse(command.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false); + _mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any()) + .Returns(Result.From(book)); + _mockBookRepository.RestoreSoftDeletedByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid bookId = Guid.Parse(command.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, isDeleted: true, includeMetadata: false); + _mockBookRepository.GetSoftDeletedByIdAsync(bookId, Arg.Any()) + .Returns(Result.From(book)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockBookRepository.Received(1).RestoreSoftDeletedByIdAsync(bookId, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandValidatorTests.cs new file mode 100644 index 00000000..fae33925 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/RestoreBook/RestoreBookCommandValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; +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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookCommandValidatorTests +{ + private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new(); + private readonly RestoreBookCommandValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-book-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId) + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(bookId: bookId, includeBookId: bookId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(bookId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + RestoreBookCommand command = _restoreBookCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryHandlerTests.cs new file mode 100644 index 00000000..88d773f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryHandlerTests.cs @@ -0,0 +1,179 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedBooksQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetDeletedBooksQueryHandler _sut; + private readonly Guid _userId; + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDeletedBooksQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the query is valid, the current user is authenticated and the library ownership policy allows access. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockBookRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + _sut = new GetDeletedBooksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenDeletedBooksExist_ShouldReturnTheirMappedResponses() + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + string coverFileName = $"covers/{Guid.NewGuid()}.jpg"; + BookEntity firstBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, includeMetadata: false); + firstBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: firstBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverFileName)]; + BookEntity secondBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, includeMetadata: false); + _mockBookRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([firstBook, secondBook])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(firstBook.Id, result.Value[0].Id); + Assert.Equal(firstBook.LibraryId, result.Value[0].LibraryId); + Assert.Equal(firstBook.Title, result.Value[0].Title); + Assert.Equal(firstBook.OriginalTitle, result.Value[0].OriginalTitle); + Assert.Equal(firstBook.Path, result.Value[0].Path); + Assert.Equal(firstBook.DeletedOnUtc ?? firstBook.CreatedOnUtc, result.Value[0].DeletedOnUtc); + Assert.Equal(coverFileName, result.Value[0].CoverPath); + Assert.Equal(secondBook.Id, result.Value[1].Id); + } + + [Fact] + public async Task HandleAsync_WhenThereAreNoDeletedBooks_ShouldReturnAnEmptyCollection() + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.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); + await _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, 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 _mockBookRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(); + _mockBookRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryValidatorTests.cs new file mode 100644 index 00000000..de83df09 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetDeletedBooks/GetDeletedBooksQueryValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; +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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedBooksQueryValidatorTests +{ + private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new(); + private readonly GetDeletedBooksQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetDeletedBooksQuery query = _getDeletedBooksQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs index 9f3aa5ef..2c5bf69f 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -21,6 +22,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; +using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -38,6 +40,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary; public class BookRepositoryTests { private readonly LuminaDbContext _mockContext; + private readonly IDateTimeProvider _mockDateTimeProvider; private readonly BookRepository _sut; private readonly BookEntityFixture _bookEntityFixture = new(); private readonly BookRatingEntityFixture _bookRatingEntityFixture = new(); @@ -57,7 +60,9 @@ public class BookRepositoryTests public BookRepositoryTests() { _mockContext = Create.MockedDbContextFor(); - _sut = new BookRepository(_mockContext); + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc)); + _sut = new BookRepository(_mockContext, _mockDateTimeProvider); } [Fact] @@ -120,6 +125,25 @@ public class BookRepositoryTests Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError); } + [Fact] + public async Task InsertAsync_WhenADeletedBookHasTheSamePath_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true); + _mockContext.Books.Add(deletedBook); + await _mockContext.SaveChangesAsync(); + BookEntity bookModel = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub"); + + // Act + Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); + + // Assert + // The deleted book keeps its path as a tombstone, so a scan can never insert it again. + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError); + } + [Fact] public async Task InsertAsync_WhenAnotherLibraryHasABookWithTheSamePath_ShouldAddBookToContextAndReturnCreated() { @@ -299,6 +323,24 @@ public class BookRepositoryTests Assert.Equal(book.Id, result.Value!.Id); } + [Fact] + public async Task GetByPathAsync_WhenBookIsDeleted_ShouldReturnIt() + { + // Arrange + BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true); + _mockContext.Books.Add(deletedBook); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByPathAsync(deletedBook.LibraryId, deletedBook.Path, CancellationToken.None); + + // Assert + // The scan deletion strategy must find the deleted row when its file disappears, so that it can remove it permanently. + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(deletedBook.Id, result.Value!.Id); + } + [Fact] public async Task GetByPathAsync_WhenBookDoesNotExist_ShouldReturnNull() { @@ -383,6 +425,198 @@ public class BookRepositoryTests Assert.Empty(result.Value); } + [Fact] + public async Task GetAllAsync_WhenBooksAreDeleted_ShouldExcludeThem() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity activeBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/active.epub"); + BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true); + _mockContext.Books.AddRange(activeBook, deletedBook); + await _mockContext.SaveChangesAsync(); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(filterModel: filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value.Data); + Assert.Equal(activeBook.Id, result.Value.Data[0].Id); + } + + [Fact] + public async Task GetByIdAsync_WhenBookIsDeleted_ShouldReturnNull() + { + // Arrange + BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true); + _mockContext.Books.Add(deletedBook); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(deletedBook.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenBookIsDeleted_ShouldStillReportItsPathAsExisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true); + _mockContext.Books.Add(deletedBook); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetExistingPathsAsync(libraryId, ["/books/deleted.epub"], CancellationToken.None); + + // Assert + // The path must keep counting as taken, so that a scan never materializes the deleted book back into the catalogue. + Assert.False(result.IsFailure); + Assert.Equal(["/books/deleted.epub"], result.Value); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedBooksOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity activeBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/active.epub"); + BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, path: "/books/deleted.epub", isDeleted: true); + BookEntity otherLibraryDeletedBook = _bookEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/books/other.epub", isDeleted: true); + _mockContext.Books.AddRange(activeBook, deletedBook, otherLibraryDeletedBook); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal(deletedBook.Id, result.Value[0].Id); + } + + [Fact] + public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldOrderByTheStoredDeletionTime() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity olderDeletion = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-2)); + olderDeletion.UpdatedOnUtc = DateTime.UtcNow; + BookEntity newerDeletion = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-1)); + newerDeletion.UpdatedOnUtc = DateTime.UtcNow.AddHours(-3); + _mockContext.Books.AddRange(olderDeletion, newerDeletion); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + // A later write to a deleted row may change its update time, but it must not change the order of the deleted items. + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(newerDeletion.Id, result.Value[0].Id); + Assert.Equal(olderDeletion.Id, result.Value[1].Id); + } + + [Fact] + public async Task GetSoftDeletedByIdAsync_WhenBookIsNotDeleted_ShouldReturnNull() + { + // Arrange + BookEntity activeBook = _bookEntityFixture.Create(); + _mockContext.Books.Add(activeBook); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetSoftDeletedByIdAsync(activeBook.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenCalled_ShouldSetTheDeletionStateAndTime() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.SoftDeleteByIdAsync(book.Id, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.True(book.IsDeleted); + Assert.Equal(_mockDateTimeProvider.UtcNow, book.DeletedOnUtc); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenBookIsAlreadyDeleted_ShouldReturnBookNotFoundError() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(isDeleted: true); + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.SoftDeleteByIdAsync(book.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(isDeleted: true, deletedOnUtc: DateTime.UtcNow.AddHours(-1)); + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(book.Id, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(book.IsDeleted); + Assert.Null(book.DeletedOnUtc); + } + + [Fact] + public async Task RestoreSoftDeletedByIdAsync_WhenBookIsNotDeleted_ShouldReturnBookNotFoundError() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.RestoreSoftDeletedByIdAsync(book.Id, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + } + + [Fact] + public async Task SoftDeleteByIdAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError() + { + // Act + Result result = await _sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + } + [Fact] public async Task GetBooksNeedingMetadataAsync_WhenCalled_ShouldReturnOnlyBooksWhoseMetadataIsNotEnriched() { @@ -403,7 +637,11 @@ public class BookRepositoryTests BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending; - _mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary); + BookEntity deletedPendingBook = _bookEntityFixture.Create(isDeleted: true); + deletedPendingBook.LibraryId = libraryId; + deletedPendingBook.Path = "/books/d.epub"; + deletedPendingBook.MetadataStatus = MetadataStatus.Pending; + _mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary, deletedPendingBook); await _mockContext.SaveChangesAsync(); // Act @@ -414,6 +652,7 @@ public class BookRepositoryTests Assert.Equal(2, result.Value.Count); Assert.Contains(result.Value, book => book.Id == pendingBook.Id); Assert.Contains(result.Value, book => book.Id == failedBook.Id); + Assert.DoesNotContain(result.Value, book => book.Id == deletedPendingBook.Id); } [Fact] @@ -483,6 +722,8 @@ public class BookRepositoryTests Guid storedLibraryId = storedBook.LibraryId; string storedPath = storedBook.Path; + bool storedIsDeleted = storedBook.IsDeleted; + DateTime? storedDeletedOnUtc = storedBook.DeletedOnUtc; MetadataStatus storedMetadataStatus = storedBook.MetadataStatus; DateTime? storedLastMetadataUpdateUtc = storedBook.LastMetadataUpdateUtc; string? storedMetadataProvider = storedBook.MetadataProvider; @@ -493,6 +734,8 @@ public class BookRepositoryTests data.Title = "Updated Title"; data.LibraryId = Guid.NewGuid(); data.Path = "/books/updated.epub"; + data.IsDeleted = true; + data.DeletedOnUtc = DateTime.UtcNow; data.MetadataStatus = MetadataStatus.Enriched; data.LastMetadataUpdateUtc = DateTime.UtcNow; data.MetadataProvider = "UpdatedProvider"; @@ -501,10 +744,14 @@ public class BookRepositoryTests // Act Result result = await _sut.UpdateAsync(data, CancellationToken.None); + bool isDeletionStateModified = _mockContext.Entry(storedBook).Property(book => book.IsDeleted).IsModified; + bool isDeletionTimeModified = _mockContext.Entry(storedBook).Property(book => book.DeletedOnUtc).IsModified; await _mockContext.SaveChangesAsync(); // Assert Assert.False(result.IsFailure); + Assert.False(isDeletionStateModified); + Assert.False(isDeletionTimeModified); BookEntity? retrievedBook = await _mockContext.Books .Include(book => book.Tags) .Include(book => book.Genres) @@ -517,6 +764,8 @@ public class BookRepositoryTests // The identity, enrichment and audit columns of the stored book are never overwritten by an edit. Assert.Equal(storedLibraryId, retrievedBook.LibraryId); Assert.Equal(storedPath, retrievedBook.Path); + Assert.Equal(storedIsDeleted, retrievedBook.IsDeleted); + Assert.Equal(storedDeletedOnUtc, retrievedBook.DeletedOnUtc); Assert.Equal(storedMetadataStatus, retrievedBook.MetadataStatus); Assert.Equal(storedLastMetadataUpdateUtc, retrievedBook.LastMetadataUpdateUtc); Assert.Equal(storedMetadataProvider, retrievedBook.MetadataProvider); @@ -524,6 +773,27 @@ public class BookRepositoryTests Assert.Equal(storedCreatedBy, retrievedBook.CreatedBy); } + [Fact] + public async Task UpdateAsync_WhenBookIsDeleted_ShouldReturnBookNotFoundWithoutUpdatingIt() + { + // Arrange + BookEntity storedBook = _bookEntityFixture.Create(isDeleted: true); + _mockContext.Books.Add(storedBook); + await _mockContext.SaveChangesAsync(); + string storedTitle = storedBook.Title; + BookEntity data = _bookEntityFixture.Create(id: storedBook.Id); + data.Title = "Updated Title"; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + // A soft deleted book can only be brought back by the explicit restore operation, never by an edit. + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + Assert.Equal(storedTitle, storedBook.Title); + } + [Fact] public async Task UpdateAsync_WhenStoredBookHasArtwork_ShouldPreserveTheStoredArtwork() { @@ -832,7 +1102,11 @@ public class BookRepositoryTests BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); bookOfAnotherLibrary.Artwork = []; - _mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary); + BookEntity deletedBookWithoutCover = _bookEntityFixture.Create(isDeleted: true); + deletedBookWithoutCover.LibraryId = libraryId; + deletedBookWithoutCover.Path = "/books/d.epub"; + deletedBookWithoutCover.Artwork = []; + _mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary, deletedBookWithoutCover); await _mockContext.SaveChangesAsync(); // Act @@ -843,6 +1117,7 @@ public class BookRepositoryTests Assert.Equal(2, result.Value.Count); Assert.Contains(result.Value, book => book.Id == bookWithoutCover.Id); Assert.Contains(result.Value, book => book.Id == bookWithFailedCover.Id); + Assert.DoesNotContain(result.Value, book => book.Id == deletedBookWithoutCover.Id); } [Fact] @@ -859,7 +1134,10 @@ public class BookRepositoryTests BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); bookOfAnotherLibrary.Artwork = []; - _mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary); + BookEntity deletedBookWithoutCover = _bookEntityFixture.Create(isDeleted: true); + deletedBookWithoutCover.LibraryId = libraryId; + deletedBookWithoutCover.Artwork = []; + _mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary, deletedBookWithoutCover); await _mockContext.SaveChangesAsync(); // Act @@ -998,7 +1276,10 @@ public class BookRepositoryTests BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending; - _mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary); + BookEntity deletedPendingBook = _bookEntityFixture.Create(isDeleted: true); + deletedPendingBook.LibraryId = libraryId; + deletedPendingBook.MetadataStatus = MetadataStatus.Pending; + _mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary, deletedPendingBook); await _mockContext.SaveChangesAsync(); // Act @@ -1191,7 +1472,9 @@ public class BookRepositoryTests List books = _bookEntityFixture.CreateMany(3); foreach (BookEntity book in books) book.LibraryId = libraryId; + BookEntity deletedBook = _bookEntityFixture.Create(libraryId: libraryId, isDeleted: true); _mockContext.Books.AddRange(books); + _mockContext.Books.Add(deletedBook); await _mockContext.SaveChangesAsync(); PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); @@ -1204,6 +1487,7 @@ public class BookRepositoryTests Assert.False(result.IsFailure); Assert.Equal(3, result.Value.Count); Assert.Equal(3, result.Value.Data.Count); + Assert.DoesNotContain(result.Value.Data, row => row.Id == deletedBook.Id); Assert.Equal(1, result.Value.CurrentPage); Assert.Equal(10, result.Value.PerPage); Assert.Equal(1, result.Value.NumberOfPages); @@ -1492,6 +1776,24 @@ public class BookRepositoryTests Assert.DoesNotContain(result.Value, book => book.Id == secondBook.Id); } + [Fact] + public async Task GetByIdsAsync_WhenABookIsDeleted_ShouldExcludeIt() + { + // Arrange + BookEntity activeBook = _bookEntityFixture.Create(includeMetadata: false); + BookEntity deletedBook = _bookEntityFixture.Create(isDeleted: true, includeMetadata: false); + _mockContext.Books.AddRange(activeBook, deletedBook); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByIdsAsync([activeBook.Id, deletedBook.Id], false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal(activeBook.Id, result.Value[0].Id); + } + [Fact] public async Task GetByIdsAsync_WhenNavigationPropertiesShouldNotBeIncluded_ShouldReturnTheRequestedBooks() { diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index 67ffba60..ccd592c9 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -101,7 +101,7 @@ public class UnitOfWorkTests { // Arrange LuminaDbContext dbContext = _fixture.Create(); - UnitOfWork unitOfWork = new(dbContext); + UnitOfWork unitOfWork = new(dbContext, Substitute.For()); CancellationToken cancellationToken = new(); // Act @@ -121,7 +121,7 @@ public class UnitOfWorkTests .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) .Options; LuminaDbContext dbContext = new(options); - UnitOfWork unitOfWork = new(dbContext); + UnitOfWork unitOfWork = new(dbContext, Substitute.For()); dbContext.Roles.Add(_roleEntityFixture.Create(id: Guid.NewGuid(), roleName: "TestRole")); await dbContext.SaveChangesAsync(CancellationToken.None); Assert.NotEmpty(dbContext.ChangeTracker.Entries()); @@ -154,6 +154,6 @@ public class UnitOfWorkTests private UnitOfWork CreateUnitOfWork() { - return new(_fixture.Create()); + return new(_fixture.Create(), Substitute.For()); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs index 87fee63e..9f2ee948 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs @@ -107,6 +107,25 @@ public class BooksMediaLibraryScanItemMaterializerTests _mockPathTemplateService.Received(1).Parse(Arg.Any(), Arg.Any(), "Artist\\track.epub", '\\'); } + [Fact] + public async Task MaterializeItemsAsync_WhenPathIsAlreadyUsedByADeletedBook_ShouldNotInsertItAgain() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]); + _mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetExistingPathsAsync(_libraryId, Arg.Any>(), Arg.Any()) + .Returns(Result.From>(["C:\\Music\\deleted.epub"])); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\Music\\deleted.epub"), CancellationToken.None); + + // Assert + // A deleted book keeps its stored path, so the scan treats the file as already catalogued and never materializes it again. + Assert.False(result.IsFailure); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + /// /// Creates the set of media library scan snapshot paths that the media library scan produces. /// diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs index 81a6581a..2253c130 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Events; using Lumina.Presentation.Api.Common.Http; @@ -72,7 +73,7 @@ public class EventualConsistencyMiddlewareTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-abort-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext dbContext = CreateContext(anchorConnection); - using UnitOfWork unitOfWork = new(dbContext); + using UnitOfWork unitOfWork = new(dbContext, Substitute.For()); await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);"); CapturingHttpResponseFeature responseFeature = new(); DefaultHttpContext httpContext = new(); @@ -112,7 +113,7 @@ public class EventualConsistencyMiddlewareTests using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); using LuminaDbContext dbContext = CreateContext(anchorConnection); - using UnitOfWork unitOfWork = new(dbContext); + using UnitOfWork unitOfWork = new(dbContext, Substitute.For()); await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);"); CapturingHttpResponseFeature responseFeature = new(); DefaultHttpContext httpContext = new(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs new file mode 100644 index 00000000..d0a6d38a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetDeletedBooks/GetDeletedBooksEndpointTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks; +using Lumina.Contracts.Fixtures.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetDeletedBooksEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetDeletedBooksEndpoint _sut; + private readonly DeletedBookResponseFixture _deletedBookResponseFixture = new(); + private readonly GetDeletedBooksQueryFixture _getDeletedBooksQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetDeletedBooksEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedBooks() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + IReadOnlyList expectedBooks = + [ + _deletedBookResponseFixture.Create( + libraryId: libraryId, + title: "The Hobbit", + includeOriginalTitle: false, + includeCoverPath: false) + ]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedBooks)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedBooks, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + GetDeletedBooksQuery expectedQuery = _getDeletedBooksQueryFixture.Create(libraryId: libraryId.ToString()); + await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + 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>([]); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs new file mode 100644 index 00000000..cd5c8119 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -0,0 +1,185 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.RestoreBook; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly RestoreBookEndpoint _sut; + private readonly RestoreBookCommandFixture _restoreBookCommandFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreBookEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Updated, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Error expectedError = DomainErrors.WrittenContent.BookNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("BookNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Error validationError = DomainErrors.WrittenContent.BookIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteIdsToTheHandler() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + RestoreBookCommand expectedCommand = _restoreBookCommandFixture.Create( + libraryId: libraryId.ToString(), + bookId: bookId.ToString()); + await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + 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.Updated); + }, callInfo.Arg())); + ConfigureRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Configures the route values of a valid restore request. + /// + private void ConfigureRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs new file mode 100644 index 00000000..d0c13aa4 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteBookEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DeleteBookEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteBookEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldDeleteBookViaApiAndReturnSuccessWithoutData() + { + // Arrange + Guid bookId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(bookId.ToString(), libraryId); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + BuildExpectedEndpoint(libraryId, bookId), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _)); + } + + [Fact] + public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ConfigureRequest("not-a-guid", libraryId); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenBookIdIsMissing_ShouldForwardGuidEmptyBookIdToApi() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi() + { + // Arrange + Guid bookId = Guid.NewGuid(); + ConfigureRequest(bookId.ToString(), "not-a-guid"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + BuildExpectedEndpoint(Guid.Empty, bookId), + Arg.Any()); + } + + /// + /// Sets the route and query values the endpoint reads the book identity from. + /// + /// The raw route value of the book Id. + /// The raw query value of the library Id. + private void ConfigureRequest(string bookId, Guid libraryId) + { + ConfigureRequest(bookId, libraryId.ToString()); + } + + /// + /// Sets the route and query values the endpoint reads the book identity from. + /// + /// The raw route value of the book Id. + /// The raw query value of the library Id. + private void ConfigureRequest(string bookId, string libraryId) + { + _sut.HttpContext.Request.RouteValues["bookId"] = bookId; + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}"); + } + + /// + /// Builds the upstream endpoint the book deletion is expected to be sent to. + /// + /// The normalized Id of the media library. + /// The normalized Id of the book. + /// The expected upstream endpoint. + private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId) + { + return ApiRoutes.Books.DELETE_BOOK + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{bookId}", bookId.ToString()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs new file mode 100644 index 00000000..71ecb595 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeletedBooks/DeletedBooksViewEndpointTests.cs @@ -0,0 +1,183 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletedBooksViewEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IUrlService _mockUrlService; + private readonly ThemePageRenderer _mockThemePageRenderer; + private readonly IAntiforgery _mockAntiforgery; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly DeletedBooksViewEndpoint _sut; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly DeletedBookDtoFixture _deletedBookDtoFixture = new(); + private readonly GetBooksViewRequestFixture _getBooksViewRequestFixture = new(); + private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeletedBooksViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _mockUrlService = Substitute.For(); + _mockThemePageRenderer = Substitute.For(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine()); + _mockAntiforgery = Substitute.For(); + _mockAntiforgery.GetAndStoreTokens(Arg.Any()) + .Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken")); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString( + callInfo.Arg(), + callInfo.Arg() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg()}")); + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns(new LocalizedString[] + { + new("Title", "Deleted items"), + new("NoDeletedItems", "There are no deleted items in this library.") + }); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _sut = Factory.Create(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books/deleted-items"; + + StubUrls(); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData() + { + // Arrange + LibraryDto library = _libraryDtoFixture.Create(title: "Books"); + DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(library); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(deletedBooks); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "
deleted
", script: ""))); + + // Act + IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result)); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(page => + page.PageKey == "library/written-content-library/book-library/books/deleted-items" && + page.Title == "Deleted items" && + string.Equals(page.PageData["libraryId"] as string, library.Id!.Value.ToString(), StringComparison.Ordinal) && + string.Equals(page.PageData["libraryTitle"] as string, "Books", StringComparison.Ordinal) && + string.Equals(page.PageData["restoreUrl"] as string, "http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book", StringComparison.Ordinal) && + string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/written-content-library/books-library/books?libraryId={library.Id}", StringComparison.Ordinal) && + string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) && + page.PageData.ContainsKey("deletedBooksJson") && + page.PageData.ContainsKey("strings") && + page.PageData.ContainsKey("stringsJson")), + Arg.Is(requestedThemeId => requestedThemeId == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome() + { + // Arrange + _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); + + // Act + IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: null), CancellationToken.None); + + // Assert + RedirectHttpResult redirectResult = Assert.IsType(result); + Assert.Equal("http://localhost/en-us", redirectResult.Url); + await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedBooks() + { + // Arrange + LibraryDto library = _libraryDtoFixture.Create(title: "Books"); + DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(library); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()).Returns(deletedBooks); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Failure(Error.Failure("Theme.Render", "The page could not be rendered."))); + + // Act + IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml", GetRenderedViewName(result)); + DeletedBooksPageDto model = Assert.IsType(GetRenderedModel(result)); + Assert.Equal(library.Id, model.Library.Id); + Assert.Equal(deletedBooks, model.DeletedBooks); + } + + /// + /// Stubs the absolute URLs that the endpoint resolves for the deleted items page. + /// + private void StubUrls() + { + _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.INDEX).Returns("http://localhost/en-us/library/written-content-library/books-library/books"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.RESTORE_BOOK, Arg.Any()) + .Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book"); + } + + /// + /// 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/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs index 88b6c5d5..0e5b86ca 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -84,6 +84,8 @@ public class BooksIndexViewEndpointTests _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items"); _mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings"); _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.READ, Arg.Any()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, Arg.Any()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETED_BOOKS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/deleted-items"); _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "
content
", script: ""))); @@ -99,6 +101,7 @@ public class BooksIndexViewEndpointTests page.PageData.ContainsKey("libraryId") && page.PageData.ContainsKey("settingsUrl") && page.PageData.ContainsKey("strings") && + page.PageData.ContainsKey("stringsJson") && string.Equals( page.PageData["itemsUrl"] as string, "http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items", @@ -106,6 +109,14 @@ public class BooksIndexViewEndpointTests string.Equals( page.PageData["readUrl"] as string, "http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read", + StringComparison.Ordinal) && + string.Equals( + page.PageData["deleteUrl"] as string, + "http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book", + StringComparison.Ordinal) && + string.Equals( + page.PageData["deletedBooksUrl"] as string, + "http://localhost/en-us/library/written-content-library/books-library/books/deleted-items", StringComparison.Ordinal)), Arg.Is(requestedThemeId => requestedThemeId == null), Arg.Any()); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs new file mode 100644 index 00000000..e7bf88dc --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreBookEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RestoreBookEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public RestoreBookEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRestoreBookViaApiAndReturnSuccessPayload() + { + // Arrange + Guid bookId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + ConfigureRequest(bookId.ToString(), libraryId); + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, bookId), + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ConfigureRequest("not-a-guid", libraryId); + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(libraryId, Guid.Empty), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi() + { + // Arrange + Guid bookId = Guid.NewGuid(); + ConfigureRequest(bookId.ToString(), "not-a-guid"); + _mockApiHttpClient.PostAsync( + Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + BuildExpectedEndpoint(Guid.Empty, bookId), + Arg.Any(), + Arg.Any()); + } + + /// + /// Sets the route and query values the endpoint reads the book identity from. + /// + /// The raw route value of the book Id. + /// The raw query value of the library Id. + private void ConfigureRequest(string bookId, Guid libraryId) + { + ConfigureRequest(bookId, libraryId.ToString()); + } + + /// + /// Sets the route and query values the endpoint reads the book identity from. + /// + /// The raw route value of the book Id. + /// The raw query value of the library Id. + private void ConfigureRequest(string bookId, string libraryId) + { + _sut.HttpContext.Request.RouteValues["bookId"] = bookId; + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}"); + } + + /// + /// Builds the upstream endpoint the book restoration is expected to be sent to. + /// + /// The normalized Id of the media library. + /// The normalized Id of the book. + /// The expected upstream endpoint. + private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId) + { + return ApiRoutes.Books.RESTORE_BOOK + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{bookId}", bookId.ToString()); + } +}