Merge pull request #281 from BinaryAlley/feature/add-delete-book-web-client

Adds book deletion and restore to the web client
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-11-14 22:26:19 +02:00
commit 3f7cc2c60f
125 files changed
+9856 -378

No files matched your search

+3 -1
View File
@@ -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. - **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. - **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 ## Reading a book
@@ -26,13 +26,17 @@
- [Get Reading Manifest](#get-reading-manifest) - [Get Reading Manifest](#get-reading-manifest)
- [Get Reading Manifest Request](#get-reading-manifest-request) - [Get Reading Manifest Request](#get-reading-manifest-request)
- [Get Reading Manifest Response](#get-reading-manifest-response) - [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](#get-reading-section)
- [Get Reading Section Request](#get-reading-section-request) - [Get Reading Section Request](#get-reading-section-request)
- [Get Reading Section Response](#get-reading-section-response) - [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) - [Delete Book](#delete-book)
- [Restore Book](#restore-book)
## 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. 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 ```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 ```js
200 Ok 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.
@@ -0,0 +1,2 @@
GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/deleted-items
Authorization: Bearer {{ACCESS_TOKEN}}
@@ -0,0 +1,2 @@
POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}/restore
Authorization: Bearer {{ACCESS_TOKEN}}
+67 -1
View File
@@ -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 audio player sub templates](#the-audio-player-sub-templates)
- [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu) - [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu)
- [Page Templates](#page-templates) - [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 Playlist Pages](#the-playlist-pages)
- [The Shared Add to Playlist Action](#the-shared-add-to-playlist-action) - [The Shared Add to Playlist Action](#the-shared-add-to-playlist-action)
- [The Album Track Actions Menu](#the-album-track-actions-menu) - [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. 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. 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. 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/queue-item` | The queue item of the audio player bar. |
| `shared/audio-player/playlist-item` | The playlist 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/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/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. | | `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. | | `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}} {{/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 #### The Playlist Pages
`playlists/index` receives a model with the following fields: `playlists/index` receives a model with the following fields:
@@ -212,6 +212,17 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// </summary> /// </summary>
public List<BookRatingEntity> Ratings { get; set; } = []; public List<BookRatingEntity> Ratings { get; set; } = [];
/// <summary>
/// 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.
/// </summary>
public bool IsDeleted { get; set; }
/// <summary>
/// Gets or sets the date and time when the book was deleted, or <see langword="null"/> when the book is not deleted.
/// </summary>
public DateTime? DeletedOnUtc { get; set; }
/// <summary> /// <summary>
/// Gets or sets the status of the metadata enrichment of the book. /// Gets or sets the status of the metadata enrichment of the book.
/// </summary> /// </summary>
@@ -26,15 +26,53 @@ public interface IBookRepository : IRepository<BookEntity>,
/// <summary> /// <summary>
/// Gets the book of the media library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>. /// Gets the book of the media library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the media library whose book is retrieved.</param> /// <param name="libraryId">The Id of the media library whose book is retrieved.</param>
/// <param name="path">The file system path of the book to be retrieved.</param> /// <param name="path">The file system path of the book to be retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="BookEntity"/> stored at the provided path, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="BookEntity"/> stored at the provided path, or an error.</returns>
Task<Result<BookEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken); Task<Result<BookEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken);
/// <summary>
/// Gets the soft deleted book identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the soft deleted book to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted <see cref="BookEntity"/>, <see langword="null"/> when the book does not exist or is not soft deleted, or an error.</returns>
Task<Result<BookEntity?>> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Gets the soft deleted books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose soft deleted books are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted books, or an error.</returns>
Task<Result<IReadOnlyList<BookEntity>>> GetSoftDeletedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Soft deletes the book identified by <paramref name="id"/>, without removing its stored metadata or artwork.
/// </summary>
/// <param name="id">The Id of the book to soft delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> SoftDeleteByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Restores the soft deleted book identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the book to restore.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Updated>> RestoreSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Gets the subset of <paramref name="paths"/> that is already used by a book of the library identified by <paramref name="libraryId"/>. /// Gets the subset of <paramref name="paths"/> that is already used by a book of the library identified by <paramref name="libraryId"/>.
/// </summary> /// </summary>
/// <remarks>
/// Soft deleted books are included on purpose: their paths must still count as taken, so that a scan never materializes a deleted book again.
/// </remarks>
/// <param name="libraryId">The Id of the library whose books are searched.</param> /// <param name="libraryId">The Id of the library whose books are searched.</param>
/// <param name="paths">The book paths to check.</param> /// <param name="paths">The book paths to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -83,6 +121,9 @@ public interface IBookRepository : IRepository<BookEntity>,
/// Resets the enrichment state of the books stored at the provided <paramref name="paths"/> in the media library identified by /// Resets the enrichment state of the books stored at the provided <paramref name="paths"/> in the media library identified by
/// <paramref name="libraryId"/>, so that they are re-enriched, because their content changed since the last scan. /// <paramref name="libraryId"/>, so that they are re-enriched, because their content changed since the last scan.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the media library whose books are reset.</param> /// <param name="libraryId">The Id of the media library whose books are reset.</param>
/// <param name="paths">The file system paths of the books whose enrichment state is reset.</param> /// <param name="paths">The file system paths of the books whose enrichment state is reset.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -93,6 +134,9 @@ public interface IBookRepository : IRepository<BookEntity>,
/// Resets the metadata enrichment status of all the books of the media library identified by <paramref name="libraryId"/>, /// Resets the metadata enrichment status of all the books of the media library identified by <paramref name="libraryId"/>,
/// so that they are re-enriched, because the metadata provider configuration of the library changed. /// so that they are re-enriched, because the metadata provider configuration of the library changed.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the media library whose books are reset.</param> /// <param name="libraryId">The Id of the media library whose books are reset.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
@@ -102,6 +146,9 @@ public interface IBookRepository : IRepository<BookEntity>,
/// Resets the artwork status of all the artwork of the books of the media library identified by <paramref name="libraryId"/>, /// Resets the artwork status of all the artwork of the books of the media library identified by <paramref name="libraryId"/>,
/// so that they are re-resolved, because the artwork provider configuration of the library changed. /// so that they are re-resolved, because the artwork provider configuration of the library changed.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the media library whose artwork is reset.</param> /// <param name="libraryId">The Id of the media library whose artwork is reset.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
@@ -258,6 +258,25 @@ public static class BookEntityMapping
); );
} }
/// <summary>
/// Converts a deleted <paramref name="repositoryEntity"/> to <see cref="DeletedBookResponse"/>.
/// </summary>
/// <param name="repositoryEntity">The deleted repository entity to be converted.</param>
/// <param name="deletedOnUtc">The date and time when the book was deleted.</param>
/// <returns>The converted deleted book response.</returns>
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
);
}
/// <summary> /// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="Book"/>. /// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="Book"/>.
/// </summary> /// </summary>
@@ -1,15 +1,12 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS; using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Primitives;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
@@ -26,8 +23,6 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
public class DeleteBookCommandHandler : ICommandHandler<DeleteBookCommand, Result<Deleted>> public class DeleteBookCommandHandler : ICommandHandler<DeleteBookCommand, Result<Deleted>>
{ {
private readonly IUnitOfWork _unitOfWork; private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
private readonly ILogger<DeleteBookCommandHandler> _logger;
private readonly IAuthorizationService _authorizationService; private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService; private readonly ICurrentUserService _currentUserService;
private readonly IValidator<DeleteBookCommand> _validator; private readonly IValidator<DeleteBookCommand> _validator;
@@ -36,22 +31,16 @@ public class DeleteBookCommandHandler : ICommandHandler<DeleteBookCommand, Resul
/// Initializes a new instance of the <see cref="DeleteBookCommandHandler"/> class. /// Initializes a new instance of the <see cref="DeleteBookCommandHandler"/> class.
/// </summary> /// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param> /// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="bookArtworkService">Injected service for removing the artwork of a book.</param>
/// <param name="logger">Injected logger used to report the issues encountered while removing the stored artwork.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param> /// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param> /// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param> /// <param name="validator">Injected validator for application validation rules.</param>
public DeleteBookCommandHandler( public DeleteBookCommandHandler(
IUnitOfWork unitOfWork, IUnitOfWork unitOfWork,
IBookArtworkService bookArtworkService,
ILogger<DeleteBookCommandHandler> logger,
IAuthorizationService authorizationService, IAuthorizationService authorizationService,
ICurrentUserService currentUserService, ICurrentUserService currentUserService,
IValidator<DeleteBookCommand> validator) IValidator<DeleteBookCommand> validator)
{ {
_unitOfWork = unitOfWork; _unitOfWork = unitOfWork;
_bookArtworkService = bookArtworkService;
_logger = logger;
_authorizationService = authorizationService; _authorizationService = authorizationService;
_currentUserService = currentUserService; _currentUserService = currentUserService;
_validator = validator; _validator = validator;
@@ -99,28 +88,9 @@ public class DeleteBookCommandHandler : ICommandHandler<DeleteBookCommand, Resul
if (!canAccessLibrary) if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized; return ApplicationErrors.Authorization.NotAuthorized;
// A book can only belong to a library that exists, so a client can never delete a book of a library of the host that is not there. // The book is soft deleted, so its metadata, artwork and path stay available until the user restores it or the file disappears from disk.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); // Keeping the row is also what makes the deletion survive an automatic scan, because the scan treats its path as already catalogued.
if (getLibraryResult.IsFailure) Result<Updated> deleteBookResult = await _unitOfWork.BookRepository.SoftDeleteByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false);
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<IReadOnlyDictionary<Guid, string?>> 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<Deleted> 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<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false);
if (deleteBookResult.IsFailure) if (deleteBookResult.IsFailure)
return deleteBookResult.Errors; return deleteBookResult.Errors;
@@ -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;
/// <summary>
/// Command for restoring a deleted book by its Id.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library this book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the deleted book to restore, taken from the route.</param>
[DebuggerDisplay("BookId: {BookId}")]
public record RestoreBookCommand(
string? LibraryId,
string? BookId
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to restore a deleted book by its Id.
/// </summary>
public class RestoreBookCommandHandler : ICommandHandler<RestoreBookCommand, Result<Updated>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<RestoreBookCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public RestoreBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<RestoreBookCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to restore a deleted book by its Id.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> HandleAsync(RestoreBookCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// 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<BookEntity?> 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<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<Updated> restoreBookResult = await _unitOfWork.BookRepository.RestoreSoftDeletedByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false);
if (restoreBookResult.IsFailure)
return restoreBookResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Updated;
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="RestoreBookCommand"/>.
/// </summary>
public class RestoreBookCommandValidator : AbstractValidator<RestoreBookCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
/// <summary>
/// Query for getting the deleted books of a media library.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library whose deleted books are retrieved, taken from the route.</param>
public record GetDeletedBooksQuery(
string? LibraryId
) : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get the deleted books of a media library.
/// </summary>
public class GetDeletedBooksQueryHandler : IQueryHandler<GetDeletedBooksQuery, Result<IReadOnlyList<DeletedBookResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetDeletedBooksQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetDeletedBooksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetDeletedBooksQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the deleted books of a media library.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the deleted books, or an error.</returns>
public async Task<Result<IReadOnlyList<DeletedBookResponse>>> HandleAsync(GetDeletedBooksQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The 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<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<IReadOnlyList<BookEntity>> getDeletedBooksResult = await _unitOfWork.BookRepository.GetSoftDeletedByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (getDeletedBooksResult.IsFailure)
return getDeletedBooksResult.Errors;
return Result.From<IReadOnlyList<DeletedBookResponse>>([.. getDeletedBooksResult.Value.Select(book => book.ToResponse(book.DeletedOnUtc ?? book.CreatedOnUtc))]);
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="GetDeletedBooksQuery"/>.
/// </summary>
public class GetDeletedBooksQueryValidator : AbstractValidator<GetDeletedBooksQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksQueryValidator"/> class.
/// </summary>
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);
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Represents a book that the user deleted and can restore.
/// </summary>
/// <param name="Id">The unique identifier of the book.</param>
/// <param name="LibraryId">The unique identifier of the media library the book belongs to.</param>
/// <param name="Title">The title of the book.</param>
/// <param name="OriginalTitle">The original title of the book, when it differs from the current one.</param>
/// <param name="Path">The file system path of the book.</param>
/// <param name="DeletedOnUtc">The date and time when the book was deleted.</param>
/// <param name="CoverPath">The relative path of the stored cover image of the book, when it has one.</param>
public record DeletedBookResponse(
Guid Id,
Guid LibraryId,
string Title,
string? OriginalTitle,
string Path,
DateTime DeletedOnUtc,
string? CoverPath
);
@@ -149,6 +149,13 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
builder.Property(book => book.MetadataProvider) builder.Property(book => book.MetadataProvider)
.HasMaxLength(100) .HasMaxLength(100)
.HasColumnOrder(40); .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) builder.HasMany(book => book.Contributors)
.WithOne() .WithOne()
@@ -226,5 +233,8 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
builder.HasIndex(book => new { book.LibraryId, book.Path }) builder.HasIndex(book => new { book.LibraryId, book.Path })
.IsUnique(); // the same physical book on disk cannot appear twice in the same library .IsUnique(); // the same physical book on disk cannot appear twice in the same library
builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus }); 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 });
} }
} }
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,59 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsBookDeletionState : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "DeletedOnUtc",
table: "Books",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 42);
migrationBuilder.AddColumn<bool>(
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" });
}
/// <inheritdoc />
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");
}
}
}
@@ -1913,6 +1913,10 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT") .HasColumnType("TEXT")
.HasColumnOrder(32); .HasColumnOrder(32);
b.Property<DateTime?>("DeletedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(42);
b.Property<string>("Description") b.Property<string>("Description")
.HasMaxLength(2000) .HasMaxLength(2000)
.HasColumnType("TEXT") .HasColumnType("TEXT")
@@ -1936,6 +1940,12 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT") .HasColumnType("TEXT")
.HasColumnOrder(27); .HasColumnOrder(27);
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(false)
.HasColumnOrder(41);
b.Property<string>("LCCN") b.Property<string>("LCCN")
.HasColumnType("TEXT") .HasColumnType("TEXT")
.HasColumnOrder(23); .HasColumnOrder(23);
@@ -2067,6 +2077,8 @@ namespace Lumina.DataAccess.Common.Migrations
b.HasIndex("LibraryId", "Path") b.HasIndex("LibraryId", "Path")
.IsUnique(); .IsUnique();
b.HasIndex("LibraryId", "IsDeleted", "DeletedOnUtc", "Title", "Id");
b.ToTable("Books", (string)null); b.ToTable("Books", (string)null);
}); });
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Specifications; using Lumina.Application.Common.Specifications;
using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications; 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 static readonly MethodInfo s_substringMethod = typeof(string).GetMethod(nameof(string.Substring), [typeof(int)])!;
private readonly LuminaDbContext _luminaDbContext; private readonly LuminaDbContext _luminaDbContext;
private readonly IDateTimeProvider _dateTimeProvider;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="BookRepository"/> class. /// Initializes a new instance of the <see cref="BookRepository"/> class.
/// </summary> /// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param> /// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public BookRepository(LuminaDbContext luminaDbContext) /// <param name="dateTimeProvider">Injected provider for the current UTC time, used to stamp deletions deterministically.</param>
public BookRepository(LuminaDbContext luminaDbContext, IDateTimeProvider dateTimeProvider)
{ {
_luminaDbContext = luminaDbContext; _luminaDbContext = luminaDbContext;
_dateTimeProvider = dateTimeProvider;
} }
/// <summary> /// <summary>
@@ -88,7 +92,7 @@ internal sealed class BookRepository : IBookRepository
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="BookEntity"/>, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="BookEntity"/>, or an error.</returns>
public async Task<Result<BookEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) public async Task<Result<BookEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{ {
IQueryable<BookEntity> query = _luminaDbContext.Books; IQueryable<BookEntity> query = _luminaDbContext.Books.Where(book => !book.IsDeleted);
if (!shouldTrackEntities) if (!shouldTrackEntities)
query = query.AsNoTracking(); query = query.AsNoTracking();
if (shouldIncludeNavigationProperties) if (shouldIncludeNavigationProperties)
@@ -119,7 +123,7 @@ internal sealed class BookRepository : IBookRepository
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{BookEntity}"/>, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{BookEntity}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<BookEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto public async Task<Result<PaginatedResultDto<BookEntity>>> GetAllAsync<TFilter>(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<BookEntity> booksQuery = _luminaDbContext.Books; IQueryable<BookEntity> booksQuery = _luminaDbContext.Books.Where(book => !book.IsDeleted);
if (!shouldTrackEntities) if (!shouldTrackEntities)
booksQuery = booksQuery.AsNoTracking(); booksQuery = booksQuery.AsNoTracking();
if (shouldIncludeNavigationProperties) if (shouldIncludeNavigationProperties)
@@ -202,7 +206,7 @@ internal sealed class BookRepository : IBookRepository
return Errors.Library.FilterMustIncludeLibraryId; return Errors.Library.FilterMustIncludeLibraryId;
// The lightweight read models are retrieved without tracking by default, because they are never modified by the caller. // The lightweight read models are retrieved without tracking by default, because they are never modified by the caller.
IQueryable<BookEntity> booksQuery = _luminaDbContext.Books; IQueryable<BookEntity> booksQuery = _luminaDbContext.Books.Where(book => !book.IsDeleted);
if (!shouldTrackEntities) if (!shouldTrackEntities)
booksQuery = booksQuery.AsNoTracking(); booksQuery = booksQuery.AsNoTracking();
if (shouldIncludeNavigationProperties) if (shouldIncludeNavigationProperties)
@@ -272,6 +276,10 @@ internal sealed class BookRepository : IBookRepository
/// <summary> /// <summary>
/// Gets the book of the media library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>. /// Gets the book of the media library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the media library whose book is retrieved.</param> /// <param name="libraryId">The Id of the media library whose book is retrieved.</param>
/// <param name="path">The file system path of the book to be retrieved.</param> /// <param name="path">The file system path of the book to be retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -287,9 +295,83 @@ internal sealed class BookRepository : IBookRepository
.FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false); .FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false);
} }
/// <summary>
/// Gets the soft deleted book identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the soft deleted book to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted <see cref="BookEntity"/>, <see langword="null"/> when the book does not exist or is not soft deleted, or an error.</returns>
public async Task<Result<BookEntity?>> GetSoftDeletedByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Books
.Include(book => book.Artwork)
.AsSplitQuery()
.FirstOrDefaultAsync(book => book.Id == id && book.IsDeleted, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the soft deleted books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose soft deleted books are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the soft deleted books, or an error.</returns>
public async Task<Result<IReadOnlyList<BookEntity>>> 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);
}
/// <summary>
/// Soft deletes the book identified by <paramref name="id"/>, without removing its stored metadata or artwork.
/// </summary>
/// <param name="id">The Id of the book to soft delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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;
}
/// <summary>
/// Restores the soft deleted book identified by <paramref name="id"/>.
/// </summary>
/// <param name="id">The Id of the book to restore.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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;
}
/// <summary> /// <summary>
/// Gets the subset of <paramref name="paths"/> that is already used by a book of the library identified by <paramref name="libraryId"/>. /// Gets the subset of <paramref name="paths"/> that is already used by a book of the library identified by <paramref name="libraryId"/>.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the library whose books are searched.</param> /// <param name="libraryId">The Id of the library whose books are searched.</param>
/// <param name="paths">The book paths to check.</param> /// <param name="paths">The book paths to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -331,6 +413,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Contributors) .Include(book => book.Contributors)
.AsSplitQuery() .AsSplitQuery()
.Where(book => book.LibraryId == libraryId .Where(book => book.LibraryId == libraryId
&& !book.IsDeleted
&& book.MetadataStatus != MetadataStatus.Enriched && book.MetadataStatus != MetadataStatus.Enriched
&& (lastPath == null || book.Path.CompareTo(lastPath) > 0)) && (lastPath == null || book.Path.CompareTo(lastPath) > 0))
.OrderBy(book => book.Path) .OrderBy(book => book.Path)
@@ -347,7 +430,7 @@ internal sealed class BookRepository : IBookRepository
public async Task<Result<int>> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken) public async Task<Result<int>> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken)
{ {
return await _luminaDbContext.Books 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);
} }
/// <summary> /// <summary>
@@ -368,6 +451,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Artwork) .Include(book => book.Artwork)
.AsSplitQuery() .AsSplitQuery()
.Where(book => book.LibraryId == libraryId .Where(book => book.LibraryId == libraryId
&& !book.IsDeleted
&& !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched) && !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched)
&& (lastPath == null || book.Path.CompareTo(lastPath) > 0)) && (lastPath == null || book.Path.CompareTo(lastPath) > 0))
.OrderBy(book => book.Path) .OrderBy(book => book.Path)
@@ -385,6 +469,7 @@ internal sealed class BookRepository : IBookRepository
{ {
return await _luminaDbContext.Books return await _luminaDbContext.Books
.CountAsync(book => book.LibraryId == libraryId .CountAsync(book => book.LibraryId == libraryId
&& !book.IsDeleted
&& !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched), cancellationToken) && !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched), cancellationToken)
.ConfigureAwait(false); .ConfigureAwait(false);
} }
@@ -393,6 +478,9 @@ internal sealed class BookRepository : IBookRepository
/// Resets the enrichment state of the books stored at the provided <paramref name="paths"/> in the media library identified by /// Resets the enrichment state of the books stored at the provided <paramref name="paths"/> in the media library identified by
/// <paramref name="libraryId"/>, so that they are re-enriched, because their content changed since the last scan. /// <paramref name="libraryId"/>, so that they are re-enriched, because their content changed since the last scan.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the media library whose books are reset.</param> /// <param name="libraryId">The Id of the media library whose books are reset.</param>
/// <param name="paths">The file system paths of the books whose enrichment state is reset.</param> /// <param name="paths">The file system paths of the books whose enrichment state is reset.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -426,6 +514,9 @@ internal sealed class BookRepository : IBookRepository
/// Resets the metadata enrichment status of all the books of the media library identified by <paramref name="libraryId"/>, /// Resets the metadata enrichment status of all the books of the media library identified by <paramref name="libraryId"/>,
/// so that they are re-enriched, because the metadata provider configuration of the library changed. /// so that they are re-enriched, because the metadata provider configuration of the library changed.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the media library whose books are reset.</param> /// <param name="libraryId">The Id of the media library whose books are reset.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
@@ -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 <paramref name="libraryId"/>, /// Resets the artwork status of all the artwork of the books of the media library identified by <paramref name="libraryId"/>,
/// so that they are re-resolved, because the artwork provider configuration of the library changed. /// so that they are re-resolved, because the artwork provider configuration of the library changed.
/// </summary> /// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="libraryId">The Id of the media library whose artwork is reset.</param> /// <param name="libraryId">The Id of the media library whose artwork is reset.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param> /// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns> /// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
@@ -514,7 +608,7 @@ internal sealed class BookRepository : IBookRepository
const int LOOKUP_CHUNK_SIZE = 500; const int LOOKUP_CHUNK_SIZE = 500;
foreach (Guid[] chunk in bookIds.Chunk(LOOKUP_CHUNK_SIZE)) foreach (Guid[] chunk in bookIds.Chunk(LOOKUP_CHUNK_SIZE))
{ {
IQueryable<BookEntity> query = _luminaDbContext.Books.AsNoTracking(); IQueryable<BookEntity> query = _luminaDbContext.Books.AsNoTracking().Where(book => !book.IsDeleted);
if (shouldIncludeNavigationProperties) if (shouldIncludeNavigationProperties)
{ {
query = query query = query
@@ -570,20 +664,29 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Ratings) .Include(book => book.Ratings)
.Include(book => book.Contributors) .Include(book => book.Contributors)
.AsSplitQuery() .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) if (foundBook is null)
return Errors.WrittenContent.BookNotFound; 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 // The stored enrichment, identity and deletion columns are never overwritten by an edit: they are owned by the scan, by the record itself
// only ever written by the auditing interceptor, which is why the copier restores them after copying the editable values. // 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; Guid libraryId = foundBook.LibraryId;
string path = foundBook.Path; string path = foundBook.Path;
bool isDeleted = foundBook.IsDeleted;
DateTime? deletedOnUtc = foundBook.DeletedOnUtc;
MetadataStatus metadataStatus = foundBook.MetadataStatus; MetadataStatus metadataStatus = foundBook.MetadataStatus;
DateTime? lastMetadataUpdateUtc = foundBook.LastMetadataUpdateUtc; DateTime? lastMetadataUpdateUtc = foundBook.LastMetadataUpdateUtc;
string? metadataProvider = foundBook.MetadataProvider; string? metadataProvider = foundBook.MetadataProvider;
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundBook, data); EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundBook, data);
foundBook.LibraryId = libraryId; foundBook.LibraryId = libraryId;
foundBook.Path = path; 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.MetadataStatus = metadataStatus;
foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc; foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc;
foundBook.MetadataProvider = metadataProvider; foundBook.MetadataProvider = metadataProvider;
@@ -25,8 +25,9 @@ namespace Lumina.DataAccess.Core.Repositories.Favorites;
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// 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 /// 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 /// the referenced items with one batched query per media kind present in the page. A favorite whose item no longer exists, or whose book
/// without display data. Duplicate favorites of the same user on the same item are rejected by the unique (UserId, MediaKind, MediaItemId) index. /// 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.
/// </remarks> /// </remarks>
internal sealed class FavoriteRepository : IFavoriteRepository internal sealed class FavoriteRepository : IFavoriteRepository
{ {
@@ -127,7 +128,7 @@ internal sealed class FavoriteRepository : IFavoriteRepository
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false), .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
FavoriteMediaKind.Book => await _luminaDbContext.Books FavoriteMediaKind.Book => await _luminaDbContext.Books
.AsNoTracking() .AsNoTracking()
.Where(book => book.Id == mediaItemId) .Where(book => book.Id == mediaItemId && !book.IsDeleted)
.Select(book => (Guid?)book.LibraryId) .Select(book => (Guid?)book.LibraryId)
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false), .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
_ => null, _ => 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. // the same author the book listing shows, and the Id is the tiebreaker between authors that share a display name.
rows = await _luminaDbContext.Books rows = await _luminaDbContext.Books
.AsNoTracking() .AsNoTracking()
.Where(book => requestedIds.Contains(book.Id)) .Where(book => requestedIds.Contains(book.Id) && !book.IsDeleted)
.Select(book => new DisplayRow( .Select(book => new DisplayRow(
book.Id, book.Id,
book.LibraryId, book.LibraryId,
+6 -2
View File
@@ -13,6 +13,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors; using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.Repositories.Authorization;
using Lumina.DataAccess.Core.Repositories.BookLibrary; using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Favorites; using Lumina.DataAccess.Core.Repositories.Favorites;
@@ -42,6 +43,7 @@ namespace Lumina.DataAccess.Core.UoW;
public class UnitOfWork : IUnitOfWork, IDisposable public class UnitOfWork : IUnitOfWork, IDisposable
{ {
private readonly LuminaDbContext _luminaDbContext; private readonly LuminaDbContext _luminaDbContext;
private readonly IDateTimeProvider _dateTimeProvider;
private IDbContextTransaction? _transaction; private IDbContextTransaction? _transaction;
private IPermissionRepository? _permissionRepository; private IPermissionRepository? _permissionRepository;
@@ -131,7 +133,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
{ {
get get
{ {
_bookRepository ??= new BookRepository(_luminaDbContext); _bookRepository ??= new BookRepository(_luminaDbContext, _dateTimeProvider);
return _bookRepository; return _bookRepository;
} }
} }
@@ -449,9 +451,11 @@ public class UnitOfWork : IUnitOfWork, IDisposable
/// Initializes a new instance of the <see cref="UnitOfWork"/> class. /// Initializes a new instance of the <see cref="UnitOfWork"/> class.
/// </summary> /// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param> /// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public UnitOfWork(LuminaDbContext luminaDbContext) /// <param name="dateTimeProvider">Injected provider for the current UTC time, passed to the repositories that stamp their own timestamps.</param>
public UnitOfWork(LuminaDbContext luminaDbContext, IDateTimeProvider dateTimeProvider)
{ {
_luminaDbContext = luminaDbContext; _luminaDbContext = luminaDbContext;
_dateTimeProvider = dateTimeProvider;
} }
/// <summary> /// <summary>
@@ -13,6 +13,8 @@ public static partial class ApiRoutes
public const string GET_BOOK_BY_ID = "/libraries/{libraryId}/books/{bookId}"; public const string GET_BOOK_BY_ID = "/libraries/{libraryId}/books/{bookId}";
public const string GET_BOOKS = "/libraries/{libraryId}/books"; public const string GET_BOOKS = "/libraries/{libraryId}/books";
public const string GET_BOOKS_LITE = "/libraries/{libraryId}/books/lite"; 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 ADD_BOOK = "/libraries/{libraryId}/books";
public const string UPDATE_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 DELETE_BOOK = "/libraries/{libraryId}/books/{bookId}";
@@ -19,9 +19,9 @@ public class DeleteBookEndpointSummary : Summary<DeleteBookEndpoint, EmptyReques
public DeleteBookEndpointSummary() public DeleteBookEndpointSummary()
{ {
Summary = "Deletes an existing book."; Summary = "Deletes an existing book.";
Description = "Deletes the book identified by the route, together with its stored artwork. The book is deleted by an Admin, who can delete the books of all libraries, or by the owner of the library of the book."; Description = "Moves the book identified by the route to the deleted items of its media library, where its metadata and stored artwork are kept so that the deletion can be undone. A deleted book is no longer listed, read or materialized again by scans, until it is restored. The book is deleted by an Admin, who can delete the books of all libraries, or by the owner of the library of the book.";
Response(200, "The book was successfully deleted."); Response(200, "The book was successfully deleted and can be restored from the deleted items of its media library.");
Response(401, "Authentication required.", "application/problem+json", Response(401, "Authentication required.", "application/problem+json",
example: new[] example: new[]
@@ -65,27 +65,15 @@ public class DeleteBookEndpointSummary : Summary<DeleteBookEndpoint, EmptyReques
} }
); );
Response(404, "The request failed because the requested book or its media library does not exist.", "application/problem+json", Response(404, "The request failed because the requested book does not exist, or does not belong to the media library named by the route.", "application/problem+json",
example: new[] example: new
{ {
new type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
{ title = "General.NotFound",
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", status = 404,
title = "General.NotFound", detail = "BookNotFound",
status = 404, instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
detail = "BookNotFound", traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
} }
); );
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetDeletedBooks;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
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.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/books/deleted-items</c> route.
/// </summary>
public class GetDeletedBooksEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetDeletedBooksQuery, Result<IReadOnlyList<DeletedBookResponse>>> _getDeletedBooksQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpoint"/> class.
/// </summary>
/// <param name="getDeletedBooksQueryHandler">Injected service for handling get deleted books queries.</param>
public GetDeletedBooksEndpoint(IQueryHandler<GetDeletedBooksQuery, Result<IReadOnlyList<DeletedBookResponse>>> getDeletedBooksQueryHandler)
{
_getDeletedBooksQueryHandler = getDeletedBooksQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_DELETED_BOOKS);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the deleted books of the library identified by the route.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
// Take the unique identifier of the library from the route.
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
Result<IReadOnlyList<DeletedBookResponse>> result = await _getDeletedBooksQueryHandler.HandleAsync(new GetDeletedBooksQuery(libraryId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDeletedBooksEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksEndpointSummary : Summary<GetDeletedBooksEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpointSummary"/> class.
/// </summary>
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<DeletedBookResponse>(response => response.Id, "The Id of the deleted book.");
ResponseParam<DeletedBookResponse>(response => response.LibraryId, "The Id of the media library the deleted book belongs to.");
ResponseParam<DeletedBookResponse>(response => response.Title, "The title of the deleted book.");
ResponseParam<DeletedBookResponse>(response => response.OriginalTitle, "The original title of the deleted book, if different from the current title.");
ResponseParam<DeletedBookResponse>(response => response.Path, "The file system path of the deleted book.");
ResponseParam<DeletedBookResponse>(response => response.DeletedOnUtc, "The date and time when the book was deleted.");
ResponseParam<DeletedBookResponse>(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<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/libraries/{libraryId}/books/{bookId}/restore</c> route.
/// </summary>
public class RestoreBookEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<RestoreBookCommand, Result<Updated>> _restoreBookCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
/// <param name="restoreBookCommandHandler">Injected service for handling restore book commands.</param>
public RestoreBookEndpoint(ICommandHandler<RestoreBookCommand, Result<Updated>> restoreBookCommandHandler)
{
_restoreBookCommandHandler = restoreBookCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.POST);
Routes(ApiRoutes.Books.RESTORE_BOOK);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Restores the deleted book identified by the route.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<Updated> result = await _restoreBookCommandHandler.HandleAsync(new RestoreBookCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="RestoreBookEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointSummary : Summary<RestoreBookEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointSummary"/> class.
/// </summary>
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<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"BookIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Data transfer object for a book that the user deleted and can restore.
/// </summary>
/// <param name="Id">The Id of the deleted book.</param>
/// <param name="LibraryId">The Id of the media library the deleted book belongs to.</param>
/// <param name="Title">The title of the deleted book.</param>
/// <param name="OriginalTitle">The original title of the deleted book, when it differs from the current one.</param>
/// <param name="Path">The file system path of the deleted book.</param>
/// <param name="DeletedOnUtc">The date and time when the book was deleted.</param>
/// <param name="CoverPath">The relative path of the stored cover image of the deleted book, when it has one.</param>
[DebuggerDisplay("Title: {Title}")]
public sealed record DeletedBookDto(
Guid Id,
Guid LibraryId,
string Title,
string? OriginalTitle,
string Path,
DateTime DeletedOnUtc,
string? CoverPath
);
@@ -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;
/// <summary>
/// Data transfer object carrying the data needed by the deleted items page of a book library.
/// </summary>
/// <param name="Library">The media library whose deleted books are shown.</param>
/// <param name="DeletedBooks">The deleted books of the media library, ordered by the time they were deleted, most recent first.</param>
public sealed record DeletedBooksPageDto(
LibraryDto Library,
IReadOnlyList<DeletedBookDto> DeletedBooks
);
@@ -13,6 +13,9 @@ public static partial class ApiRoutes
public const string GET_BOOKS_LITE = "libraries/{libraryId}/books/lite"; public const string GET_BOOKS_LITE = "libraries/{libraryId}/books/lite";
public const string GET_BOOK = "libraries/{libraryId}/books/{bookId}"; public const string GET_BOOK = "libraries/{libraryId}/books/{bookId}";
public const string UPDATE_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 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_MANIFEST = "libraries/{libraryId}/books/{bookId}/reading/manifest";
public const string GET_BOOK_READING_AVAILABILITY = "libraries/{libraryId}/books/{bookId}/reading/availability"; public const string GET_BOOK_READING_AVAILABILITY = "libraries/{libraryId}/books/{bookId}/reading/availability";
@@ -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 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 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 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 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 READ = "{culture}/library/written-content-library/books-library/books/{bookId}/read";
public const string GET_READING_MANIFEST = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest"; public const string GET_READING_MANIFEST = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest";
@@ -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;
/// <summary>
/// API endpoint for the <c>/{culture}/library/written-content-library/books-library/books/{bookId}/api-delete-book</c> route.
/// </summary>
public class DeleteBookEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public DeleteBookEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.DELETE);
Routes(WebRoutes.Books.DELETE_BOOK);
DontAutoTag();
Options(options => options.WithTags("Books"));
EnableAntiforgery();
}
/// <summary>
/// Deletes the book identified by the route.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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();
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Class used for providing a textual description for the <see cref="DeleteBookEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointSummary : Summary<DeleteBookEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointSummary"/> class.
/// </summary>
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.");
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/{culture}/library/written-content-library/books-library/books/deleted-items</c> route.
/// </summary>
public class DeletedBooksViewEndpoint : BaseEndpoint<GetBooksViewRequest, IResult>
{
// 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;
/// <summary>
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
/// <param name="urlService">Injected service for generating URLs from action and controller names, with localization.</param>
/// <param name="themePageRenderer">Injected service for rendering themed pages.</param>
/// <param name="antiforgery">Injected service for anti-forgery token handling.</param>
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the view resources.</param>
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);
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Books.DELETED_BOOKS);
DontAutoTag();
Options(options => options.WithTags("Books"));
}
/// <summary>
/// Displays the deleted books of a media library, rendered by the active theme with a fallback to the Razor view.
/// </summary>
/// <param name="request">The request containing the Id of the media library whose deleted books are shown.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetBooksViewRequest request, CancellationToken cancellationToken)
{
if (request.LibraryId is null)
return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!);
LibraryDto library = await _apiHttpClient.GetAsync<LibraryDto>(
ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false);
DeletedBookDto[] deletedBooks = await _apiHttpClient.GetAsync<DeletedBookDto[]>(
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<string, object?> 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<string, object?>
{
["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<ThemePageRenderResultDto> 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<string, object?> { ["Title"] = title });
return View(
"/Core/Views/Shared/_ThemedView.cshtml",
new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script),
new Dictionary<string, object?> { ["Title"] = title });
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="DeletedBooksViewEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedBooksViewEndpointSummary : Summary<DeletedBooksViewEndpoint, GetBooksViewRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpointSummary"/> class.
/// </summary>
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.");
}
}
@@ -105,6 +105,7 @@ public class EditBookViewEndpoint : BaseEndpoint<GetBookRequest, IResult>
["libraryId"] = book.LibraryId.ToString(), ["libraryId"] = book.LibraryId.ToString(),
["antiforgeryToken"] = antiforgeryTokens.RequestToken, ["antiforgeryToken"] = antiforgeryTokens.RequestToken,
["saveUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { bookId = default(Guid) }) ?? string.Empty, ["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, ["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, ["backUrl"] = (_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX) ?? string.Empty) + "?libraryId=" + book.LibraryId,
["bookJson"] = JsonSerializer.Serialize(book, s_camelCaseJsonOptions), ["bookJson"] = JsonSerializer.Serialize(book, s_camelCaseJsonOptions),
@@ -9,11 +9,12 @@ using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Common; using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes; using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#endregion #endregion
@@ -76,6 +77,13 @@ public class BooksIndexViewEndpoint : BaseEndpoint<GetBooksViewRequest, IResult>
return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!); return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!);
LibraryDto library = await _apiHttpClient.GetAsync<LibraryDto>(ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); LibraryDto library = await _apiHttpClient.GetAsync<LibraryDto>(ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false);
Dictionary<string, object?> 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() ThemePageDto pageModel = new()
{ {
PageKey = VIEW_PAGE_KEY, PageKey = VIEW_PAGE_KEY,
@@ -88,8 +96,11 @@ public class BooksIndexViewEndpoint : BaseEndpoint<GetBooksViewRequest, IResult>
["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty, ["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty,
["readUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) }) ?? 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, ["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, ["availabilityUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) }) ?? string.Empty,
["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) ["strings"] = strings,
["stringsJson"] = stringsJson
} }
}; };
@@ -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;
/// <summary>
/// API endpoint for the <c>/{culture}/library/written-content-library/books-library/books/{bookId}/api-restore-book</c> route.
/// </summary>
public class RestoreBookEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public RestoreBookEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.POST);
Routes(WebRoutes.Books.RESTORE_BOOK);
DontAutoTag();
Options(options => options.WithTags("Books"));
EnableAntiforgery();
}
/// <summary>
/// Restores the deleted book identified by the route.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
ApiRoutes.Books.RESTORE_BOOK.Replace("{libraryId}", libraryId).Replace("{bookId}", bookId),
new Web.Common.Requests.Common.EmptyRequest(),
cancellationToken).ConfigureAwait(false);
return JsonSuccess(new { isRestored = true });
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
/// <summary>
/// Class used for providing a textual description for the <see cref="RestoreBookEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointSummary : Summary<RestoreBookEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointSummary"/> class.
/// </summary>
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.");
}
}
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>العناصر المحذوفة</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>العودة إلى المكتبة</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>لا توجد عناصر محذوفة في هذه المكتبة.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>الكتاب</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>تاريخ الحذف</value>
</data>
<data name="Restore" xml:space="preserve">
<value>استعادة</value>
</data>
<data name="Restored" xml:space="preserve">
<value>تمت استعادة الكتاب.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>تعذرت استعادة الكتاب.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Gelöschte Elemente</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>Zurück zur Bibliothek</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>In dieser Bibliothek gibt es keine gelöschten Elemente.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>Buch</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>Gelöscht am</value>
</data>
<data name="Restore" xml:space="preserve">
<value>Wiederherstellen</value>
</data>
<data name="Restored" xml:space="preserve">
<value>Das Buch wurde wiederhergestellt.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>Das Buch konnte nicht wiederhergestellt werden.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Deleted items</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>Back to library</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>There are no deleted items in this library.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>Book</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>Deleted on</value>
</data>
<data name="Restore" xml:space="preserve">
<value>Restore</value>
</data>
<data name="Restored" xml:space="preserve">
<value>The book was restored.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>The book could not be restored.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Elementos eliminados</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>Volver a la biblioteca</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>No hay elementos eliminados en esta biblioteca.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>Libro</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>Eliminado el</value>
</data>
<data name="Restore" xml:space="preserve">
<value>Restaurar</value>
</data>
<data name="Restored" xml:space="preserve">
<value>El libro se ha restaurado.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>El libro no se ha podido restaurar.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Éléments supprimés</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>Retour à la bibliothèque</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>Cette bibliothèque ne contient aucun élément supprimé.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>Livre</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>Supprimé le</value>
</data>
<data name="Restore" xml:space="preserve">
<value>Restaurer</value>
</data>
<data name="Restored" xml:space="preserve">
<value>Le livre a été restauré.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>Le livre n'a pas pu être restauré.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Elementi eliminati</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>Torna alla biblioteca</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>Non ci sono elementi eliminati in questa biblioteca.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>Libro</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>Eliminato il</value>
</data>
<data name="Restore" xml:space="preserve">
<value>Ripristina</value>
</data>
<data name="Restored" xml:space="preserve">
<value>Il libro è stato ripristinato.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>Non è stato possibile ripristinare il libro.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>削除済みアイテム</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>ライブラリに戻る</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>このライブラリに削除済みアイテムはありません。</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>本</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>削除日</value>
</data>
<data name="Restore" xml:space="preserve">
<value>復元</value>
</data>
<data name="Restored" xml:space="preserve">
<value>本が復元されました。</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>本を復元できませんでした。</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Deleted items</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>Back to library</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>There are no deleted items in this library.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>Book</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>Deleted on</value>
</data>
<data name="Restore" xml:space="preserve">
<value>Restore</value>
</data>
<data name="Restored" xml:space="preserve">
<value>The book was restored.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>The book could not be restored.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Elemente șterse</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>Înapoi la bibliotecă</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>Nu există elemente șterse în această bibliotecă.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>Carte</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>Șters la</value>
</data>
<data name="Restore" xml:space="preserve">
<value>Restaurează</value>
</data>
<data name="Restored" xml:space="preserve">
<value>Cartea a fost restaurată.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>Cartea nu a putut fi restaurată.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Видалені елементи</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>Повернутися до бібліотеки</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>У цій бібліотеці немає видалених елементів.</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>Книга</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>Видалено</value>
</data>
<data name="Restore" xml:space="preserve">
<value>Відновити</value>
</data>
<data name="Restored" xml:space="preserve">
<value>Книгу відновлено.</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>Не вдалося відновити книгу.</value>
</data>
</root>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>已删除项目</value>
</data>
<data name="BackToLibrary" xml:space="preserve">
<value>返回图书馆</value>
</data>
<data name="NoDeletedItems" xml:space="preserve">
<value>此库中没有已删除项目。</value>
</data>
<data name="BookTitle" xml:space="preserve">
<value>图书</value>
</data>
<data name="DeletedOn" xml:space="preserve">
<value>删除时间</value>
</data>
<data name="Restore" xml:space="preserve">
<value>恢复</value>
</data>
<data name="Restored" xml:space="preserve">
<value>图书已恢复。</value>
</data>
<data name="RestoreFailed" xml:space="preserve">
<value>无法恢复图书。</value>
</data>
</root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>عرض التفاصيل</value> <value>عرض التفاصيل</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>حذف</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>هل أنت متأكد من أنك تريد حذف هذا العنصر؟</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>تعذر حذف العنصر.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>العناصر المحذوفة</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>Details anzeigen</value> <value>Details anzeigen</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>Löschen</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Möchten Sie dieses Element wirklich löschen?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>Das Element konnte nicht gelöscht werden.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>Gelöschte Elemente</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>View details</value> <value>View details</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Are you sure you want to delete this item?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>The item could not be deleted.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>Deleted items</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>Ver detalles</value> <value>Ver detalles</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>Eliminar</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>¿Seguro que quieres eliminar este elemento?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>No se ha podido eliminar el elemento.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>Elementos eliminados</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>Voir les détails</value> <value>Voir les détails</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>Supprimer</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Voulez-vous vraiment supprimer cet élément ?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>L'élément n'a pas pu être supprimé.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>Éléments supprimés</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>Visualizza dettagli</value> <value>Visualizza dettagli</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>Elimina</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Sei sicuro di voler eliminare questo elemento?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>Non è stato possibile eliminare l'elemento.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>Elementi eliminati</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>詳細を表示</value> <value>詳細を表示</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>削除</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>この項目を削除してもよろしいですか?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>項目を削除できませんでした。</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>削除済みアイテム</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>View details</value> <value>View details</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Are you sure you want to delete this item?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>The item could not be deleted.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>Deleted items</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>Vezi detalii</value> <value>Vezi detalii</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>Șterge</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Sigur doriți să ștergeți acest element?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>Elementul nu a putut fi șters.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>Elemente șterse</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>Переглянути деталі</value> <value>Переглянути деталі</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>Видалити</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Ви впевнені, що хочете видалити цей елемент?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>Не вдалося видалити елемент.</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>Видалені елементи</value>
</data>
</root> </root>
@@ -57,4 +57,16 @@
<data name="ViewDetails" xml:space="preserve"> <data name="ViewDetails" xml:space="preserve">
<value>查看详情</value> <value>查看详情</value>
</data> </data>
<data name="Delete" xml:space="preserve">
<value>删除</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>确定要删除此项目吗?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>无法删除该项目。</value>
</data>
<data name="DeletedItems" xml:space="preserve">
<value>已删除项目</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>إضافة وسم</value> <value>إضافة وسم</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>حذف الكتاب</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>تم حذف الكتاب.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>هل أنت متأكد من أنك تريد حذف هذا العنصر؟</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>تعذر حذف العنصر.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>Schlagwort hinzufügen</value> <value>Schlagwort hinzufügen</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>Buch löschen</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>Das Buch wurde gelöscht.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Möchten Sie dieses Element wirklich löschen?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>Das Element konnte nicht gelöscht werden.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>Add tag</value> <value>Add tag</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>Delete book</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>The book was deleted.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Are you sure you want to delete this item?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>The item could not be deleted.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>Añadir etiqueta</value> <value>Añadir etiqueta</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>Eliminar libro</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>El libro se ha eliminado.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>¿Seguro que quieres eliminar este elemento?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>El elemento no se ha podido eliminar.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>Ajouter une étiquette</value> <value>Ajouter une étiquette</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>Supprimer le livre</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>Le livre a été supprimé.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Voulez-vous vraiment supprimer cet élément ?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>L'élément n'a pas pu être supprimé.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>Aggiungi etichetta</value> <value>Aggiungi etichetta</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>Elimina libro</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>Il libro è stato eliminato.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Sei sicuro di voler eliminare questo elemento?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>Non è stato possibile eliminare l'elemento.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>タグを追加</value> <value>タグを追加</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>本を削除</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>本が削除されました。</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>この項目を削除してもよろしいですか?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>項目を削除できませんでした。</value>
</data>
</root> </root>
@@ -1083,4 +1083,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>Add tag</value> <value>Add tag</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>Delete book</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>The book was deleted.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Are you sure you want to delete this item?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>The item could not be deleted.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>Adaugă etichetă</value> <value>Adaugă etichetă</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>Șterge cartea</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>Cartea a fost ștearsă.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Sigur doriți să ștergeți acest element?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>Elementul nu a putut fi șters.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>Додати тег</value> <value>Додати тег</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>Видалити книгу</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>Книгу видалено.</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>Ви впевнені, що хочете видалити цей елемент?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>Не вдалося видалити елемент.</value>
</data>
</root> </root>
@@ -1084,4 +1084,16 @@
<data name="AddTag" xml:space="preserve"> <data name="AddTag" xml:space="preserve">
<value>添加标签</value> <value>添加标签</value>
</data> </data>
<data name="DeleteBook" xml:space="preserve">
<value>删除图书</value>
</data>
<data name="BookDeleted" xml:space="preserve">
<value>图书已删除。</value>
</data>
<data name="DeleteConfirm" xml:space="preserve">
<value>确定要删除此项目吗?</value>
</data>
<data name="DeleteFailed" xml:space="preserve">
<value>无法删除该项目。</value>
</data>
</root> </root>
@@ -127,7 +127,7 @@
const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.UPDATE_USER_AUTHORIZATION)', formData); const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.UPDATE_USER_AUTHORIZATION)', formData);
if (result.success) if (result.success)
notificationService.show('@_localizer["UserAuthorizationUpdated"]', NotificationType.SUCCESS); notificationService.show(@Json.Serialize(_localizer["UserAuthorizationUpdated"].Value), NotificationType.SUCCESS);
} }
async function fetchUserRoleAsync(userId) { async function fetchUserRoleAsync(userId) {
@@ -178,7 +178,7 @@
// Users dropdown change. // Users dropdown change.
if (e.target.closest('#authorization-users-combobox .enlightenment-option')) { if (e.target.closest('#authorization-users-combobox .enlightenment-option')) {
var selectedUserId = e.target.dataset.value; 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); document.querySelectorAll("input[name='authorization-permissions-permissions']").forEach(input => input.checked = false);
roleIdInput.value = ''; roleIdInput.value = '';
userIdInput.value = ''; userIdInput.value = '';
@@ -112,7 +112,7 @@
{ success: (await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.CREATE_ROLE)', formData)) !== undefined }; { success: (await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Admin.CREATE_ROLE)', formData)) !== undefined };
if (result.success) { if (result.success) {
await fetchRolesAsync(); 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. // 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". // All permissions should be "unchecked".
document.querySelectorAll("input[name='authorization-role-permissions']") document.querySelectorAll("input[name='authorization-role-permissions']")
@@ -147,7 +147,7 @@
btnDeleteRole.classList.add('hidden'); btnDeleteRole.classList.add('hidden');
// The "update" button should be "create". // 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. // The input for the role name should also have its text emptied.
txtRoleName.value = ''; txtRoleName.value = '';
@@ -195,12 +195,12 @@
// On delete role button click. // On delete role button click.
const handleBtnDeleteRoleClick = async function(e) { const handleBtnDeleteRoleClick = async function(e) {
// Ask the user for confirmation before deleting the role. // 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 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. 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) { if (success) {
await fetchRolesAsync(); await fetchRolesAsync();
notificationService.show('@_localizer["RoleDeleted"]', NotificationType.SUCCESS); notificationService.show(@Json.Serialize(_localizer["RoleDeleted"].Value), NotificationType.SUCCESS);
} }
} }
}; };
@@ -218,13 +218,13 @@
if (roleId) { if (roleId) {
btnDeleteRole.classList.remove('hidden'); btnDeleteRole.classList.remove('hidden');
btnDeleteRole.classList.add('inline'); btnDeleteRole.classList.add('inline');
btnConfirmRole.textContent = '@_localizer["UpdateRole"]'; btnConfirmRole.textContent = @Json.Serialize(_localizer["UpdateRole"].Value);
roleIdInput.value = roleId; roleIdInput.value = roleId;
} else { } else {
roleIdInput.value = ''; roleIdInput.value = '';
btnDeleteRole.classList.remove('inline'); btnDeleteRole.classList.remove('inline');
btnDeleteRole.classList.add('hidden'); btnDeleteRole.classList.add('hidden');
btnConfirmRole.textContent = '@_localizer["CreateRole"]'; btnConfirmRole.textContent = @Json.Serialize(_localizer["CreateRole"].Value);
} }
} }
}; };
@@ -181,7 +181,7 @@
const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Plugins.UPDATE_PLUGIN_SETTINGS)'; const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Plugins.UPDATE_PLUGIN_SETTINGS)';
const result = await callApiPutAsync(url, { pluginId: pluginId, settings: settings }); const result = await callApiPutAsync(url, { pluginId: pluginId, settings: settings });
if (result.success) { if (result.success) {
notificationService.show('@_localizer["SettingsSaved"]', NotificationType.SUCCESS); notificationService.show(@Json.Serialize(_localizer["SettingsSaved"].Value), NotificationType.SUCCESS);
} }
} }
}; };
@@ -205,10 +205,10 @@
body: formData body: formData
}); });
if (response.ok) { if (response.ok) {
notificationService.show('@_localizer["PluginUploadedRestartRequired"]', NotificationType.SUCCESS); notificationService.show(@Json.Serialize(_localizer["PluginUploadedRestartRequired"].Value), NotificationType.SUCCESS);
uploadInput.value = ''; uploadInput.value = '';
} else { } else {
notificationService.show('@_localizer["UploadFailed"]', NotificationType.ERROR); notificationService.show(@Json.Serialize(_localizer["UploadFailed"].Value), NotificationType.ERROR);
} }
} }
@@ -166,29 +166,29 @@ It keeps the DOM contract the client script binds to, without any images or colo
// Localized strings. // Localized strings.
const schedulerStrings = { const schedulerStrings = {
noJobs: '@_localizer["NoJobs"]', noJobs: @Json.Serialize(_localizer["NoJobs"].Value),
daily: '@_localizer["DailySchedule"]', daily: @Json.Serialize(_localizer["DailySchedule"].Value),
interval: '@_localizer["IntervalSchedule"]', interval: @Json.Serialize(_localizer["IntervalSchedule"].Value),
startup: '@_localizer["StartupSchedule"]', startup: @Json.Serialize(_localizer["StartupSchedule"].Value),
jobStarted: '@_localizer["JobStarted"]', jobStarted: @Json.Serialize(_localizer["JobStarted"].Value),
jobRemoved: '@_localizer["JobRemoved"]', jobRemoved: @Json.Serialize(_localizer["JobRemoved"].Value),
jobStopped: '@_localizer["JobStopped"]', jobStopped: @Json.Serialize(_localizer["JobStopped"].Value),
jobFired: '@_localizer["JobFired"]', jobFired: @Json.Serialize(_localizer["JobFired"].Value),
jobAdded: '@_localizer["JobAdded"]', jobAdded: @Json.Serialize(_localizer["JobAdded"].Value),
jobNotFound: '@_localizer["JobNotFound"]', jobNotFound: @Json.Serialize(_localizer["JobNotFound"].Value),
jobAlreadyRunning: '@_localizer["JobAlreadyRunning"]', jobAlreadyRunning: @Json.Serialize(_localizer["JobAlreadyRunning"].Value),
taskTypeNames: { taskTypeNames: {
ScanMediaLibraries: '@_localizer["TaskType.ScanMediaLibraries"]', ScanMediaLibraries: @Json.Serialize(_localizer["TaskType.ScanMediaLibraries"].Value),
CleanTemporaryFiles: '@_localizer["TaskType.CleanTemporaryFiles"]', CleanTemporaryFiles: @Json.Serialize(_localizer["TaskType.CleanTemporaryFiles"].Value),
RepairThemes: '@_localizer["TaskType.RepairThemes"]', RepairThemes: @Json.Serialize(_localizer["TaskType.RepairThemes"].Value),
CleanScheduledJobExecutionHistory: '@_localizer["TaskType.CleanScheduledJobExecutionHistory"]', CleanScheduledJobExecutionHistory: @Json.Serialize(_localizer["TaskType.CleanScheduledJobExecutionHistory"].Value),
TechnicalDataCleanup: '@_localizer["TaskType.TechnicalDataCleanup"]' TechnicalDataCleanup: @Json.Serialize(_localizer["TaskType.TechnicalDataCleanup"].Value)
}, },
statusNames: { statusNames: {
Added: '@_localizer["Status.Added"]', Added: @Json.Serialize(_localizer["Status.Added"].Value),
Active: '@_localizer["Status.Active"]', Active: @Json.Serialize(_localizer["Status.Active"].Value),
Running: '@_localizer["Status.Running"]', Running: @Json.Serialize(_localizer["Status.Running"].Value),
Completed: '@_localizer["Status.Completed"]' 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
<td data-label="${escapeHtml(columnLabels[1])}">${escapeHtml(job.name)}</td> <td data-label="${escapeHtml(columnLabels[1])}">${escapeHtml(job.name)}</td>
<td data-label="${escapeHtml(columnLabels[2])}">${schedulerStrings.taskTypeNames[job.taskType] ?? job.taskType}</td> <td data-label="${escapeHtml(columnLabels[2])}">${schedulerStrings.taskTypeNames[job.taskType] ?? job.taskType}</td>
<td data-label="${escapeHtml(columnLabels[3])}">${scheduleLabel}</td> <td data-label="${escapeHtml(columnLabels[3])}">${scheduleLabel}</td>
<td data-label="${escapeHtml(columnLabels[4])}">${isInterval ? job.intervalMinutes + ' ' + '@_localizer["MinutesShort"]' : '-'}</td> <td data-label="${escapeHtml(columnLabels[4])}">${isInterval ? job.intervalMinutes + ' ' + @Json.Serialize(_localizer["MinutesShort"].Value) : '-'}</td>
<td data-label="${escapeHtml(columnLabels[5])}">${isDaily ? String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0') : '-'}</td> <td data-label="${escapeHtml(columnLabels[5])}">${isDaily ? String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0') : '-'}</td>
<td data-label="${escapeHtml(columnLabels[6])}">${schedulerStrings.statusNames[job.status] ?? job.status}</td> <td data-label="${escapeHtml(columnLabels[6])}">${schedulerStrings.statusNames[job.status] ?? job.status}</td>
<td data-label="${escapeHtml(columnLabels[7])}">${formatDateTime(job.lastStartedOnUtc)}</td> <td data-label="${escapeHtml(columnLabels[7])}">${formatDateTime(job.lastStartedOnUtc)}</td>
@@ -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 isRunning = job.status === 'Running';
const isActive = job.status === 'Active'; const isActive = job.status === 'Active';
const canStop = isActive || isRunning; const canStop = isActive || isRunning;
actionsDiv.appendChild(createActionButton('@_localizer["Start"]', () => startJobAsync(job.id), canStop)); actionsDiv.appendChild(createActionButton(@Json.Serialize(_localizer["Start"].Value), () => startJobAsync(job.id), canStop));
actionsDiv.appendChild(createActionButton('@_localizer["Stop"]', () => stopJobAsync(job.id), !canStop)); actionsDiv.appendChild(createActionButton(@Json.Serialize(_localizer["Stop"].Value), () => stopJobAsync(job.id), !canStop));
actionsDiv.appendChild(createActionButton('@_localizer["Fire"]', () => fireJobAsync(job.id), isRunning)); 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. // 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); actionsCell.appendChild(actionsDiv);
row.appendChild(actionsCell); 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) { 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)); const removed = await callApiDeleteAsync(getJobActionUrl(removeJobUrlTemplate, jobId));
if (removed) if (removed)
notificationService.show(schedulerStrings.jobRemoved, NotificationType.SUCCESS); 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 minute: scheduleType === 'DailyAtHourAndMinute' ? Number(jobMinuteInput.value) : null
}; };
if (!payload.name) { if (!payload.name) {
notificationService.show('@_localizer["JobNameRequired"]', NotificationType.ERROR); notificationService.show(@Json.Serialize(_localizer["JobNameRequired"].Value), NotificationType.ERROR);
return; return;
} }
const response = await callApiPostAsync(addJobUrl, payload); const response = await callApiPostAsync(addJobUrl, payload);
@@ -180,7 +180,7 @@
const button = event.target.closest('.delete-theme-button'); const button = event.target.closest('.delete-theme-button');
if (!button) if (!button)
return; 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); await callApiDeleteAsync(button.dataset.url);
refreshPageContent(); refreshPageContent();
} }
@@ -238,7 +238,7 @@
if (response.ok) if (response.ok)
refreshPageContent(); refreshPageContent();
else 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. // Opens the file picker when the upload button is clicked.
@@ -103,20 +103,20 @@
}; };
const jsLocalizedStrings = { const jsLocalizedStrings = {
all: '@_localizer["All"]', all: @Json.Serialize(_localizer["All"].Value),
items: '@_localizer["Items"]', items: @Json.Serialize(_localizer["Items"].Value),
of: '@_localizer["Of"]', of: @Json.Serialize(_localizer["Of"].Value),
page: '@_localizer["Page"]', page: @Json.Serialize(_localizer["Page"].Value),
sortAscending: '@_localizer["SortAscending"]', sortAscending: @Json.Serialize(_localizer["SortAscending"].Value),
sortDescending: '@_localizer["SortDescending"]', sortDescending: @Json.Serialize(_localizer["SortDescending"].Value),
viewDetails: '@_localizer["ViewDetails"]', viewDetails: @Json.Serialize(_localizer["ViewDetails"].Value),
actions: '@_localizer["Actions"]', actions: @Json.Serialize(_localizer["Actions"].Value),
play: '@_localizer["Play"]', play: @Json.Serialize(_localizer["Play"].Value),
shuffle: '@_localizer["Shuffle"]', shuffle: @Json.Serialize(_localizer["Shuffle"].Value),
deleteItem: '@_localizer["Delete"]', deleteItem: @Json.Serialize(_localizer["Delete"].Value),
deleteConfirm: '@_localizer["DeleteConfirm"]', deleteConfirm: @Json.Serialize(_localizer["DeleteConfirm"].Value),
deleteFailed: '@_localizer["DeleteFailed"]', deleteFailed: @Json.Serialize(_localizer["DeleteFailed"].Value),
addToPlaylist: '@_localizer["AddToPlaylist"]' addToPlaylist: @Json.Serialize(_localizer["AddToPlaylist"].Value)
}; };
function buildItemsUrl() { function buildItemsUrl() {
@@ -975,23 +975,23 @@
// The localized labels of the release types, keyed by their canonical enum name. // The localized labels of the release types, keyed by their canonical enum name.
const releaseTypeLabels = { const releaseTypeLabels = {
'Album': '@_localizer["Album"].Value', 'Album': @Json.Serialize(_localizer["Album"].Value),
'Broadcast': '@_localizer["Broadcast"].Value', 'Broadcast': @Json.Serialize(_localizer["Broadcast"].Value),
'Ep': '@_localizer["Ep"].Value', 'Ep': @Json.Serialize(_localizer["Ep"].Value),
'Other': '@_localizer["Other"].Value', 'Other': @Json.Serialize(_localizer["Other"].Value),
'Single': '@_localizer["Single"].Value', 'Single': @Json.Serialize(_localizer["Single"].Value),
'AudioDrama': '@_localizer["AudioDrama"].Value', 'AudioDrama': @Json.Serialize(_localizer["AudioDrama"].Value),
'AudioBook': '@_localizer["AudioBook"].Value', 'AudioBook': @Json.Serialize(_localizer["AudioBook"].Value),
'Compilation': '@_localizer["Compilation"].Value', 'Compilation': @Json.Serialize(_localizer["Compilation"].Value),
'DjMix': '@_localizer["DjMix"].Value', 'DjMix': @Json.Serialize(_localizer["DjMix"].Value),
'Demo': '@_localizer["Demo"].Value', 'Demo': @Json.Serialize(_localizer["Demo"].Value),
'FieldRecording': '@_localizer["FieldRecording"].Value', 'FieldRecording': @Json.Serialize(_localizer["FieldRecording"].Value),
'Interview': '@_localizer["Interview"].Value', 'Interview': @Json.Serialize(_localizer["Interview"].Value),
'Live': '@_localizer["Live"].Value', 'Live': @Json.Serialize(_localizer["Live"].Value),
'Mixtape': '@_localizer["Mixtape"].Value', 'Mixtape': @Json.Serialize(_localizer["Mixtape"].Value),
'Remix': '@_localizer["Remix"].Value', 'Remix': @Json.Serialize(_localizer["Remix"].Value),
'Soundtrack': '@_localizer["Soundtrack"].Value', 'Soundtrack': @Json.Serialize(_localizer["Soundtrack"].Value),
'SpokenWord': '@_localizer["SpokenWord"].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. // 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']; const releaseTypeOrder = ['Album', 'Compilation', 'Ep', 'Live', 'Remix', 'Single', 'Soundtrack', 'Broadcast', 'AudioDrama', 'AudioBook', 'Demo', 'DjMix', 'FieldRecording', 'Interview', 'Mixtape', 'SpokenWord', 'Other'];
@@ -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()
<div style="display: grid; grid-template-rows: auto 1fr;">
<div style="min-height: 1rem;"></div>
<div class="enlightenment-panel shadow-effect mx-auto panel w-60 mb-10 deleted-books-panel" style="min-width: 320px;">
<div class="shine-effect"></div>
<div class="form-row deleted-books-top-bar">
<button id="btn-back-to-library" type="button" class="abort-button">@_localizer["BackToLibrary"]</button>
</div>
<div class="form-row deleted-books-title-row">
<h1 class="text-light-two w-100 text-center pt-0 pb-0 engraved-title">@_localizer["Title"]</h1>
</div>
<p id="no-deleted-books" class="text-light-two text-center @(Model.DeletedBooks.Count == 0 ? string.Empty : "hidden")">@_localizer["NoDeletedItems"]</p>
<table id="deleted-books-table" class="w-100 form-table deleted-books-table @(Model.DeletedBooks.Count == 0 ? "hidden" : string.Empty)">
<thead>
<tr>
<th>@_localizer["BookTitle"]</th>
<th>@_localizer["DeletedOn"]</th>
<th class="w-100px"></th>
</tr>
</thead>
<tbody>
@foreach (DeletedBookDto book in Model.DeletedBooks)
{
<tr class="deleted-book-row" data-book-id="@book.Id">
<td>@book.Title</td>
<td>@book.DeletedOnUtc.ToString("g")</td>
<td>
<button type="button" class="confirm-button w-100px btn-restore-book" data-book-id="@book.Id">@_localizer["Restore"]</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
@section Scripts {
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls. site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// Create cleanup registry for this view.
const cleanupFunctions = [];
let isInitialized = false;
const libraryId = '@libraryId';
const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)';
const restoreUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.RESTORE_BOOK, 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 btnBackToLibrary = document.getElementById('btn-back-to-library');
const deletedBooksTable = document.getElementById('deleted-books-table');
const noDeletedBooks = document.getElementById('no-deleted-books');
const jsLocalizedStrings = {
restored: @Json.Serialize(_localizer["Restored"].Value),
restoreFailed: @Json.Serialize(_localizer["RestoreFailed"].Value)
};
// Restores the clicked deleted book, then removes its row from the page.
async function handleRestoreAsync(event) {
const button = event.target.closest('.btn-restore-book');
if (!button || button.disabled)
return;
button.disabled = true;
try {
const url = restoreUrlTemplate.replace('/@(default(Guid))', `/${button.dataset.bookId}`) + `?libraryId=${encodeURIComponent(libraryId)}`;
const result = await callApiPostAsync(url, {});
if (result?.isRestored !== true) {
notificationService.show(jsLocalizedStrings.restoreFailed, NotificationType.ERROR);
return;
}
notificationService.show(jsLocalizedStrings.restored, NotificationType.SUCCESS);
button.closest('.deleted-book-row')?.remove();
if (deletedBooksTable && deletedBooksTable.querySelectorAll('.deleted-book-row').length === 0) {
deletedBooksTable.classList.add('hidden');
noDeletedBooks?.classList.remove('hidden');
}
} finally {
if (button.isConnected)
button.disabled = false;
}
}
// Navigates back to the library page of the deleted books.
async function handleBackToLibraryAsync() {
await updateContentAsync(`${libraryIndexUrl}?libraryId=${encodeURIComponent(libraryId)}`, true);
}
// Add listeners.
btnBackToLibrary.addEventListener('click', handleBackToLibraryAsync);
deletedBooksTable.addEventListener('click', handleRestoreAsync);
document.addEventListener('DOMContentLoaded', InitializeAsync);
// Register cleanup for these listeners.
cleanupFunctions.push(() => {
btnBackToLibrary.removeEventListener('click', handleBackToLibraryAsync);
deletedBooksTable.removeEventListener('click', handleRestoreAsync);
document.removeEventListener('DOMContentLoaded', InitializeAsync);
});
function InitializeAsync() {
if (isInitialized)
return;
isInitialized = true;
}
// Store all cleanups for this view on window object using the scriptId.
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -39,6 +39,7 @@
<input id="search-input" type="text" class="enlightenment-input w-200px" placeholder="@_localizer["Search"]" /> <input id="search-input" type="text" class="enlightenment-input w-200px" placeholder="@_localizer["Search"]" />
<button id="search-button" type="button" class="confirm-button">@_localizer["Search"]</button> <button id="search-button" type="button" class="confirm-button">@_localizer["Search"]</button>
<button id="sort-toggle" type="button" class="confirm-button">@_localizer["SortAscending"]</button> <button id="sort-toggle" type="button" class="confirm-button">@_localizer["SortAscending"]</button>
<button id="btn-deleted-books" type="button" class="abort-button">@_localizer["DeletedItems"]</button>
<span id="count-label" class="text-light-two"></span> <span id="count-label" class="text-light-two"></span>
</div> </div>
<div style="display: flex; align-items: flex-start;"> <div style="display: flex; align-items: flex-start;">
@@ -63,10 +64,14 @@
const cleanupFunctions = []; const cleanupFunctions = [];
let isInitialized = false; let isInitialized = false;
let requestSequence = 0; 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 libraryId = '@(Model.Id ?? Guid.Empty)';
const readUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) })'; const readUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) })';
const detailsUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, 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) })'; 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. // 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'); const booksContainer = document.getElementById('books-container');
@@ -75,6 +80,7 @@
const searchInput = document.getElementById('search-input'); const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button'); const searchButton = document.getElementById('search-button');
const sortToggle = document.getElementById('sort-toggle'); const sortToggle = document.getElementById('sort-toggle');
const btnDeletedBooks = document.getElementById('btn-deleted-books');
const countLabel = document.getElementById('count-label'); const countLabel = document.getElementById('count-label');
const alphaPicker = document.getElementById('alpha-picker'); const alphaPicker = document.getElementById('alpha-picker');
const pagination = document.getElementById('pagination'); const pagination = document.getElementById('pagination');
@@ -95,16 +101,19 @@
}; };
const jsLocalizedStrings = { const jsLocalizedStrings = {
all: '@_localizer["All"]', all: @Json.Serialize(_localizer["All"].Value),
items: '@_localizer["Items"]', items: @Json.Serialize(_localizer["Items"].Value),
of: '@_localizer["Of"]', of: @Json.Serialize(_localizer["Of"].Value),
page: '@_localizer["Page"]', page: @Json.Serialize(_localizer["Page"].Value),
sortAscending: '@_localizer["SortAscending"]', sortAscending: @Json.Serialize(_localizer["SortAscending"].Value),
sortDescending: '@_localizer["SortDescending"]', sortDescending: @Json.Serialize(_localizer["SortDescending"].Value),
readerUnavailable: '@_localizer["ReaderUnavailable"]', readerUnavailable: @Json.Serialize(_localizer["ReaderUnavailable"].Value),
readerDisabled: '@_localizer["ReaderDisabled"]', readerDisabled: @Json.Serialize(_localizer["ReaderDisabled"].Value),
read: '@_localizer["Read"]', read: @Json.Serialize(_localizer["Read"].Value),
viewDetails: '@_localizer["ViewDetails"]' 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. // Builds the URL of the retrieval endpoint, from the current state.
@@ -213,17 +222,23 @@
menu.setAttribute('role', 'menu'); menu.setAttribute('role', 'menu');
menu.innerHTML = ` menu.innerHTML = `
<a role="menuitem" href="${readUrlTemplate.replace('/@(default(Guid))', `/${book.id}`) + `?libraryId=${libraryId}`}">${jsLocalizedStrings.read}</a> <a role="menuitem" href="${readUrlTemplate.replace('/@(default(Guid))', `/${book.id}`) + `?libraryId=${libraryId}`}">${jsLocalizedStrings.read}</a>
<a role="menuitem" href="${detailsUrl}">${jsLocalizedStrings.viewDetails}</a>`; <a role="menuitem" href="${detailsUrl}">${jsLocalizedStrings.viewDetails}</a>
<a role="menuitem" href="#" class="card-action-delete">${jsLocalizedStrings.deleteItem}</a>`;
// Menu entries navigate through the same AJAX navigation used by the nav-links, so that the persistent chrome keeps running. // 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 => { menu.addEventListener('click', async event => {
const deleteItem = event.target.closest('.card-action-delete');
const menuItem = event.target.closest('a[role="menuitem"]'); const menuItem = event.target.closest('a[role="menuitem"]');
if (!menuItem) if (!menuItem)
return; return;
event.preventDefault(); event.preventDefault();
event.stopImmediatePropagation(); event.stopImmediatePropagation();
closeCardMenus(); 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. // 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. // Updates the count label: total items when pagination is off, displayed range out of total when it is on.
function updateCountLabel(response) { function updateCountLabel(response) {
if (!countLabel) 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. // Navigates to the previous page.
function handlePrevPageClick() { function handlePrevPageClick() {
state.currentPage = Math.max(1, state.currentPage - 1); state.currentPage = Math.max(1, state.currentPage - 1);
@@ -468,6 +515,7 @@
bindEventHandler(searchButton, 'click', handleSearch); bindEventHandler(searchButton, 'click', handleSearch);
bindEventHandler(searchInput, 'keydown', handleSearchKeydown); bindEventHandler(searchInput, 'keydown', handleSearchKeydown);
bindEventHandler(sortToggle, 'click', handleSortToggle); bindEventHandler(sortToggle, 'click', handleSortToggle);
bindEventHandler(btnDeletedBooks, 'click', handleDeletedBooksAsync);
bindEventHandler(prevPageButton, 'click', handlePrevPageClick); bindEventHandler(prevPageButton, 'click', handlePrevPageClick);
bindEventHandler(nextPageButton, 'click', handleNextPageClick); bindEventHandler(nextPageButton, 'click', handleNextPageClick);
document.addEventListener('keydown', handleAlphaKeydown); document.addEventListener('keydown', handleAlphaKeydown);
@@ -480,6 +528,7 @@
unbindEventHandler(searchButton, 'click', handleSearch); unbindEventHandler(searchButton, 'click', handleSearch);
unbindEventHandler(searchInput, 'keydown', handleSearchKeydown); unbindEventHandler(searchInput, 'keydown', handleSearchKeydown);
unbindEventHandler(sortToggle, 'click', handleSortToggle); unbindEventHandler(sortToggle, 'click', handleSortToggle);
unbindEventHandler(btnDeletedBooks, 'click', handleDeletedBooksAsync);
unbindEventHandler(prevPageButton, 'click', handlePrevPageClick); unbindEventHandler(prevPageButton, 'click', handlePrevPageClick);
unbindEventHandler(nextPageButton, 'click', handleNextPageClick); unbindEventHandler(nextPageButton, 'click', handleNextPageClick);
document.removeEventListener('keydown', handleAlphaKeydown); document.removeEventListener('keydown', handleAlphaKeydown);
@@ -527,6 +527,7 @@
<div class="form-row mt-10"> <div class="form-row mt-10">
<button id="btn-save-book" type="button" class="confirm-button w-100px">@_localizer["Save"]</button> <button id="btn-save-book" type="button" class="confirm-button w-100px">@_localizer["Save"]</button>
<button id="btn-delete-book" type="button" class="abort-button w-100px">@_localizer["DeleteBook"]</button>
</div> </div>
</div> </div>
</div> </div>
@@ -545,6 +546,7 @@
const libraryId = '@libraryId'; const libraryId = '@libraryId';
const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)'; const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)';
const saveUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`); 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}`; 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. // 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 btnChangeCover = document.getElementById('btn-change-cover');
const btnBackToLibrary = document.getElementById('btn-back-to-library'); const btnBackToLibrary = document.getElementById('btn-back-to-library');
const btnSaveBook = document.getElementById('btn-save-book'); const btnSaveBook = document.getElementById('btn-save-book');
const btnDeleteBook = document.getElementById('btn-delete-book');
const isbnsBody = document.getElementById('isbns-body'); const isbnsBody = document.getElementById('isbns-body');
const contributorsBody = document.getElementById('contributors-body'); const contributorsBody = document.getElementById('contributors-body');
const ratingsBody = document.getElementById('ratings-body'); const ratingsBody = document.getElementById('ratings-body');
@@ -570,6 +573,9 @@
coverSaved: @Json.Serialize(_localizer["CoverSaved"].Value), coverSaved: @Json.Serialize(_localizer["CoverSaved"].Value),
saveFailed: @Json.Serialize(_localizer["SaveFailed"].Value), saveFailed: @Json.Serialize(_localizer["SaveFailed"].Value),
coverUploadFailed: @Json.Serialize(_localizer["CoverUploadFailed"].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), noCover: @Json.Serialize(_localizer["NoCover"].Value),
remove: @Json.Serialize(_localizer["Remove"].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. // Opens the file picker that chooses the new cover image.
function handleChangeCoverClick() { function handleChangeCoverClick() {
coverInput.click(); coverInput.click();
@@ -880,6 +898,7 @@
// Add listeners. // Add listeners.
btnSaveBook.addEventListener('click', handleSaveAsync); btnSaveBook.addEventListener('click', handleSaveAsync);
btnDeleteBook.addEventListener('click', handleDeleteAsync);
btnBackToLibrary.addEventListener('click', handleBackToLibraryAsync); btnBackToLibrary.addEventListener('click', handleBackToLibraryAsync);
btnChangeCover.addEventListener('click', handleChangeCoverClick); btnChangeCover.addEventListener('click', handleChangeCoverClick);
coverInput.addEventListener('change', handleCoverChangeAsync); coverInput.addEventListener('change', handleCoverChangeAsync);
@@ -898,6 +917,7 @@
// Register cleanup for these listeners. // Register cleanup for these listeners.
cleanupFunctions.push(() => { cleanupFunctions.push(() => {
btnSaveBook.removeEventListener('click', handleSaveAsync); btnSaveBook.removeEventListener('click', handleSaveAsync);
btnDeleteBook.removeEventListener('click', handleDeleteAsync);
btnBackToLibrary.removeEventListener('click', handleBackToLibraryAsync); btnBackToLibrary.removeEventListener('click', handleBackToLibraryAsync);
btnChangeCover.removeEventListener('click', handleChangeCoverClick); btnChangeCover.removeEventListener('click', handleChangeCoverClick);
coverInput.removeEventListener('change', handleCoverChangeAsync); coverInput.removeEventListener('change', handleCoverChangeAsync);
@@ -409,7 +409,7 @@
}; };
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData); const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData);
if (data && data.isUpdated === true) { 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 // 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. // 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') if (window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance && typeof window.LuminaAudioPlayer.instance.reloadPreferencesAsync === 'function')
+2
View File
@@ -249,6 +249,8 @@
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBook.http" /> <File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http" /> <File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http" /> <File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/GetDeletedBooks.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/RestoreBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http" /> <File Path="../docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http" />
<File Path="../docs/technical/requests/library/written-content-library/book-library/books/UpdateBookCover.http" /> <File Path="../docs/technical/requests/library/written-content-library/book-library/books/UpdateBookCover.http" />
</Folder> </Folder>
@@ -33,6 +33,8 @@ public class BookEntityFixture
/// <param name="path">Optional. The file system path of the book.</param> /// <param name="path">Optional. The file system path of the book.</param>
/// <param name="title">Optional. The title of the book.</param> /// <param name="title">Optional. The title of the book.</param>
/// <param name="originalTitle">Optional. The original title of the book.</param> /// <param name="originalTitle">Optional. The original title of the book.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the book was deleted. Only used when the book is marked as deleted.</param>
/// <param name="isDeleted">Optional. Whether the book is marked as deleted.</param>
/// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, ISBNs, Ratings) should be included, or forced to empty collections.</param> /// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, ISBNs, Ratings) should be included, or forced to empty collections.</param>
/// <returns>The created <see cref="BookEntity"/>.</returns> /// <returns>The created <see cref="BookEntity"/>.</returns>
public BookEntity Create( public BookEntity Create(
@@ -41,6 +43,8 @@ public class BookEntityFixture
string? path = null, string? path = null,
string? title = null, string? title = null,
string? originalTitle = null, string? originalTitle = null,
DateTime? deletedOnUtc = null,
bool isDeleted = false,
bool includeMetadata = true) bool includeMetadata = true)
{ {
int releaseYear = Random.Shared.Next(2000, 2010); 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.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
.RuleFor(x => x.ISBNs, f => includeMetadata ? _isbnEntityFixture.CreateMany(f.Random.Number(1, 5)) : []) .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.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.CreatedOnUtc, f => f.Date.Past())
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
.Generate(); .Generate();
@@ -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;
/// <summary>
/// Fixture class for the <see cref="RestoreBookCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="RestoreBookCommand"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the book belongs to, taken from the route.</param>
/// <param name="bookId">Optional. The Id of the deleted book to restore, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBookId">Whether the book Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="RestoreBookCommand"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="RestoreBookCommand"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="RestoreBookCommand"/> instances.</returns>
public List<RestoreBookCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetDeletedBooksQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetDeletedBooksQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose deleted books are retrieved, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetDeletedBooksQuery"/>.</returns>
public GetDeletedBooksQuery Create(
string? libraryId = null,
bool includeLibraryId = true)
{
return new GetDeletedBooksQuery(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="GetDeletedBooksQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetDeletedBooksQuery"/> instances.</returns>
public List<GetDeletedBooksQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="DeletedBookResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedBookResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="DeletedBookResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the deleted book.</param>
/// <param name="libraryId">Optional. The Id of the media library the deleted book belongs to.</param>
/// <param name="title">Optional. The title of the deleted book.</param>
/// <param name="originalTitle">Optional. The original title of the deleted book.</param>
/// <param name="path">Optional. The file system path of the deleted book.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the book was deleted.</param>
/// <param name="coverPath">Optional. The path of the cover image of the deleted book.</param>
/// <param name="includeOriginalTitle">Whether the original title should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeletedBookResponse"/>.</returns>
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
);
}
/// <summary>
/// Creates a list of <see cref="DeletedBookResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedBookResponse"/> instances.</returns>
public List<DeletedBookResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="DeletedBookDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedBookDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="DeletedBookDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The Id of the deleted book.</param>
/// <param name="libraryId">Optional. The Id of the media library the deleted book belongs to.</param>
/// <param name="title">Optional. The title of the deleted book.</param>
/// <param name="originalTitle">Optional. The original title of the deleted book.</param>
/// <param name="path">Optional. The file system path of the deleted book.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the book was deleted.</param>
/// <param name="coverPath">Optional. The relative path of the stored cover image of the deleted book.</param>
/// <param name="includeOriginalTitle">Whether the original title should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeletedBookDto"/>.</returns>
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
);
}
/// <summary>
/// Creates multiple <see cref="DeletedBookDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedBookDto"/> instances.</returns>
public List<DeletedBookDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -51,7 +51,7 @@ public class BookRepositoryTests
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid();
BookEntity changedBook = _bookEntityFixture.Create(); BookEntity changedBook = _bookEntityFixture.Create();
@@ -91,7 +91,7 @@ public class BookRepositoryTests
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(); BookEntity book = _bookEntityFixture.Create();
@@ -120,7 +120,7 @@ public class BookRepositoryTests
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid();
BookEntity enrichedBook = _bookEntityFixture.Create(); BookEntity enrichedBook = _bookEntityFixture.Create();
@@ -155,7 +155,7 @@ public class BookRepositoryTests
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(); BookEntity book = _bookEntityFixture.Create();
@@ -189,7 +189,7 @@ public class BookRepositoryTests
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(); BookEntity book = _bookEntityFixture.Create();
@@ -214,7 +214,7 @@ public class BookRepositoryTests
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid();
BookEntity existingBook = _bookEntityFixture.Create(); BookEntity existingBook = _bookEntityFixture.Create();
@@ -244,7 +244,7 @@ public class BookRepositoryTests
Guid userId = Guid.NewGuid(); Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)]; book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)]; book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)];
@@ -278,7 +278,7 @@ public class BookRepositoryTests
Guid userId = Guid.NewGuid(); Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)]; book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)];
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)]; book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)];
@@ -315,7 +315,7 @@ public class BookRepositoryTests
Guid userId = Guid.NewGuid(); Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
Guid keptMediaContributorId = Guid.NewGuid(); Guid keptMediaContributorId = Guid.NewGuid();
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId); BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId);
@@ -348,7 +348,7 @@ public class BookRepositoryTests
Guid userId = Guid.NewGuid(); Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
Guid keptMediaContributorId = Guid.NewGuid(); Guid keptMediaContributorId = Guid.NewGuid();
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId); BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId);
@@ -380,7 +380,7 @@ public class BookRepositoryTests
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); 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}")]; 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(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
string keptTagName = $"remove-book-tag-{Guid.NewGuid():N}"; string keptTagName = $"remove-book-tag-{Guid.NewGuid():N}";
string keptGenreName = $"remove-book-genre-{Guid.NewGuid():N}"; string keptGenreName = $"remove-book-genre-{Guid.NewGuid():N}";
@@ -483,7 +483,7 @@ public class BookRepositoryTests
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options); using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated(); context.Database.EnsureCreated();
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid();
BookEntity bookOfLibrary = _bookEntityFixture.Create(); 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
context.Books.Add(_bookEntityFixture.Create(includeMetadata: false)); context.Books.Add(_bookEntityFixture.Create(includeMetadata: false));
await context.SaveChangesAsync(); 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity firstBook = _bookEntityFixture.Create(includeMetadata: false); BookEntity firstBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity secondBook = _bookEntityFixture.Create(includeMetadata: false); BookEntity secondBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity thirdBook = _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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: "HiddenTag")]; 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-include-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
book.Tags = [_tagEntityFixture.Create(name: "LoadedTag"), _tagEntityFixture.Create(name: "SecondLoadedTag")]; 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-boundary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 500; const int BOOK_COUNT = 500;
List<BookEntity> books = CreateBooks(BOOK_COUNT); List<BookEntity> books = CreateBooks(BOOK_COUNT);
context.Books.AddRange(books); 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 501; const int BOOK_COUNT = 501;
List<BookEntity> books = CreateBooks(BOOK_COUNT); List<BookEntity> books = CreateBooks(BOOK_COUNT);
context.Books.AddRange(books); 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-min-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity firstAuthor = _mediaContributorEntityFixture.Create(displayName: "Zoe Author"); MediaContributorEntity firstAuthor = _mediaContributorEntityFixture.Create(displayName: "Zoe Author");
MediaContributorEntity secondAuthor = _mediaContributorEntityFixture.Create(displayName: "Alice 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-requested-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity requestedBook = _bookEntityFixture.Create(includeMetadata: false); BookEntity requestedBook = _bookEntityFixture.Create(includeMetadata: false);
BookEntity bookNotRequested = _bookEntityFixture.Create(includeMetadata: false); BookEntity bookNotRequested = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity requestedAuthor = _mediaContributorEntityFixture.Create(displayName: "Requested Author"); 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
BookEntity book = _bookEntityFixture.Create(includeMetadata: false); BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
MediaContributorEntity author = _mediaContributorEntityFixture.Create(); MediaContributorEntity author = _mediaContributorEntityFixture.Create();
context.Books.Add(book); 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"); using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open(); anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection); using LuminaDbContext context = CreateContext(anchorConnection);
BookRepository sut = new(context); BookRepository sut = new(context, Substitute.For<IDateTimeProvider>());
const int BOOK_COUNT = 501; const int BOOK_COUNT = 501;
List<BookEntity> books = CreateBooks(BOOK_COUNT); List<BookEntity> books = CreateBooks(BOOK_COUNT);
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Shared Author"); MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Shared Author");
@@ -348,6 +348,30 @@ public class FavoriteRepositoryTests
Assert.Equal((Guid?)expectedLibraryId, result.Value); 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<Guid?> 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] [Fact]
public async Task GetMediaItemLibraryIdAsync_WhenTheMediaItemDoesNotExist_ShouldReturnSuccessWithNull() public async Task GetMediaItemLibraryIdAsync_WhenTheMediaItemDoesNotExist_ShouldReturnSuccessWithNull()
{ {
@@ -853,6 +877,38 @@ public class FavoriteRepositoryTests
Assert.Null(item.Display); 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<PaginatedResultDto<FavoriteItemDto>> 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] [Theory]
[InlineData(FavoriteMediaKind.Video)] // planned kind, so no display data can be resolved yet [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 [InlineData(FavoriteMediaKind.Photo)] // planned kind, so no display data can be resolved yet
@@ -47,7 +47,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act // Act
await sut.BeginTransactionAsync(CancellationToken.None); await sut.BeginTransactionAsync(CancellationToken.None);
@@ -67,7 +67,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); RoleEntity role = _roleEntityFixture.Create(roleName: "Admin");
// Act // Act
@@ -95,7 +95,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act // Act
await sut.CommitTransactionAsync(CancellationToken.None); await sut.CommitTransactionAsync(CancellationToken.None);
@@ -115,7 +115,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); RoleEntity role = _roleEntityFixture.Create(roleName: "Admin");
// Act // Act
@@ -142,7 +142,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act // Act
await sut.RollbackTransactionAsync(CancellationToken.None); await sut.RollbackTransactionAsync(CancellationToken.None);
@@ -162,7 +162,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act // Act
await sut.BeginTransactionAsync(CancellationToken.None); await sut.BeginTransactionAsync(CancellationToken.None);
@@ -183,7 +183,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act // Act
sut.Dispose(); sut.Dispose();
@@ -203,7 +203,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
Guid libraryId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid();
BookEntity firstBook = _bookEntityFixture.Create(); BookEntity firstBook = _bookEntityFixture.Create();
firstBook.LibraryId = libraryId; firstBook.LibraryId = libraryId;
@@ -237,7 +237,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
// Act // Act
IFavoriteRepository firstRepository = sut.FavoriteRepository; IFavoriteRepository firstRepository = sut.FavoriteRepository;
@@ -259,7 +259,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
Guid userId = Guid.NewGuid(); Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId)); dbContext.Users.Add(_userEntityFixture.Create(id: userId));
Result<Success> userSaveResult = await sut.SaveChangesAsync(CancellationToken.None); Result<Success> userSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
@@ -303,7 +303,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
Guid userId = Guid.NewGuid(); Guid userId = Guid.NewGuid();
UserEntity user = _userEntityFixture.Create(id: userId); UserEntity user = _userEntityFixture.Create(id: userId);
FavoriteEntity favorite = _favoriteEntityFixture.Create( FavoriteEntity favorite = _favoriteEntityFixture.Create(
@@ -337,7 +337,7 @@ public class UnitOfWorkTests
{ {
using (dbContext) using (dbContext)
{ {
UnitOfWork sut = new(dbContext); UnitOfWork sut = new(dbContext, Substitute.For<IDateTimeProvider>());
dbContext.Users.Add(_userEntityFixture.Create(id: userId)); dbContext.Users.Add(_userEntityFixture.Create(id: userId));
Guid mediaItemId = Guid.NewGuid(); Guid mediaItemId = Guid.NewGuid();
// The fixture populates the update audit columns, so the test also proves the interceptor owns them on insert. // The fixture populates the update audit columns, so the test also proves the interceptor owns them on insert.
@@ -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.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; 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.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -21,6 +22,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -64,7 +66,7 @@ public class DeleteBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
} }
[Fact] [Fact]
public async Task DeleteBook_WhenBookBelongsToAnOwnedLibrary_ShouldDeleteTheBook() public async Task DeleteBook_WhenBookBelongsToAnOwnedLibrary_ShouldSoftDeleteTheBook()
{ {
// Arrange // Arrange
Guid userId = GetCurrentUserId(); Guid userId = GetCurrentUserId();
@@ -78,11 +80,13 @@ public class DeleteBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope(); using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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] [Fact]
public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldRemoveTheArtworkAndTheStoredCoverFile() public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldKeepTheArtworkAndTheStoredCoverFileForRestore()
{ {
// Arrange // Arrange
Guid userId = GetCurrentUserId(); Guid userId = GetCurrentUserId();
@@ -98,9 +102,45 @@ public class DeleteBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope(); using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId)); BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId);
Assert.Null(await dbContext.Books.SelectMany(book => book.Artwork).FirstOrDefaultAsync(artwork => artwork.BookId == bookId)); Assert.NotNull(book);
Assert.False(File.Exists(fullCoverPath)); 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<BookResponse>? books = await booksResponse.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
Assert.NotNull(books);
Assert.Equal(0, books!.Count);
Assert.Empty(books.Data);
PaginatedResponse<BookLiteResponse>? booksLite = await booksLiteResponse.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_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] [Fact]
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetDeletedBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedBooksEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<DeletedBookResponse[]>(_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);
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a book in the provided library.
/// </summary>
/// <param name="libraryId">The Id of the library that owns the book.</param>
/// <param name="isDeleted">Whether the book is soft deleted.</param>
/// <param name="title">The title of the book.</param>
/// <returns>The seeded book.</returns>
private async Task<BookEntity> SeedBookAsync(Guid libraryId, bool isDeleted, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<LuminaDbContext>();
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);
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/> and a book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="isDeleted">Whether the seeded book is soft deleted.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, bool isDeleted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -66,6 +66,27 @@ public class GetThemeTemplateEndpointTests : IClassFixture<AuthenticatedLuminaAp
Assert.False(string.IsNullOrWhiteSpace(result.Template)); Assert.False(string.IsNullOrWhiteSpace(result.Template));
} }
[Theory]
[InlineData("lumina-default")]
[InlineData("editorial-paper")]
public async Task GetThemeTemplate_WhenCalledForTheDeletedItemsPage_ShouldReturnTheBundledTemplate(string themeId)
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync($"/api/v1/themes/{themeId}/templates/library/written-content-library/book-library/books/deleted-items");
// Assert
response.EnsureSuccessStatusCode();
ThemeTemplateResponse? result = await response.Content.ReadFromJsonAsync<ThemeTemplateResponse>(_jsonOptions);
Assert.NotNull(result);
Assert.Equal(themeId, result!.Theme.ThemeId);
Assert.Contains("btn-back-to-library", result.Template);
Assert.Contains("restoreUrlTemplate", result.Template);
}
[Fact] [Fact]
public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnNotFound() public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnNotFound()
{ {
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more