diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs
new file mode 100644
index 00000000..5a6445bc
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
+using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+
+///
+/// Extension methods for converting .
+///
+public static class GetBookRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted query.
+ public static GetBookQuery ToQuery(this GetBookRequest request)
+ {
+ return new GetBookQuery(
+ Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs
new file mode 100644
index 00000000..82de4c1c
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCommandMapping.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+
+///
+/// Extension methods for converting .
+///
+public static class UpdateBookCommandMapping
+{
+ ///
+ /// Converts to , so that the edited data can be applied to the domain book.
+ ///
+ /// The command containing the edited data of the book.
+ /// The built metadata.
+ public static BookMetadataDto ToBookMetadataDto(this UpdateBookCommand command)
+ {
+ return new BookMetadataDto(
+ Title: command.Metadata!.Title,
+ OriginalTitle: command.Metadata.OriginalTitle,
+ Description: command.Metadata.Description,
+ ReleaseInfo: command.Metadata.ReleaseInfo,
+ Genres: command.Metadata.Genres,
+ Tags: command.Metadata.Tags,
+ Language: command.Metadata.Language,
+ OriginalLanguage: command.Metadata.OriginalLanguage,
+ Publisher: command.Metadata.Publisher,
+ PageCount: command.Metadata.PageCount,
+ Format: command.Format,
+ Edition: command.Edition,
+ VolumeNumber: command.VolumeNumber,
+ Series: command.Series,
+ ASIN: command.ASIN,
+ GoodreadsId: command.GoodreadsId,
+ LCCN: command.LCCN,
+ OCLCNumber: command.OCLCNumber,
+ OpenLibraryId: command.OpenLibraryId,
+ LibraryThingId: command.LibraryThingId,
+ GoogleBooksId: command.GoogleBooksId,
+ BarnesAndNobleId: command.BarnesAndNobleId,
+ AppleBooksId: command.AppleBooksId,
+ Isbns: command.ISBNs,
+ Contributors: command.Contributors,
+ Ratings: command.Ratings,
+ CoverImagePath: null
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs
new file mode 100644
index 00000000..6720e145
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs
@@ -0,0 +1,42 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
+using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+
+///
+/// Extension methods for converting .
+///
+public static class UpdateBookRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted command.
+ public static UpdateBookCommand ToCommand(this UpdateBookRequest request)
+ {
+ return new UpdateBookCommand(
+ Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty,
+ request.Metadata,
+ request.Format,
+ request.Edition,
+ request.VolumeNumber,
+ request.Series,
+ request.ASIN,
+ request.GoodreadsId,
+ request.LCCN,
+ request.OCLCNumber,
+ request.OpenLibraryId,
+ request.LibraryThingId,
+ request.GoogleBooksId,
+ request.BarnesAndNobleId,
+ request.AppleBooksId,
+ request.ISBNs,
+ request.Contributors,
+ request.Ratings
+ );
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs
index 8db5934c..8da5d195 100644
--- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/IBookArtworkService.cs
@@ -2,6 +2,7 @@
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.Common.Primitives;
using System;
+using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -26,6 +27,20 @@ public interface IBookArtworkService
/// An containing either the relative path of the stored artwork, or an error.
Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken);
+ ///
+ /// Stores the artwork uploaded in the of the book into the internal media directory, and returns the relative path of the stored artwork.
+ ///
+ /// The Id of the media library the book belongs to.
+ /// The Id of the book.
+ /// The name of the media library the book belongs to.
+ /// The name of the author of the book.
+ /// The title of the book.
+ /// The stream of the uploaded artwork file.
+ /// The name of the uploaded artwork file.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the relative path of the stored artwork, or an error.
+ Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, Stream artworkStream, string fileName, CancellationToken cancellationToken);
+
///
/// Deletes the artwork of the book from the internal media directory.
///
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs
index ea190340..fa7e7e5c 100644
--- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs
@@ -1,26 +1,30 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
-using Lumina.Application.Common.DataAccess.Repositories.Books;
-using Lumina.Application.Common.DataAccess.UoW;
-using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
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.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
-
+using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using Lumina.Contracts.DTO.MediaContributors;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
@@ -31,16 +35,22 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
public class AddBookCommandHandler : ICommandHandler>
{
private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
///
/// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
/// Injected validator for application validation rules.
- public AddBookCommandHandler(IUnitOfWork unitOfWork, IValidator validator)
+ public AddBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator)
{
_unitOfWork = unitOfWork;
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
_validator = validator;
}
@@ -58,24 +68,31 @@ public class AddBookCommandHandler : ICommandHandler 0)
return validationResult;
- // TODO: update Api.Book.md documentation when the functionality is fully implemented
- List contributorIds = [];
- foreach (MediaContributorDto mediaContributor in command.Contributors!)
- {
- // TODO: add logic to search the media contributors repository for existing contributors, based on the provided names
- }
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Admins can add books to all libraries; for everyone else, only to the libraries they own.
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // TODO: update Api.Book.md documentation when the functionality is fully implemented.
BookSeries? bookSeries = null;
if (command.Series != null)
{
- // TODO: add logic to search the book series repository for existing book series, based on the provided title
- // TODO: uncomment integration and unit tests about series
+ // TODO: add logic to search the book series repository for existing book series, based on the provided title.
+ // TODO: uncomment integration and unit tests about series.
}
List> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create(
rating.Value ?? default,
rating.MaxValue ?? default,
Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null),
Optional.FromNullable(rating.VoteCount)));
- // check if any of the results contain errors
+ // Check if any of the results contain errors.
List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)];
if (errors.Count != 0) // if there are errors, return them
return errors;
@@ -147,6 +164,28 @@ public class AddBookCommandHandler : ICommandHandler contributorIds = [];
+ Dictionary contributorsByDisplayName = [];
+ foreach (MediaContributorDto contributor in command.Contributors!)
+ {
+ if (contributor.Name?.DisplayName is null)
+ continue;
+
+ if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity))
+ {
+ Result findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false);
+ if (findOrCreateResult.IsFailure)
+ return findOrCreateResult.Errors;
+ contributorEntity = findOrCreateResult.Value;
+ contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity);
+ }
+
+ contributorIds.Add(MediaContributorId.Create(contributorEntity.Id));
+ }
+
Result createBookResult = Book.Create(
LibraryId.Create(command.LibraryId),
command.Path,
@@ -171,12 +210,27 @@ public class AddBookCommandHandler : ICommandHandler contributor.Name?.DisplayName is not null)
+ .Select(contributor => new BookContributorEntity
+ {
+ Id = Guid.NewGuid(),
+ BookId = persistenceBook.Id,
+ MediaContributorId = contributorsByDisplayName[contributor.Name!.DisplayName!].Id,
+ RoleName = contributor.Role?.Name ?? "Contributor",
+ RoleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other,
+ CreatedOnUtc = DateTime.UtcNow,
+ CreatedBy = userId,
+ UpdatedBy = null
+ })];
Result insertBookResult = await _unitOfWork.BookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsFailure)
return insertBookResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
- return persistenceBook.ToResponse();
+ return persistenceBook.ToResponse() with { Contributors = command.Contributors };
}
}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs
index bcad4b8a..498de529 100644
--- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs
@@ -104,15 +104,7 @@ public class AddBookCommandValidator : AbstractValidator
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
- .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
-
- releaseInfo.RuleFor(r => r!.ReReleaseYear)
- .Must((releaseInfoInstance, reReleaseYear) =>
- !releaseInfoInstance!.ReReleaseDate.HasValue ||
- !releaseInfoInstance.ReReleaseYear.HasValue ||
- reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
- .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
- .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
+ .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
});
metadata.RuleFor(m => m!.Genres)
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs
new file mode 100644
index 00000000..f9650855
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs
@@ -0,0 +1,55 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
+
+///
+/// Command for updating an existing book.
+///
+/// The Id of the book to update.
+/// Written content metadata of the book.
+/// The format of the book (e.g., Hardcover, Paperback), if applicable.
+/// The edition of the book, if applicable.
+/// The volume or book number in the series, if applicable.
+/// The series name, if the book is part of a series.
+/// The ASIN (Amazon Standard Identification Number) of the book, if applicable.
+/// The Goodreads ID of the book, if applicable.
+/// The Library of Congress Control Number (LCCN) of the book, if applicable.
+/// The OCLC Number (WorldCat identifier) of the book, if applicable.
+/// The Open Library ID of the book, if applicable.
+/// The LibraryThing ID of the book, if applicable.
+/// The Google Books ID of the book, if applicable.
+/// The Barnes & Noble ID of the book, if applicable.
+/// The Apple Books ID of the book, if applicable.
+/// The list of ISBN (International Standard Book Number) of the book.
+/// The list of media contributors (actors, directors, etc) starring in this book.
+/// The list of ratings for this book.
+[DebuggerDisplay("Title: {Metadata.Title}")]
+public record UpdateBookCommand(
+ Guid Id,
+ WrittenContentMetadataDto? Metadata,
+ BookFormat? Format,
+ string? Edition,
+ float? VolumeNumber,
+ BookSeriesDto? Series,
+ string? ASIN,
+ string? GoodreadsId,
+ string? LCCN,
+ string? OCLCNumber,
+ string? OpenLibraryId,
+ string? LibraryThingId,
+ string? GoogleBooksId,
+ string? BarnesAndNobleId,
+ string? AppleBooksId,
+ List? ISBNs,
+ List? Contributors,
+ List? Ratings
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs
new file mode 100644
index 00000000..c844a210
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs
@@ -0,0 +1,154 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
+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.DTO.MediaContributors;
+using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+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.UpdateBook;
+
+///
+/// Handler for the command to update an existing book.
+///
+public class UpdateBookCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected validator for application validation rules.
+ public UpdateBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to update an existing book.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the updated , or an error message.
+ ///
+ public async Task> HandleAsync(UpdateBookCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Get the existing book with all its related data.
+ Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
+ if (getBookResult.IsFailure)
+ return getBookResult.Errors;
+ if (getBookResult.Value is null)
+ return DomainErrors.WrittenContent.BookNotFound;
+ BookEntity existingBook = getBookResult.Value;
+
+ // Admins can update the books of all libraries; for everyone else, only the books of the libraries they own.
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // Convert the book to a domain object and apply the edited metadata to it.
+ Result getDomainBookResult = existingBook.ToDomainEntity();
+ if (getDomainBookResult.IsFailure)
+ return getDomainBookResult.Errors;
+ Book book = getDomainBookResult.Value;
+
+ Result applyMetadataResult = book.ApplyMetadata(command.ToBookMetadataDto());
+ if (applyMetadataResult.IsFailure)
+ return applyMetadataResult.Errors;
+
+ // Link the media contributors typed by the user to the book, finding or creating a single contributor per person.
+ List linkedContributors = [];
+ // A person can be credited under several roles in the same book; each distinct display name must resolve to the same media
+ // contributor row, otherwise the duplicate inserts would violate the unique display name constraint when the changes are saved.
+ Dictionary contributorsByDisplayName = [];
+ foreach (MediaContributorDto contributor in command.Contributors!)
+ {
+ if (contributor.Name?.DisplayName is null)
+ continue;
+
+ if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity))
+ {
+ Result findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false);
+ if (findOrCreateResult.IsFailure)
+ return findOrCreateResult.Errors;
+ contributorEntity = findOrCreateResult.Value;
+ contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity);
+ }
+
+ string roleName = contributor.Role?.Name ?? "Contributor";
+ MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other;
+ linkedContributors.Add(new BookContributorEntity
+ {
+ Id = Guid.NewGuid(),
+ BookId = existingBook.Id,
+ MediaContributorId = contributorEntity.Id,
+ RoleName = roleName,
+ RoleCategory = roleCategory,
+ CreatedOnUtc = DateTime.UtcNow,
+ CreatedBy = userId,
+ UpdatedBy = null
+ });
+ }
+ book.UpdateContributors([.. linkedContributors.Select(linkedContributor => MediaContributorId.Create(linkedContributor.MediaContributorId))]);
+
+ // Map the updated domain book onto a fresh repository entity, ready for the repository to replace the stored data.
+ BookEntity updatedBook = book.ToRepositoryEntity();
+ updatedBook.BookContributors = linkedContributors;
+ updatedBook.UpdatedOnUtc = DateTime.UtcNow;
+ updatedBook.UpdatedBy = userId;
+
+ // The identity, enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that
+ // backs the response; without this, the response would report the fresh entity defaults (Pending metadata status, no cover path).
+ updatedBook.CreatedOnUtc = existingBook.CreatedOnUtc;
+ updatedBook.MetadataStatus = existingBook.MetadataStatus;
+ updatedBook.LastMetadataUpdateUtc = existingBook.LastMetadataUpdateUtc;
+ updatedBook.MetadataProvider = existingBook.MetadataProvider;
+ updatedBook.BookArtwork = existingBook.BookArtwork;
+
+ Result updateResult = await _unitOfWork.BookRepository.UpdateAsync(updatedBook, cancellationToken).ConfigureAwait(false);
+ if (updateResult.IsFailure)
+ return updateResult.Errors;
+
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ return updatedBook.ToResponse() with { Contributors = command.Contributors };
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs
new file mode 100644
index 00000000..1d57e744
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs
@@ -0,0 +1,345 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
+
+///
+/// Validates the needed validation rules for .
+///
+public class UpdateBookCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateBookCommandValidator()
+ {
+ RuleFor(command => command.Id)
+ .NotEmpty()
+ .WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
+
+ RuleFor(command => command.Metadata)
+ .NotNull()
+ .WithError(Errors.Metadata.MetadataCannotBeNull)
+ .ChildRules(metadata =>
+ {
+ metadata.RuleFor(m => m!.Title)
+ .NotEmpty()
+ .WithError(Errors.Metadata.TitleCannotBeEmpty)
+ .MaximumLength(255)
+ .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
+
+ metadata.RuleFor(m => m!.OriginalTitle)
+ .MaximumLength(255)
+ .When(m => m!.OriginalTitle is not null)
+ .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
+
+ metadata.RuleFor(m => m!.Description)
+ .MaximumLength(2000)
+ .When(m => m!.Description is not null)
+ .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
+
+ metadata.RuleFor(m => m!.ReleaseInfo)
+ .NotNull()
+ .WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
+ .ChildRules(releaseInfo =>
+ {
+ releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
+ .InclusiveBetween(1, 9999)
+ .When(r => r!.OriginalReleaseYear.HasValue)
+ .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
+
+ releaseInfo.RuleFor(r => r!.ReReleaseYear)
+ .InclusiveBetween(1, 9999)
+ .When(r => r!.ReReleaseYear.HasValue)
+ .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
+
+ releaseInfo.RuleFor(r => r!.ReleaseCountry)
+ .Matches("^[A-Za-z]{2}$")
+ .When(r => r!.ReleaseCountry is not null)
+ .WithError(Errors.Metadata.CountryCodeMustBe2CharactersLong);
+
+ releaseInfo.RuleFor(r => r!.ReleaseVersion)
+ .MaximumLength(50)
+ .When(r => r!.ReleaseVersion is not null)
+ .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
+
+ releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
+ .Must((releaseInfoInstance, originalReleaseYear) =>
+ !releaseInfoInstance!.OriginalReleaseDate.HasValue ||
+ !releaseInfoInstance.OriginalReleaseYear.HasValue ||
+ originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
+ .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
+ .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
+
+ releaseInfo.RuleFor(r => r!.ReReleaseYear)
+ .Must((releaseInfoInstance, reReleaseYear) =>
+ !releaseInfoInstance!.ReReleaseDate.HasValue ||
+ !releaseInfoInstance.ReReleaseYear.HasValue ||
+ reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
+ .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
+ .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
+
+ releaseInfo.RuleFor(r => r!.ReReleaseYear)
+ .Must((releaseInfoInstance, reReleaseYear) =>
+ !releaseInfoInstance!.ReReleaseYear.HasValue ||
+ !releaseInfoInstance.OriginalReleaseYear.HasValue ||
+ reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
+ .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
+ .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
+
+ releaseInfo.RuleFor(r => r!.ReReleaseDate)
+ .Must((releaseInfoInstance, reReleaseDate) =>
+ !releaseInfoInstance!.ReReleaseDate.HasValue ||
+ !releaseInfoInstance.OriginalReleaseDate.HasValue ||
+ reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
+ .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
+ .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
+ });
+
+ metadata.RuleFor(m => m!.Genres)
+ .NotNull()
+ .WithError(Errors.Metadata.GenresListCannotBeNull);
+
+ metadata.RuleForEach(m => m!.Genres)
+ .ChildRules(genre =>
+ genre.RuleFor(g => g.Name)
+ .NotEmpty()
+ .WithError(Errors.Metadata.GenreNameCannotBeEmpty)
+ .MaximumLength(50)
+ .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
+
+ metadata.RuleFor(m => m!.Tags)
+ .NotNull()
+ .WithError(Errors.Metadata.TagsListCannotBeNull);
+
+ metadata.RuleForEach(m => m!.Tags)
+ .ChildRules(tag =>
+ tag.RuleFor(t => t.Name)
+ .NotEmpty()
+ .WithError(Errors.Metadata.TagNameCannotBeEmpty)
+ .MaximumLength(50)
+ .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
+
+ metadata.RuleFor(m => m!.Language!.LanguageCode)
+ .NotEmpty()
+ .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
+ .MaximumLength(2)
+ .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
+ .When(m => m!.Language is not null);
+
+ metadata.RuleFor(m => m!.Language!.LanguageName)
+ .NotEmpty()
+ .WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
+ .MaximumLength(50)
+ .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
+ .When(m => m!.Language is not null);
+
+ metadata.RuleFor(m => m!.Language!.NativeName)
+ .MaximumLength(50)
+ .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
+ .When(m => m!.Language is not null);
+
+ metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
+ .NotEmpty()
+ .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
+ .MaximumLength(2)
+ .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
+ .When(m => m!.OriginalLanguage is not null);
+
+ metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
+ .NotEmpty()
+ .WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
+ .MaximumLength(50)
+ .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
+ .When(m => m!.OriginalLanguage is not null);
+
+ metadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
+ .MaximumLength(50)
+ .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
+ .When(m => m!.OriginalLanguage is not null);
+
+ metadata.RuleFor(m => m!.Publisher)
+ .MaximumLength(100)
+ .When(m => m!.Publisher is not null)
+ .WithError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong);
+
+ metadata.RuleFor(m => m!.PageCount)
+ .GreaterThan(0)
+ .When(m => m!.PageCount.HasValue)
+ .WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero);
+ });
+
+ RuleFor(command => command.Format)
+ .IsInEnum()
+ .When(command => command.Format is not null)
+ .WithError(Errors.WrittenContent.UnknownBookFormat);
+
+ RuleFor(command => command.Edition)
+ .MaximumLength(50)
+ .When(command => command.Edition is not null)
+ .WithError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong);
+
+ RuleFor(command => command.VolumeNumber)
+ .GreaterThan(0)
+ .When(command => command.VolumeNumber.HasValue)
+ .WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero);
+
+ RuleFor(command => command.Series)
+ .ChildRules(series =>
+ series.RuleFor(s => s!.Title)
+ .NotEmpty()
+ .WithError(Errors.Metadata.TitleCannotBeEmpty)
+ .MaximumLength(255)
+ .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong))
+ .When(command => command.Series is not null);
+
+ RuleFor(command => command.ASIN)
+ .Length(10)
+ .When(command => command.ASIN is not null)
+ .WithError(Errors.WrittenContent.AsinMustBe10CharactersLong);
+
+ RuleFor(command => command.GoodreadsId)
+ .Matches(@"^\d+$")
+ .When(command => command.GoodreadsId is not null)
+ .WithError(Errors.WrittenContent.GoodreadsIdMustBeNumeric);
+
+ RuleFor(command => command.LCCN)
+ .Matches(@"^[a-z]{0,3}\d{8,10}$")
+ .When(command => command.LCCN is not null)
+ .WithError(Errors.WrittenContent.InvalidLccnFormat);
+
+ RuleFor(command => command.OCLCNumber)
+ .Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$")
+ .When(command => command.OCLCNumber is not null)
+ .WithError(Errors.WrittenContent.InvalidOclcFormat);
+
+ RuleFor(command => command.OpenLibraryId)
+ .Matches(@"^OL[1-9]\d*[AMW]$")
+ .When(command => command.OpenLibraryId is not null)
+ .WithError(Errors.WrittenContent.InvalidOpenLibraryId);
+
+ RuleFor(command => command.LibraryThingId)
+ .MaximumLength(50)
+ .When(command => command.LibraryThingId is not null)
+ .WithError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong);
+
+ RuleFor(command => command.GoogleBooksId)
+ .Length(12)
+ .When(command => command.GoogleBooksId is not null)
+ .WithError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong)
+ .Matches(@"^[A-Za-z0-9_-]{12}$")
+ .When(command => command.GoogleBooksId is not null)
+ .WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat);
+
+ RuleFor(command => command.BarnesAndNobleId)
+ .Length(10)
+ .When(command => command.BarnesAndNobleId is not null)
+ .WithError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong)
+ .Matches(@"^\d{10}$")
+ .When(command => command.BarnesAndNobleId is not null)
+ .WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat);
+
+ RuleFor(command => command.AppleBooksId)
+ .Matches(@"^id\d+$")
+ .When(command => command.AppleBooksId is not null)
+ .WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat);
+
+ RuleFor(command => command.ISBNs)
+ .NotNull()
+ .WithError(Errors.WrittenContent.IsbnListCannotBeNull);
+
+ RuleForEach(command => command.ISBNs)
+ .ChildRules(isbn =>
+ {
+ isbn.RuleFor(i => i.Value)
+ .NotEmpty()
+ .WithError(Errors.WrittenContent.IsbnValueCannotBeEmpty);
+
+ isbn.RuleFor(i => i.Value)
+ .Matches(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$")
+ .When(i => i.Format == IsbnFormat.Isbn13)
+ .WithError(Errors.WrittenContent.InvalidIsbn13Format);
+
+ isbn.RuleFor(i => i.Value)
+ .Matches(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$")
+ .When(i => i.Format == IsbnFormat.Isbn10)
+ .WithError(Errors.WrittenContent.InvalidIsbn10Format);
+
+ isbn.RuleFor(i => i.Format)
+ .IsInEnum()
+ .WithError(Errors.WrittenContent.UnknownIsbnFormat);
+ });
+
+ RuleFor(command => command.Contributors)
+ .NotNull()
+ .WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
+
+ RuleForEach(command => command.Contributors)
+ .ChildRules(contributor =>
+ {
+ contributor.RuleFor(c => c.Name)
+ .NotNull()
+ .WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty)
+ .ChildRules(name =>
+ {
+ name.RuleFor(n => n!.DisplayName)
+ .NotNull()
+ .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
+ .NotEmpty()
+ .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
+ .MaximumLength(100)
+ .WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong);
+
+ name.RuleFor(n => n!.LegalName)
+ .MaximumLength(100)
+ .When(n => n!.LegalName is not null)
+ .WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong);
+ });
+
+ contributor.RuleFor(c => c.Role)
+ .NotNull()
+ .WithError(Errors.MediaContributor.ContributorRoleCannotBeNull)
+ .ChildRules(role =>
+ {
+ role.RuleFor(r => r!.Name)
+ .NotEmpty()
+ .WithError(Errors.MediaContributor.RoleNameCannotBeEmpty)
+ .MaximumLength(50)
+ .WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
+ role.RuleFor(r => r!.Category)
+ .NotEmpty()
+ .WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
+ });
+ });
+
+ RuleFor(command => command.Ratings)
+ .NotNull()
+ .WithError(Errors.Metadata.RatingsListCannotBeNull);
+
+ RuleForEach(command => command.Ratings)
+ .ChildRules(rating =>
+ {
+ rating.RuleFor(r => r.Value)
+ .GreaterThan(0)
+ .WithError(Errors.Metadata.RatingValueMustBePositive)
+ .Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
+ .WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
+
+ rating.RuleFor(r => r.MaxValue)
+ .GreaterThan(0)
+ .WithError(Errors.Metadata.RatingMaxValueMustBePositive);
+
+ rating.RuleFor(r => r.VoteCount)
+ .GreaterThanOrEqualTo(0)
+ .When(r => r.VoteCount.HasValue)
+ .WithError(Errors.Metadata.RatingVoteCountMustBePositive);
+ });
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs
new file mode 100644
index 00000000..9921e03d
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs
@@ -0,0 +1,21 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+using System.Diagnostics;
+using System.IO;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
+
+///
+/// Command for updating the cover image of an existing book.
+///
+/// The Id of the book whose cover image is updated.
+/// The stream of the uploaded cover image file.
+/// The name of the uploaded cover image file.
+[DebuggerDisplay("BookId: {BookId} FileName: {FileName}")]
+public record UpdateBookCoverCommand(
+ Guid BookId,
+ Stream? Cover,
+ string? FileName
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs
new file mode 100644
index 00000000..df4d26db
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs
@@ -0,0 +1,161 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
+
+///
+/// Handler for the command to update the cover image of an existing book.
+///
+public class UpdateBookCoverCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IBookArtworkService _bookArtworkService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service for storing the artwork of a book.
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected validator for application validation rules.
+ public UpdateBookCoverCommandHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _bookArtworkService = bookArtworkService;
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to update the cover image of an existing book.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the relative path of the stored cover image, or an error message.
+ ///
+ public async Task> HandleAsync(UpdateBookCoverCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Get the existing book with its artwork.
+ Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.BookId, cancellationToken).ConfigureAwait(false);
+ if (getBookResult.IsFailure)
+ return getBookResult.Errors;
+ if (getBookResult.Value is null)
+ return DomainErrors.WrittenContent.BookNotFound;
+ BookEntity existingBook = getBookResult.Value;
+
+ // Admins can update the books of all libraries; for everyone else, only the books of the libraries they own.
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // The artwork is stored under the library and author segments, so their names are resolved to keep the location consistent with the scanned artwork.
+ Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure)
+ return getLibraryResult.Errors;
+ if (getLibraryResult.Value is null)
+ return DomainErrors.Library.LibraryNotFound;
+ string libraryName = getLibraryResult.Value.Title;
+ string authorName = await GetAuthorNameAsync(existingBook, cancellationToken).ConfigureAwait(false);
+
+ Result storeArtworkResult = await _bookArtworkService.SaveBookArtworkAsync(
+ existingBook.LibraryId,
+ existingBook.Id,
+ libraryName,
+ authorName,
+ existingBook.Title,
+ command.Cover!,
+ command.FileName!,
+ cancellationToken).ConfigureAwait(false);
+ if (storeArtworkResult.IsFailure)
+ return storeArtworkResult.Errors;
+
+ // Update the stored cover artwork of the book with the newly stored image.
+ BookArtworkEntity? coverArtwork = existingBook.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover);
+ if (coverArtwork is null)
+ {
+ existingBook.BookArtwork.Add(new BookArtworkEntity
+ {
+ Id = Guid.NewGuid(),
+ BookId = existingBook.Id,
+ ArtworkType = ArtworkType.Cover,
+ Ordinal = 0,
+ FileName = storeArtworkResult.Value,
+ Status = ArtworkStatus.Enriched,
+ CreatedOnUtc = DateTime.UtcNow,
+ CreatedBy = userId,
+ UpdatedBy = null
+ });
+ }
+ else
+ {
+ coverArtwork.FileName = storeArtworkResult.Value;
+ coverArtwork.Status = ArtworkStatus.Enriched;
+ coverArtwork.LastUpdateUtc = DateTime.UtcNow;
+ coverArtwork.UpdatedOnUtc = DateTime.UtcNow;
+ coverArtwork.UpdatedBy = userId;
+ }
+
+ await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+
+ return storeArtworkResult.Value;
+ }
+
+ ///
+ /// Gets the display name of the author of the , used to build the artwork storage path, or an empty string when the book has no author.
+ ///
+ /// The book whose author is retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// The display name of the author of the book, or an empty string.
+ private async Task GetAuthorNameAsync(BookEntity book, CancellationToken cancellationToken)
+ {
+ IReadOnlyCollection authorIds = [.. book.BookContributors
+ .Where(participation => participation.RoleCategory == MediaContributorRoleCategory.Author)
+ .Select(participation => participation.MediaContributorId)
+ .Distinct()];
+ if (authorIds.Count == 0)
+ return string.Empty;
+
+ Result> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(authorIds, cancellationToken).ConfigureAwait(false);
+ if (getContributorsResult.IsFailure)
+ return string.Empty;
+ return getContributorsResult.Value.Select(contributor => contributor.DisplayName).FirstOrDefault() ?? string.Empty;
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs
new file mode 100644
index 00000000..3333a4e4
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs
@@ -0,0 +1,30 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
+
+///
+/// Validates the needed validation rules for .
+///
+public class UpdateBookCoverCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateBookCoverCommandValidator()
+ {
+ RuleFor(command => command.BookId)
+ .NotEmpty()
+ .WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
+
+ RuleFor(command => command.Cover)
+ .NotNull()
+ .WithError(Errors.WrittenContent.BookCoverCannotBeNull);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs
new file mode 100644
index 00000000..e4ed13d0
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
+
+///
+/// Query for getting a book by its Id.
+///
+/// The Id of the book to get.
+public record GetBookQuery(
+ Guid Id
+) : IQuery;
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs
new file mode 100644
index 00000000..683bd388
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs
@@ -0,0 +1,122 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
+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.DTO.MediaContributors;
+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;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
+
+///
+/// Handler for the query to get a book by its Id.
+///
+public class GetBookQueryHandler : IQueryHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected validator for application validation rules.
+ public GetBookQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the query to get a book by its Id.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the requested , or an error message.
+ ///
+ public async Task> HandleAsync(GetBookQuery query, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(query);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // Get the book with the specified id from the repository.
+ Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
+ if (getBookResult.IsFailure)
+ return getBookResult.Errors;
+ if (getBookResult.Value is null)
+ return DomainErrors.WrittenContent.BookNotFound;
+
+ // Admins can see the books of all libraries; for everyone else, only the books of the libraries they own.
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(getBookResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ BookResponse response = getBookResult.Value.ToResponse();
+
+ // The response carries the resolved contributor names, so that the clients can display them without querying the contributors themselves.
+ List contributors = await GetContributorsAsync(getBookResult.Value, cancellationToken).ConfigureAwait(false);
+ if (contributors.Count == 0)
+ return response;
+
+ Dictionary contributorsById = contributors.ToDictionary(contributor => contributor.Id);
+ List contributorResponses = [];
+ foreach (BookContributorEntity participation in getBookResult.Value.BookContributors)
+ {
+ if (!contributorsById.TryGetValue(participation.MediaContributorId, out MediaContributorEntity? contributor))
+ continue;
+ contributorResponses.Add(new MediaContributorDto(
+ new MediaContributorNameDto(contributor.DisplayName, contributor.LegalName),
+ new MediaContributorRoleDto(participation.RoleName, participation.RoleCategory)
+ ));
+ }
+
+ return response with { Contributors = contributorResponses };
+ }
+
+ ///
+ /// Gets the media contributors linked to the book of , by their unique identifiers.
+ ///
+ /// The book whose media contributors are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the media contributors of the book, or an error.
+ private async Task> GetContributorsAsync(BookEntity book, CancellationToken cancellationToken)
+ {
+ IReadOnlyCollection contributorIds = [.. book.BookContributors.Select(participation => participation.MediaContributorId).Distinct()];
+ if (contributorIds.Count == 0)
+ return [];
+
+ Result> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
+ if (getContributorsResult.IsFailure)
+ return [];
+ return [.. getContributorsResult.Value];
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs
new file mode 100644
index 00000000..43ba1eaa
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs
@@ -0,0 +1,26 @@
+#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.GetBook;
+
+///
+/// Validates the needed validation rules for .
+///
+public class GetBookQueryValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetBookQueryValidator()
+ {
+ RuleFor(query => query.Id)
+ .NotEmpty()
+ .WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty)
+ .WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs
new file mode 100644
index 00000000..192ed038
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs
@@ -0,0 +1,53 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using System.Collections.Generic;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+
+///
+/// Represents a request to update an existing book.
+///
+/// The Id of the book to update, taken from the route. Required.
+/// Written content metadata of the book. Required.
+/// The format of the book (e.g., Hardcover, Paperback). Optional.
+/// The edition of the book. Optional.
+/// The volume or book number in the series. Optional.
+/// The series name, if the book is part of a series. Optional.
+/// The ASIN (Amazon Standard Identification Number) of the book. Optional.
+/// The Goodreads Id of the book. Optional.
+/// The Library of Congress Control Number (LCCN) of the book. Optional.
+/// The OCLC Number (WorldCat identifier) of the book. Optional.
+/// The Open Library Id of the book. Optional.
+/// The LibraryThing Id of the book. Optional.
+/// The Google Books Id of the book. Optional.
+/// The Barnes & Noble Id of the book. Optional.
+/// The Apple Books Id of the book. Optional.
+/// The list of ISBN (International Standard Book Number) of the book. Required.
+/// The list of media contributors (actors, directors, etc) starring in this book. Required.
+/// The list of ratings for this book. Required.
+[DebuggerDisplay("Title: {Metadata.Title}")]
+public record UpdateBookRequest(
+ string? Id,
+ WrittenContentMetadataDto? Metadata,
+ BookFormat? Format,
+ string? Edition,
+ float? VolumeNumber,
+ BookSeriesDto? Series,
+ string? ASIN,
+ string? GoodreadsId,
+ string? LCCN,
+ string? OCLCNumber,
+ string? OpenLibraryId,
+ string? LibraryThingId,
+ string? GoogleBooksId,
+ string? BarnesAndNobleId,
+ string? AppleBooksId,
+ List? ISBNs,
+ List? Contributors,
+ List? Ratings
+);
diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs
index 054a10f7..ecda2029 100644
--- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs
+++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs
@@ -58,7 +58,7 @@ internal sealed class BookRepository : IBookRepository
if (bookExists)
return Errors.WrittenContent.BookAlreadyExists;
- // fetch existing tags and genres
+ // Fetch existing tags and genres.
List existingTags = await _luminaDbContext.Set()
.Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
@@ -67,7 +67,7 @@ internal sealed class BookRepository : IBookRepository
.Where(g => book.Genres.Select(bg => bg.Name).Contains(g.Name))
.ToListAsync(cancellationToken).ConfigureAwait(false);
- // replace tags and genres in the book with existing ones
+ // Replace tags and genres in the book with existing ones.
book.Tags = [.. book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)];
book.Genres = [.. book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)];
@@ -87,6 +87,8 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
+ .Include(book => book.Ratings)
+ .Include(book => book.BookContributors)
.Include(book => book.BookArtwork)
.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false);
}
@@ -102,6 +104,8 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
+ .Include(book => book.Ratings)
+ .Include(book => book.BookContributors)
.Include(book => book.BookArtwork)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
@@ -126,21 +130,21 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.BookArtwork)
.AsNoTracking();
- // books should always be retrieved only per owning libraries
+ // Books should always be retrieved only per owning libraries.
if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty)
return Errors.Library.FilterMustIncludeLibraryId;
booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId);
FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter);
- // apply filtering
+ // Apply filtering.
if (filterSpecification is not null)
booksQuery = booksQuery.Where(filterSpecification.ToExpression());
- // apply sorting based on the specified sortBy and sortOrder parameters
+ // Apply sorting based on the specified sortBy and sortOrder parameters.
booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
- // if no pagination was requested, return all the books of the library
+ // If no pagination was requested, return all the books of the library.
if (paginationData is null)
{
IReadOnlyList allBooks = await booksQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
@@ -156,9 +160,9 @@ internal sealed class BookRepository : IBookRepository
int count = await booksQuery.Select(book => book.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
- int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // make sure current page doesn't exceed maximum number of pages
+ int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
- // apply pagination
+ // Apply pagination.
IReadOnlyList paginatedResult = await booksQuery
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
@@ -359,7 +363,7 @@ internal sealed class BookRepository : IBookRepository
return authorRows
.GroupBy(row => row.BookId)
- .ToDictionary(group => group.Key, group => (string?)group.Min(row => row.DisplayName));
+ .ToDictionary(group => group.Key, group => group.Min(row => row.DisplayName));
}
///
@@ -387,9 +391,9 @@ internal sealed class BookRepository : IBookRepository
}
///
- /// Updates a book.
+ /// Updates a book, replacing its editable data while preserving its identity, enrichment and audit columns.
///
- /// The book to update.
+ /// The book whose editable data is applied to the stored book.
/// Cancellation token that can be used to stop the execution.
/// An representing either a successful operation, or an error.
public async Task> UpdateAsync(BookEntity data, CancellationToken cancellationToken)
@@ -398,11 +402,52 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
+ .Include(book => book.Ratings)
+ .Include(book => book.BookContributors)
.FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundBook is null)
return Errors.WrittenContent.BookNotFound;
- // update the scalar properties of the book
+
+ // The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself.
+ Guid libraryId = foundBook.LibraryId;
+ string path = foundBook.Path;
+ MetadataStatus metadataStatus = foundBook.MetadataStatus;
+ DateTime? lastMetadataUpdateUtc = foundBook.LastMetadataUpdateUtc;
+ string? metadataProvider = foundBook.MetadataProvider;
+ DateTime createdOnUtc = foundBook.CreatedOnUtc;
+ Guid createdBy = foundBook.CreatedBy;
+
+ // Copy the editable scalar properties of the book, ignoring the unchanged collection and enrichment columns.
_luminaDbContext.Entry(foundBook).CurrentValues.SetValues(data);
+ foundBook.LibraryId = libraryId;
+ foundBook.Path = path;
+ foundBook.MetadataStatus = metadataStatus;
+ foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc;
+ foundBook.MetadataProvider = metadataProvider;
+ foundBook.CreatedOnUtc = createdOnUtc;
+ foundBook.CreatedBy = createdBy;
+
+ // Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated.
+ List existingTags = await _luminaDbContext.Set()
+ .Where(tag => data.Tags.Select(bookTag => bookTag.Name).Contains(tag.Name))
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ List existingGenres = await _luminaDbContext.Set()
+ .Where(genre => data.Genres.Select(bookGenre => bookGenre.Name).Contains(genre.Name))
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+
+ foundBook.Tags.Clear();
+ foundBook.Tags.UnionWith(data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag));
+ foundBook.Genres.Clear();
+ foundBook.Genres.UnionWith(data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre));
+
+ // Replace the owned collections of the book, so that removed entries are deleted and new entries are inserted.
+ foundBook.ISBNs.Clear();
+ foundBook.ISBNs.AddRange(data.ISBNs);
+ foundBook.Ratings.Clear();
+ foundBook.Ratings.AddRange(data.Ratings);
+ foundBook.BookContributors.Clear();
+ foundBook.BookContributors.AddRange(data.BookContributors);
+
return Result.Updated;
}
@@ -445,7 +490,7 @@ internal sealed class BookRepository : IBookRepository
Expression titleProperty = Expression.Property(book, nameof(BookEntity.Title));
- // the raw title: the title, unless it is null or empty, in which case the original title (or an empty string) is used
+ // The raw title: the title, unless it is null or empty, in which case the original title (or an empty string) is used.
BinaryExpression isTitleMissing = Expression.OrElse(
Expression.Equal(titleProperty, Expression.Constant(null, typeof(string))),
Expression.Equal(titleProperty, Expression.Constant(string.Empty)));
@@ -455,7 +500,7 @@ internal sealed class BookRepository : IBookRepository
MethodCallExpression lowerTitle = Expression.Call(rawTitle, s_toLowerMethod);
- // when ignoring the "The " prefix, strip a leading "the " from the lowercased title
+ // When ignoring the "The " prefix, strip a leading "the " from the lowercased title.
Expression effectiveTitle = lowerTitle;
if (shouldIgnoreThePrefixForAlphaPicker)
{
@@ -476,11 +521,11 @@ internal sealed class BookRepository : IBookRepository
{
FilterSpecification? filterSpecification = null;
- // include the search term filter, if provided
+ // Include the search term filter, if provided.
if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm))
filterSpecification = new BookSearchSpecification(libraryFilter.SearchTerm);
- // include the alpha key filter, if provided
+ // Include the alpha key filter, if provided.
if (libraryFilter.FilterAlphaKey is not null)
{
BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
diff --git a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs
index ac637464..a31b8da5 100644
--- a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs
+++ b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs
@@ -37,6 +37,8 @@ public static partial class Errors
public static Error VolumeNumberMustBeGreaterThanZero => Error.Validation(description: nameof(VolumeNumberMustBeGreaterThanZero));
public static Error BookLibraryCannotBeNull => Error.Validation(description: nameof(BookLibraryCannotBeNull));
public static Error BookPathCannotBeEmpty => Error.Validation(description: nameof(BookPathCannotBeEmpty));
+ public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty));
+ public static Error BookCoverCannotBeNull => Error.Validation(description: nameof(BookCoverCannotBeNull));
public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound));
}
}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs
index 84eb7e05..452e3667 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs
@@ -247,9 +247,7 @@ internal class FileProviderService : IFileProviderService
Result newFilePathResult = FileSystemPathId.Create(newFile);
if (newFilePathResult.IsFailure)
return newFilePathResult.Errors;
- // check if the user has access permissions to the provided path
- if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute))
- return Errors.Permission.UnauthorizedAccess;
+ // renaming a file only requires write access to its parent directory, never execute access to the file itself
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write))
return Errors.Permission.UnauthorizedAccess;
_fileSystem.File.Move(path.Path, newFilePathResult.Value.Path);
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs
index 8ce2aca8..efd252b3 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs
@@ -60,7 +60,7 @@ internal sealed class BookArtworkService : IBookArtworkService
/// An containing either the relative path of the stored artwork, or an error.
public async Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken)
{
- // resolve the local file path of the artwork, downloading it to a temporary file when it is remote
+ // Resolve the local file path of the artwork, downloading it to a temporary file when it is remote.
Result resolveSourceResult = await ResolveArtworkSourceAsync(artwork, cancellationToken).ConfigureAwait(false);
if (resolveSourceResult.IsFailure)
return resolveSourceResult.Errors;
@@ -75,7 +75,7 @@ internal sealed class BookArtworkService : IBookArtworkService
}
finally
{
- // remove the temporary file downloaded for the remote artwork, never a local file of the user
+ // Remove the temporary file downloaded for the remote artwork, never a local file of the user.
if (resolveSourceResult.Value.IsTemporary && File.Exists(sourcePath))
{
try
@@ -84,11 +84,79 @@ internal sealed class BookArtworkService : IBookArtworkService
}
catch (IOException)
{
- // a failed cleanup of the temporary file must not mask the result of the operation
+ // A failed cleanup of the temporary file must not mask the result of the operation.
}
catch (UnauthorizedAccessException)
{
- // a failed cleanup of the temporary file must not mask the result of the operation
+ // A failed cleanup of the temporary file must not mask the result of the operation.
+ }
+ }
+ }
+ }
+
+ ///
+ /// Stores the artwork uploaded in the of the book into the internal media directory, and returns the relative path of the stored artwork.
+ ///
+ /// The Id of the media library the book belongs to.
+ /// The Id of the book.
+ /// The name of the media library the book belongs to.
+ /// The name of the author of the book.
+ /// The title of the book.
+ /// The stream of the uploaded artwork file.
+ /// The name of the uploaded artwork file.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the relative path of the stored artwork, or an error.
+ public async Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, Stream artworkStream, string fileName, CancellationToken cancellationToken)
+ {
+ if (artworkStream is null || artworkStream.Length == 0)
+ return Errors.FileSystemManagement.FileNotFound;
+ if (artworkStream.Length > MAX_ARTWORK_SIZE_BYTES)
+ return Errors.FileSystemManagement.FileTooLarge;
+
+ // Copy the uploaded artwork into a temporary file, so that the shared artwork storage can validate and copy it.
+ string temporaryPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}{Path.GetExtension(fileName)}");
+ bool written = false;
+ try
+ {
+ await using (FileStream fileStream = new(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true))
+ await artworkStream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
+ written = true;
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception)
+ {
+ return Errors.FileSystemManagement.FileNotFound;
+ }
+ finally
+ {
+ // Remove the partially written temporary file when the upload failed.
+ if (!written && File.Exists(temporaryPath))
+ File.Delete(temporaryPath);
+ }
+
+ try
+ {
+ return await StoreArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, temporaryPath, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ // Remove the temporary file after the artwork has been stored.
+ if (File.Exists(temporaryPath))
+ {
+ try
+ {
+ File.Delete(temporaryPath);
+ }
+ catch (IOException)
+ {
+ // A failed cleanup of the temporary file must not mask the result of the operation.
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // A failed cleanup of the temporary file must not mask the result of the operation.
}
}
}
@@ -135,16 +203,16 @@ internal sealed class BookArtworkService : IBookArtworkService
if (!fileExistsResult.Value)
return Errors.FileSystemManagement.FileNotFound;
- // reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine
+ // Reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine.
if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.ReparsePoint))
return Errors.FileSystemManagement.InvalidPath;
- // reject the artwork when it exceeds the maximum allowed size
+ // Reject the artwork when it exceeds the maximum allowed size.
FileInfo sourceFileInfo = new(sourcePath);
if (sourceFileInfo.Length > MAX_ARTWORK_SIZE_BYTES)
return Errors.FileSystemManagement.FileTooLarge;
- // make sure the file is an actual supported image
+ // Make sure the file is an actual supported image.
Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(sourcePathIdResult.Value, cancellationToken).ConfigureAwait(false);
if (imageTypeResult.IsFailure)
return imageTypeResult.Errors;
@@ -159,24 +227,24 @@ internal sealed class BookArtworkService : IBookArtworkService
if (ensureDirectoryResult.IsFailure)
return ensureDirectoryResult.Errors;
- // delete the previous cover of the book, so that a changed artwork does not leave orphaned files behind
+ // Delete the previous cover of the book, so that a changed artwork does not leave orphaned files behind.
DeleteCover(artworkDirectoryPathResult.Value);
Result artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPathResult.Value);
if (artworkDirectoryPathIdResult.IsFailure)
return artworkDirectoryPathIdResult.Errors;
- // copy the artwork file from the source location
+ // Copy the artwork file from the source location.
Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourcePathIdResult.Value, artworkDirectoryPathIdResult.Value, true);
if (copyFileResult.IsFailure)
return copyFileResult.Errors;
- // rename the copied file to the standard naming
+ // Rename the copied file to the standard naming.
Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}");
if (renameFileResult.IsFailure)
return renameFileResult.Errors;
- // get the internal relative path for the copied file
+ // Get the internal relative path for the copied file.
string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..];
if (!relativePath.StartsWith(_pathService.PathSeparator))
relativePath = $"{_pathService.PathSeparator}{relativePath}";
@@ -197,7 +265,7 @@ internal sealed class BookArtworkService : IBookArtworkService
if (string.IsNullOrWhiteSpace(artwork.RemoteUrl))
return Errors.FileSystemManagement.FileNotFound;
- // download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size
+ // Download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size.
using HttpClient httpClient = _httpClientFactory.CreateClient();
string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}");
bool downloaded = false;
@@ -233,7 +301,7 @@ internal sealed class BookArtworkService : IBookArtworkService
}
finally
{
- // remove the partially downloaded temporary file when the download failed
+ // Remove the partially downloaded temporary file when the download failed.
if (!downloaded && File.Exists(tempPath))
File.Delete(tempPath);
}
diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs
index 9ff7ea86..49959c37 100644
--- a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs
+++ b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs
@@ -14,6 +14,8 @@ public static partial class ApiRoutes
public const string GET_BOOKS = "/books";
public const string GET_BOOKS_LITE = "/books/lite";
public const string ADD_BOOK = "/books";
+ public const string UPDATE_BOOK = "/books/{id}";
+ public const string UPDATE_BOOK_COVER = "/books/{id}/cover";
public const string GET_BOOK_READING_MANIFEST = "/books/{bookId}/reading/manifest";
public const string GET_BOOK_READING_AVAILABILITY = "/books/{bookId}/reading/availability";
public const string GET_BOOK_READING_SECTION = "/books/{bookId}/reading/sections/{locationRef}";
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs
index 9417c0fc..39350e75 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointSummary.cs
@@ -88,7 +88,7 @@ public class GetThumbnailEndpointSummary : Summary API endpoint, for OpenAPI.
///
[ExcludeFromCodeCoverage]
-public class AddLibraryEndpointSummary : Summary
+public class AddBookEndpointSummary : Summary
{
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
- public AddLibraryEndpointSummary()
+ public AddBookEndpointSummary()
{
Summary = "Adds a new book.";
Description = "Creates a new book and returns its details, including the location of the newly created resource.";
@@ -130,6 +130,8 @@ public class AddLibraryEndpointSummary : Summary r.LibraryId, "The Id of the media library this book belongs to. Required.");
+ RequestParam(r => r.Path, "The file system path of the book. Required.");
RequestParam(r => r.Metadata, "Written content metadata of the book. Required.");
RequestParam(r => r.Metadata!.Title, "The title of the written content. Required.");
RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the written content, if different from the current title. Optional.");
@@ -171,13 +173,55 @@ public class AddLibraryEndpointSummary : Summary r.Contributors, "The list of media contributors (actors, directors, etc) starring in this book. Required.");
RequestParam(r => r.Ratings, "The list of ratings for this book. Required.");
- ResponseParam(r => r.Id, "The unique identifier of the entity.");
- ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created.");
- ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated.");
+ ResponseParam(r => r.Id, "The unique identifier of the book.");
+ ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to.");
+ ResponseParam(r => r.Path, "The file system path of the book.");
ResponseParam(r => r.Metadata, "The written content metadata of the book.");
- ResponseParam(r => r.Metadata.Title, "The title of the media item.");
- ResponseParam(r => r.Metadata.OriginalTitle, "The original title of the media item.");
- // TODO: continue response params
+ ResponseParam(r => r.Metadata!.Title, "The title of the book.");
+ ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title.");
+ ResponseParam(r => r.Metadata!.Description, "A brief description or summary of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo, "The release information of the book, including its release date and other relevant details.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book.");
+ ResponseParam(r => r.Metadata!.Genres, "The list of genres of the book.");
+ ResponseParam(r => r.Metadata!.Tags, "The list of tags of the book.");
+ ResponseParam(r => r.Metadata!.Language, "The language in which the book is written.");
+ ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book.");
+ ResponseParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English.");
+ ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book.");
+ ResponseParam(r => r.Metadata!.Publisher, "The publisher of the book.");
+ ResponseParam(r => r.Metadata!.PageCount, "The number of pages of the book.");
+ ResponseParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
+ ResponseParam(r => r.Edition, "The edition of the book, if applicable.");
+ ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
+ ResponseParam(r => r.Series, "The series the book is part of, if applicable.");
+ ResponseParam(r => r.Series!.Title, "The title of the series the book is part of.");
+ ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
+ ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
+ ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
+ ResponseParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable.");
+ ResponseParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable.");
+ ResponseParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable.");
+ ResponseParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable.");
+ ResponseParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
+ ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
+ ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
+ ResponseParam(r => r.Contributors, "The list of media contributors starring in this book.");
+ ResponseParam(r => r.Ratings, "The list of ratings for the book.");
+ ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book.");
+ ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable.");
+ ResponseParam(r => r.MetadataProvider, "The name of the plugin that enriched the metadata of the book, if applicable.");
+ ResponseParam(r => r.CreatedOnUtc, "The date and time when the book was created.");
+ ResponseParam(r => r.UpdatedOnUtc, "The date and time when the book was last updated, if applicable.");
+ ResponseParam(r => r.CoverPath, "The path of the cover image of the book, if available.");
Response(201, "The new book is returned.", example:
new BookResponse(
@@ -196,16 +240,18 @@ public class AddLibraryEndpointSummary : Summary() {
- { new(Name: "fantasy") },
- { new(Name: "adventure") },
- { new(Name: "classic") }
- },
- Tags: new List() {
- { new(Name: "epic fantasy") },
- { new(Name: "quest") },
- { new(Name: "middle-earth") }
- },
+ Genres:
+ [
+ new(Name: "fantasy"),
+ new(Name: "adventure"),
+ new(Name: "classic")
+ ],
+ Tags:
+ [
+ new(Name: "epic fantasy"),
+ new(Name: "quest"),
+ new(Name: "middle-earth")
+ ],
Language: new(
LanguageCode: "en",
LanguageName: "English",
@@ -321,6 +367,18 @@ public class AddLibraryEndpointSummary : Summary
public class GetBookEndpoint : BaseEndpoint
{
+ private readonly IQueryHandler> _getBookQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get book queries.
+ public GetBookEndpoint(IQueryHandler> getBookQueryHandler)
+ {
+ _getBookQueryHandler = getBookQueryHandler;
+ }
+
///
/// Configures the API endpoint.
///
@@ -22,19 +38,17 @@ public class GetBookEndpoint : BaseEndpoint
Verbs(FastEndpoints.Http.GET);
Routes(ApiRoutes.Books.GET_BOOK_BY_ID);
Version(1);
- AllowAnonymous();
DontCatchExceptions();
}
///
- /// Adds a book stored in .
+ /// Gets the book identified by .
///
- /// The request containing the book to be added.
+ /// The request containing the Id of the book to get.
/// Cancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken)
{
- //Result result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
- //return result.Match(success => TypedResults.CreatedAtRoute($"/api/v1/books/{success.Id}", success), Problem);
- return await Task.FromResult(TypedResults.Ok());
+ Result result = await _getBookQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
}
}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs
new file mode 100644
index 00000000..86965b7f
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs
@@ -0,0 +1,259 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetBookEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetBookEndpointSummary()
+ {
+ Summary = "Gets a book by its Id.";
+ Description = "Gets the full details of the book identified by the request, including the resolved names of its media contributors.";
+
+ ExampleRequest = new GetBookRequest(
+ Id: Guid.NewGuid().ToString()
+ );
+
+ RequestParam(r => r.Id, "The Id of the book to get. Required.");
+
+ ResponseParam(r => r.Id, "The Id of the book.");
+ ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to.");
+ ResponseParam(r => r.Path, "The file system path of the book.");
+ ResponseParam(r => r.Metadata, "The written content metadata of the book.");
+ ResponseParam(r => r.Metadata!.Title, "The title of the book.");
+ ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title.");
+ ResponseParam(r => r.Metadata!.Description, "A brief description or summary of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo, "The release information of the book, including its release date and other relevant details.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book.");
+ ResponseParam(r => r.Metadata!.Genres, "The list of genres of the book.");
+ ResponseParam(r => r.Metadata!.Tags, "The list of tags of the book.");
+ ResponseParam(r => r.Metadata!.Language, "The language in which the book is written.");
+ ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book.");
+ ResponseParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English.");
+ ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book.");
+ ResponseParam(r => r.Metadata!.Publisher, "The publisher of the book.");
+ ResponseParam(r => r.Metadata!.PageCount, "The number of pages of the book.");
+ ResponseParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
+ ResponseParam(r => r.Edition, "The edition of the book, if applicable.");
+ ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
+ ResponseParam(r => r.Series, "The series the book is part of, if applicable.");
+ ResponseParam(r => r.Series!.Title, "The title of the series the book is part of.");
+ ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
+ ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
+ ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
+ ResponseParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable.");
+ ResponseParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable.");
+ ResponseParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable.");
+ ResponseParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable.");
+ ResponseParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
+ ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
+ ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
+ ResponseParam(r => r.Contributors, "The list of media contributors starring in this book.");
+ ResponseParam(r => r.Ratings, "The list of ratings for the book.");
+ ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book.");
+ ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable.");
+ ResponseParam(r => r.MetadataProvider, "The name of the plugin that enriched the metadata of the book, if applicable.");
+ ResponseParam(r => r.CreatedOnUtc, "The date and time when the book was created.");
+ ResponseParam(r => r.UpdatedOnUtc, "The date and time when the book was last updated, if applicable.");
+ ResponseParam(r => r.CoverPath, "The path of the cover image of the book, if available.");
+
+ Response(200, "The requested book is returned.",
+ example: new BookResponse(
+ Id: Guid.NewGuid(),
+ LibraryId: Guid.NewGuid(),
+ Path: "/books/the-fellowship-of-the-ring.epub",
+ Metadata: new WrittenContentMetadataDto(
+ Title: "The Fellowship of the Ring",
+ OriginalTitle: "The Fellowship of the Ring",
+ Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.",
+ ReleaseInfo: new ReleaseInfoDto(
+ OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null),
+ OriginalReleaseYear: 1954,
+ ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null),
+ ReReleaseYear: 2001,
+ ReleaseCountry: "uk",
+ ReleaseVersion: "50th Anniversary Edition"
+ ),
+ Genres:
+ [
+ new(Name: "fantasy"),
+ new(Name: "adventure"),
+ new(Name: "classic")
+ ],
+ Tags:
+ [
+ new(Name: "epic fantasy"),
+ new(Name: "quest"),
+ new(Name: "middle-earth")
+ ],
+ Language: new LanguageInfoDto(
+ LanguageCode: "en",
+ LanguageName: "English",
+ NativeName: "English"
+ ),
+ OriginalLanguage: new LanguageInfoDto(
+ LanguageCode: "en",
+ LanguageName: "English",
+ NativeName: "English"
+ ),
+ Publisher: "Houghton Mifflin",
+ PageCount: 398
+ ),
+ Format: BookFormat.Paperback,
+ Edition: "50th Anniversary Edition",
+ VolumeNumber: 1,
+ Series: new BookSeriesDto(
+ Title: "The Lord of the Rings"
+ ),
+ ASIN: "B007978NPG",
+ GoodreadsId: "3",
+ LCCN: "54009621",
+ OCLCNumber: "ocm00012345",
+ OpenLibraryId: "OL7603910M",
+ LibraryThingId: "3203347",
+ GoogleBooksId: "aWZzLPhY4o0C",
+ BarnesAndNobleId: "1100307790",
+ AppleBooksId: "id395211",
+ ISBNs:
+ [
+ new IsbnDto(
+ Value: "0395272238",
+ Format: IsbnFormat.Isbn10
+ ),
+ new IsbnDto(
+ Value: "9780395272237",
+ Format: IsbnFormat.Isbn13
+ )
+ ],
+ Contributors:
+ [
+ new MediaContributorDto(
+ Name: new MediaContributorNameDto(
+ DisplayName: "J.R.R. Tolkien",
+ LegalName: "John Ronald Reuel Tolkien"
+ ),
+ Role: new MediaContributorRoleDto(
+ Name: "author",
+ Category: MediaContributorRoleCategory.Author
+ )
+ ),
+ new MediaContributorDto(
+ Name: new MediaContributorNameDto(
+ DisplayName: "Alan Lee",
+ LegalName: "Alan Lee"
+ ),
+ Role: new MediaContributorRoleDto(
+ Name: "illustrator",
+ Category: MediaContributorRoleCategory.Illustrator
+ )
+ )
+ ],
+ Ratings:
+ [
+ new BookRatingDto(
+ Source: BookRatingSource.GoogleBooks,
+ Value: 4.36M,
+ MaxValue: 5,
+ VoteCount: 2345678
+ ),
+ new BookRatingDto(
+ Source: BookRatingSource.Amazon,
+ Value: 4.7M,
+ MaxValue: 5,
+ VoteCount: 87654
+ )
+ ],
+ MetadataStatus: MetadataStatus.Enriched,
+ LastMetadataUpdateUtc: DateTime.UtcNow,
+ MetadataProvider: "GoogleBooks",
+ CreatedOnUtc: DateTime.UtcNow,
+ UpdatedOnUtc: DateTime.UtcNow,
+ CoverPath: "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg"
+ )
+ );
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "You are not authorized",
+ instance = "/api/v1/books/{id}"
+ }
+ );
+
+ 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/books/{id}",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(404, "The request failed because the book does not exist.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
+ title = "General.NotFound",
+ status = 404,
+ detail = "BookNotFound",
+ instance = "/api/v1/books/{id}",
+ 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/books/{id}",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "BookIdCannotBeEmpty"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs
index 5ef15425..14be3df3 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs
@@ -112,7 +112,8 @@ public class GetBooksLiteEndpointSummary : Summary
+/// API endpoint for the /books/{id} route.
+///
+public class UpdateBookEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _updateBookCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling update book commands.
+ public UpdateBookEndpoint(ICommandHandler> updateBookCommandHandler)
+ {
+ _updateBookCommandHandler = updateBookCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.PUT);
+ Routes(ApiRoutes.Books.UPDATE_BOOK);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Updates the book described in .
+ ///
+ /// The request containing the edited details of the book.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken)
+ {
+ // The book is identified by the {id} route value, not by the id of the request body, so that a mismatched or malicious id can never
+ // redirect the update to another book; the raw value is kept as a string, so that an unparseable id reaches the command validator,
+ // which reports it with a ProblemDetails validation error instead of failing the request binding.
+ request = request with { Id = HttpContext.Request.RouteValues["id"]?.ToString() };
+
+ Result result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs
new file mode 100644
index 00000000..392faaf0
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs
@@ -0,0 +1,460 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateBookEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateBookEndpointSummary()
+ {
+ Summary = "Updates a book.";
+ Description = "Updates the details of the book identified by the request.";
+
+ RequestParam(r => r.Id, "The Id of the book to update. Required.");
+ RequestParam(r => r.Metadata, "The written content metadata of the book. Required.");
+ RequestParam(r => r.Metadata!.Title, "The title of the book. Required.");
+ RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional.");
+ RequestParam(r => r.Metadata!.Description, "A brief description or summary of the book. Optional.");
+ RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required.");
+ RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book. Optional.");
+ RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book. Optional.");
+ RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book. Optional.");
+ RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book. Optional.");
+ RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released. Optional.");
+ RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book. Optional.");
+ RequestParam(r => r.Metadata!.Genres, "The list of genres of the book. Required.");
+ RequestParam(r => r.Metadata!.Tags, "The list of tags of the book. Required.");
+ RequestParam(r => r.Metadata!.Language, "The language in which the book is written. Optional.");
+ RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book. Optional.");
+ RequestParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English. Optional.");
+ RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book. Optional.");
+ RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated. Optional.");
+ RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book. Optional.");
+ RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English. Optional.");
+ RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book. Optional.");
+ RequestParam(r => r.Metadata!.Publisher, "The publisher of the book. Optional.");
+ RequestParam(r => r.Metadata!.PageCount, "The number of pages of the book. Optional.");
+ RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback). Optional.");
+ RequestParam(r => r.Edition, "The edition of the book. Optional.");
+ RequestParam(r => r.VolumeNumber, "The volume or book number in the series. Optional.");
+ RequestParam(r => r.Series, "The series the book is part of. Optional.");
+ RequestParam(r => r.Series!.Title, "The title of the series the book is part of. Optional.");
+ RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book. Optional.");
+ RequestParam(r => r.GoodreadsId, "The Goodreads Id of the book. Optional.");
+ RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book. Optional.");
+ RequestParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book. Optional.");
+ RequestParam(r => r.OpenLibraryId, "The Open Library Id of the book. Optional.");
+ RequestParam(r => r.LibraryThingId, "The LibraryThing Id of the book. Optional.");
+ RequestParam(r => r.GoogleBooksId, "The Google Books Id of the book. Optional.");
+ RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble Id of the book. Optional.");
+ RequestParam(r => r.AppleBooksId, "The Apple Books Id of the book. Optional.");
+ RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book. Required.");
+ RequestParam(r => r.Contributors, "The list of media contributors of the book. Required.");
+ RequestParam(r => r.Ratings, "The list of ratings of the book. Required.");
+
+ ExampleRequest = new UpdateBookRequest(
+ Id: Guid.NewGuid().ToString(),
+ Metadata: new WrittenContentMetadataDto(
+ Title: "The Fellowship of the Ring",
+ OriginalTitle: "The Fellowship of the Ring",
+ Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.",
+ ReleaseInfo: new ReleaseInfoDto(
+ OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null),
+ OriginalReleaseYear: 1954,
+ ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null),
+ ReReleaseYear: 2001,
+ ReleaseCountry: "uk",
+ ReleaseVersion: "50th Anniversary Edition"
+ ),
+ Genres:
+ [
+ new(Name: "fantasy"),
+ new(Name: "adventure"),
+ new(Name: "classic")
+ ],
+ Tags:
+ [
+ new(Name: "epic fantasy"),
+ new(Name: "quest"),
+ new(Name: "middle-earth")
+ ],
+ Language: new LanguageInfoDto(
+ LanguageCode: "en",
+ LanguageName: "English",
+ NativeName: "English"
+ ),
+ OriginalLanguage: new LanguageInfoDto(
+ LanguageCode: "en",
+ LanguageName: "English",
+ NativeName: "English"
+ ),
+ Publisher: "Houghton Mifflin",
+ PageCount: 398
+ ),
+ Format: BookFormat.Paperback,
+ Edition: "50th Anniversary Edition",
+ VolumeNumber: 1,
+ Series: new BookSeriesDto(
+ Title: "The Lord of the Rings"
+ ),
+ ASIN: "B007978NPG",
+ GoodreadsId: "3",
+ LCCN: "54009621",
+ OCLCNumber: "ocm00012345",
+ OpenLibraryId: "OL7603910M",
+ LibraryThingId: "3203347",
+ GoogleBooksId: "aWZzLPhY4o0C",
+ BarnesAndNobleId: "1100307790",
+ AppleBooksId: "id395211",
+ ISBNs:
+ [
+ new IsbnDto(
+ Value: "0395272238",
+ Format: IsbnFormat.Isbn10
+ ),
+ new IsbnDto(
+ Value: "9780395272237",
+ Format: IsbnFormat.Isbn13
+ )
+ ],
+ Contributors:
+ [
+ new MediaContributorDto(
+ Name: new MediaContributorNameDto(
+ DisplayName: "J.R.R. Tolkien",
+ LegalName: "John Ronald Reuel Tolkien"
+ ),
+ Role: new MediaContributorRoleDto(
+ Name: "author",
+ Category: MediaContributorRoleCategory.Author
+ )
+ ),
+ new MediaContributorDto(
+ Name: new MediaContributorNameDto(
+ DisplayName: "Alan Lee",
+ LegalName: "Alan Lee"
+ ),
+ Role: new MediaContributorRoleDto(
+ Name: "illustrator",
+ Category: MediaContributorRoleCategory.Illustrator
+ )
+ )
+ ],
+ Ratings:
+ [
+ new BookRatingDto(
+ Source: BookRatingSource.GoogleBooks,
+ Value: 4.36M,
+ MaxValue: 5,
+ VoteCount: 2345678
+ ),
+ new BookRatingDto(
+ Source: BookRatingSource.Amazon,
+ Value: 4.7M,
+ MaxValue: 5,
+ VoteCount: 87654
+ )
+ ]
+ );
+
+ ResponseParam(r => r.Id, "The Id of the book.");
+ ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to.");
+ ResponseParam(r => r.Path, "The file system path of the book.");
+ ResponseParam(r => r.Metadata, "The written content metadata of the book.");
+ ResponseParam(r => r.Metadata!.Title, "The title of the book.");
+ ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title.");
+ ResponseParam(r => r.Metadata!.Description, "A brief description or summary of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo, "The release information of the book, including its release date and other relevant details.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the book.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the book was released.");
+ ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the book.");
+ ResponseParam(r => r.Metadata!.Genres, "The list of genres of the book.");
+ ResponseParam(r => r.Metadata!.Tags, "The list of tags of the book.");
+ ResponseParam(r => r.Metadata!.Language, "The language in which the book is written.");
+ ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book.");
+ ResponseParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English.");
+ ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English.");
+ ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book.");
+ ResponseParam(r => r.Metadata!.Publisher, "The publisher of the book.");
+ ResponseParam(r => r.Metadata!.PageCount, "The number of pages of the book.");
+ ResponseParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
+ ResponseParam(r => r.Edition, "The edition of the book, if applicable.");
+ ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
+ ResponseParam(r => r.Series, "The series the book is part of, if applicable.");
+ ResponseParam(r => r.Series!.Title, "The title of the series the book is part of.");
+ ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
+ ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
+ ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
+ ResponseParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable.");
+ ResponseParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable.");
+ ResponseParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable.");
+ ResponseParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable.");
+ ResponseParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
+ ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
+ ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
+ ResponseParam(r => r.Contributors, "The list of media contributors starring in this book.");
+ ResponseParam(r => r.Ratings, "The list of ratings for the book.");
+ ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book.");
+ ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable.");
+ ResponseParam(r => r.MetadataProvider, "The name of the plugin that enriched the metadata of the book, if applicable.");
+ ResponseParam(r => r.CreatedOnUtc, "The date and time when the book was created.");
+ ResponseParam(r => r.UpdatedOnUtc, "The date and time when the book was last updated, if applicable.");
+ ResponseParam(r => r.CoverPath, "The path of the cover image of the book, if available.");
+
+ Response(200, "The updated book is returned.",
+ example: new BookResponse(
+ Id: Guid.NewGuid(),
+ LibraryId: Guid.NewGuid(),
+ Path: "/books/the-fellowship-of-the-ring.epub",
+ Metadata: new WrittenContentMetadataDto(
+ Title: "The Fellowship of the Ring",
+ OriginalTitle: "The Fellowship of the Ring",
+ Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.",
+ ReleaseInfo: new ReleaseInfoDto(
+ OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null),
+ OriginalReleaseYear: 1954,
+ ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null),
+ ReReleaseYear: 2001,
+ ReleaseCountry: "uk",
+ ReleaseVersion: "50th Anniversary Edition"
+ ),
+ Genres:
+ [
+ new(Name: "fantasy"),
+ new(Name: "adventure"),
+ new(Name: "classic")
+ ],
+ Tags:
+ [
+ new(Name: "epic fantasy"),
+ new(Name: "quest"),
+ new(Name: "middle-earth")
+ ],
+ Language: new LanguageInfoDto(
+ LanguageCode: "en",
+ LanguageName: "English",
+ NativeName: "English"
+ ),
+ OriginalLanguage: new LanguageInfoDto(
+ LanguageCode: "en",
+ LanguageName: "English",
+ NativeName: "English"
+ ),
+ Publisher: "Houghton Mifflin",
+ PageCount: 398
+ ),
+ Format: BookFormat.Paperback,
+ Edition: "50th Anniversary Edition",
+ VolumeNumber: 1,
+ Series: new BookSeriesDto(
+ Title: "The Lord of the Rings"
+ ),
+ ASIN: "B007978NPG",
+ GoodreadsId: "3",
+ LCCN: "54009621",
+ OCLCNumber: "ocm00012345",
+ OpenLibraryId: "OL7603910M",
+ LibraryThingId: "3203347",
+ GoogleBooksId: "aWZzLPhY4o0C",
+ BarnesAndNobleId: "1100307790",
+ AppleBooksId: "id395211",
+ ISBNs:
+ [
+ new IsbnDto(
+ Value: "0395272238",
+ Format: IsbnFormat.Isbn10
+ ),
+ new IsbnDto(
+ Value: "9780395272237",
+ Format: IsbnFormat.Isbn13
+ )
+ ],
+ Contributors:
+ [
+ new MediaContributorDto(
+ Name: new MediaContributorNameDto(
+ DisplayName: "J.R.R. Tolkien",
+ LegalName: "John Ronald Reuel Tolkien"
+ ),
+ Role: new MediaContributorRoleDto(
+ Name: "author",
+ Category: MediaContributorRoleCategory.Author
+ )
+ ),
+ new MediaContributorDto(
+ Name: new MediaContributorNameDto(
+ DisplayName: "Alan Lee",
+ LegalName: "Alan Lee"
+ ),
+ Role: new MediaContributorRoleDto(
+ Name: "illustrator",
+ Category: MediaContributorRoleCategory.Illustrator
+ )
+ )
+ ],
+ Ratings:
+ [
+ new BookRatingDto(
+ Source: BookRatingSource.GoogleBooks,
+ Value: 4.36M,
+ MaxValue: 5,
+ VoteCount: 2345678
+ ),
+ new BookRatingDto(
+ Source: BookRatingSource.Amazon,
+ Value: 4.7M,
+ MaxValue: 5,
+ VoteCount: 87654
+ )
+ ],
+ MetadataStatus: MetadataStatus.Enriched,
+ LastMetadataUpdateUtc: DateTime.UtcNow,
+ MetadataProvider: "GoogleBooks",
+ CreatedOnUtc: DateTime.UtcNow,
+ UpdatedOnUtc: DateTime.UtcNow,
+ CoverPath: "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg"
+ )
+ );
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "You are not authorized",
+ instance = "/api/v1/books/{id}"
+ }
+ );
+
+ 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/books/{id}",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(404, "The request failed because the book or its media library does not exist.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
+ title = "General.NotFound",
+ status = 404,
+ detail = "BookNotFound",
+ instance = "/api/v1/books/{id}",
+ 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/books/{id}",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "BookIdCannotBeEmpty",
+ "MetadataCannotBeNull",
+ "TitleCannotBeEmpty",
+ "TitleMustBeMaximum255CharactersLong",
+ "OriginalTitleMustBeMaximum255CharactersLong",
+ "DescriptionMustBeMaximum2000CharactersLong",
+ "ReleaseInfoCannotBeNull",
+ "OriginalReleaseYearMustBeBetween1And9999",
+ "ReReleaseYearMustBeBetween1And9999",
+ "CountryCodeMustBe2CharactersLong",
+ "ReleaseVersionMustBeMaximum50CharactersLong",
+ "OriginalReleaseDateAndYearMustMatch",
+ "ReReleaseDateAndYearMustMatch",
+ "ReReleaseYearCannotBeEarlierThanOriginalReleaseYear",
+ "ReReleaseDateCannotBeEarlierThanOriginalReleaseDate",
+ "GenresListCannotBeNull",
+ "GenreNameCannotBeEmpty",
+ "GenreNameMustBeMaximum50CharactersLong",
+ "TagsListCannotBeNull",
+ "TagNameCannotBeEmpty",
+ "TagNameMustBeMaximum50CharactersLong",
+ "LanguageCodeCannotBeEmpty",
+ "LanguageCodeMustBe2CharactersLong",
+ "LanguageNameCannotBeEmpty",
+ "LanguageNameMustBeMaximum50CharactersLong",
+ "LanguageNativeNameMustBeMaximum50CharactersLong",
+ "PublisherMustBeMaximum100CharactersLong",
+ "PageCountMustBeGreaterThanZero",
+ "UnknownBookFormat",
+ "EditionMustBeMaximum50CharactersLong",
+ "VolumeNumberMustBeGreaterThanZero",
+ "AsinMustBe10CharactersLong",
+ "GoodreadsIdMustBeNumeric",
+ "InvalidLccnFormat",
+ "InvalidOclcFormat",
+ "InvalidOpenLibraryId",
+ "LibraryThingIdMustBeMaximum50CharactersLong",
+ "GoogleBooksIdMustBe12CharactersLong",
+ "InvalidGoogleBooksIdFormat",
+ "BarnesAndNoblesIdMustBe10CharactersLong",
+ "InvalidBarnesAndNoblesIdFormat",
+ "InvalidAppleBooksIdFormat",
+ "IsbnListCannotBeNull",
+ "IsbnValueCannotBeEmpty",
+ "InvalidIsbn13Format",
+ "InvalidIsbn10Format",
+ "UnknownIsbnFormat",
+ "ContributorsListCannotBeNull",
+ "ContributorNameCannotBeEmpty",
+ "ContributorDisplayNameCannotBeEmpty",
+ "ContributorDisplayNameMustBeMaximum100CharactersLong",
+ "ContributorLegalNameMustBeMaximum100CharactersLong",
+ "ContributorRoleCannotBeNull",
+ "RoleNameCannotBeEmpty",
+ "RoleNameMustBeMaximum50CharactersLong",
+ "RoleCategoryCannotBeEmpty",
+ "RatingsListCannotBeNull",
+ "RatingValueMustBePositive",
+ "RatingValueCannotBeGreaterThanMaxValue",
+ "RatingMaxValueMustBePositive",
+ "RatingVoteCountMustBePositive"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs
new file mode 100644
index 00000000..6c6d9b08
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs
@@ -0,0 +1,81 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
+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;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
+
+///
+/// API endpoint for the /books/{id}/cover route.
+///
+public class UpdateBookCoverEndpoint : BaseEndpoint
+{
+ private readonly Application.Common.CQRS.ICommandHandler> _updateBookCoverCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling update book cover commands.
+ public UpdateBookCoverEndpoint(Application.Common.CQRS.ICommandHandler> updateBookCoverCommandHandler)
+ {
+ _updateBookCoverCommandHandler = updateBookCoverCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(Http.PUT);
+ Routes(ApiRoutes.Books.UPDATE_BOOK_COVER);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Updates the cover image of the book with the image uploaded in the multipart form of the request.
+ ///
+ /// The request object.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // The endpoint takes no typed request, because its body is a multipart file, so the book id is read from the {id} route
+ // value; an unparseable value becomes Guid.Empty, which the command validator reports as a missing book id.
+ Guid bookId = Guid.TryParse(HttpContext.Request.RouteValues["id"]?.ToString(), out Guid parsedBookId) ? parsedBookId : Guid.Empty;
+
+ IFormFile? cover = null;
+ if (HttpContext.Request.HasFormContentType)
+ {
+ try
+ {
+ // The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
+ // so a malformed upload is treated as a missing cover, which the command validator reports.
+ cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
+ }
+ catch (InvalidDataException)
+ {
+ cover = null;
+ }
+ }
+
+ // The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
+ UpdateBookCoverCommand command = new(bookId, cover?.OpenReadStream(), cover?.FileName);
+ try
+ {
+ Result result = await _updateBookCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+ finally
+ {
+ command.Cover?.Dispose();
+ }
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs
new file mode 100644
index 00000000..a7f89cfe
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
+
+///
+/// Class used for providing a textual description for the