Refactors the update book slice across the stack

This commit is contained in:
BinaryAlley committed 2026-09-12 12:13:18 -07:00
1 parent 9a71a6d32b
commit 001146eefc
27 files changed
+4065 -632

No files matched your search

@@ -1,6 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaContributors;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
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 System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -11,40 +24,66 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.B
public static class UpdateBookCommandMapping
{
/// <summary>
/// Converts <paramref name="command"/> to <see cref="BookMetadataDto"/>, so that the edited data can be applied to the domain book.
/// Converts <paramref name="command"/> to <see cref="Book"/>, preserving the identity and creation metadata of the stored book identified by <paramref name="existingBook"/>.
/// </summary>
/// <param name="command">The command containing the edited data of the book.</param>
/// <returns>The built metadata.</returns>
public static BookMetadataDto ToBookMetadataDto(this UpdateBookCommand command)
/// <param name="command">The command to be converted.</param>
/// <param name="existingBook">The stored book whose identity, file system path and creation metadata are preserved.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="Book"/>, or an error message.
/// </returns>
public static Result<Book> ToDomainEntity(this UpdateBookCommand command, BookEntity existingBook)
{
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
IEnumerable<Result<BookRating>> domainRatingsResult = command.Ratings!.ToDomainEntities();
List<Error> errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors) ?? []];
if (errors.Count > 0)
return errors;
IEnumerable<Result<Isbn>> domainIsbnsResult = command.ISBNs!.ToDomainEntities();
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors) ?? []];
if (errors.Count > 0)
return errors;
Result<WrittenContentMetadata> metadataResult = command.Metadata!.ToDomainEntity();
if (metadataResult.IsFailure)
return metadataResult.Errors;
// TODO: update Api.Books.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.
}
// Map the media contributors referenced by the user to their domain counterparts; a contributor is identified by its id and carries the role it played.
IEnumerable<Result<BookMediaContributor>> domainContributorsResult = command.Contributors!.ToBookDomainEntities();
errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors) ?? []];
if (errors.Count > 0)
return errors;
return Book.Create(
BookId.Create(existingBook.Id),
LibraryId.Create(existingBook.LibraryId),
existingBook.Path,
metadataResult.Value,
Optional<BookFormat>.FromNullable(command.Format),
Optional<string>.FromNullable(command.Edition),
Optional<float>.FromNullable(command.VolumeNumber),
Optional<BookSeries>.FromNullable(bookSeries),
Optional<string>.FromNullable(command.ASIN),
Optional<string>.FromNullable(command.GoodreadsId),
Optional<string>.FromNullable(command.LCCN),
Optional<string>.FromNullable(command.OCLCNumber),
Optional<string>.FromNullable(command.OpenLibraryId),
Optional<string>.FromNullable(command.LibraryThingId),
Optional<string>.FromNullable(command.GoogleBooksId),
Optional<string>.FromNullable(command.BarnesAndNobleId),
Optional<string>.FromNullable(command.AppleBooksId),
existingBook.CreatedOnUtc,
Optional<DateTime>.FromNullable(existingBook.UpdatedOnUtc),
[.. domainIsbnsResult.Select(isbn => isbn.Value)],
[.. domainContributorsResult.Select(domainContributor => domainContributor.Value)],
[.. domainRatingsResult.Select(domainRating => domainRating.Value)]
);
}
}
@@ -15,11 +15,14 @@ public static class UpdateBookRequestMapping
/// Converts <paramref name="request"/> to <see cref="UpdateBookCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="libraryId">The Id of the library the book belongs to, taken from the route.</param>
/// <param name="bookId">The Id of the book to update, taken from the route.</param>
/// <returns>The converted command.</returns>
public static UpdateBookCommand ToCommand(this UpdateBookRequest request)
public static UpdateBookCommand ToCommand(this UpdateBookRequest request, string? libraryId, string? bookId)
{
return new UpdateBookCommand(
Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty,
libraryId,
bookId,
request.Metadata,
request.Format,
request.Edition,
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
@@ -14,7 +14,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Command for updating an existing book.
/// </summary>
/// <param name="Id">The Id of the book to update.</param>
/// <param name="LibraryId">The unique identifier of the media library this book belongs to, taken from the route.</param>
/// <param name="BookId">The unique identifier of the book to update, taken from the route.</param>
/// <param name="Metadata">Written content metadata of the book.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback), if applicable.</param>
/// <param name="Edition">The edition of the book, if applicable.</param>
@@ -34,7 +35,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <param name="Ratings">The list of ratings for this book.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateBookCommand(
Guid Id,
string? LibraryId,
string? BookId,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
@@ -50,6 +52,6 @@ public record UpdateBookCommand(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
) : ICommand;
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -8,12 +8,9 @@ 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;
@@ -70,74 +67,44 @@ public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Resul
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the route identifiers are non-empty Guids before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid bookId = Guid.Parse(command.BookId!);
// Get the existing book with all its related data.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
if (getBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
BookEntity existingBook = getBookResult.Value;
// Resource scoping: the book must belong to the library named by the route, so that a book can never be edited through another
// library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
if (existingBook.LibraryId != libraryId)
return DomainErrors.WrittenContent.BookNotFound;
// Admins can update the books of all libraries; for everyone else, only the books of the libraries they own.
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// Convert the book to a domain object and apply the edited metadata to it.
Result<Book> getDomainBookResult = existingBook.ToDomainEntity();
if (getDomainBookResult.IsFailure)
return getDomainBookResult.Errors;
Book book = getDomainBookResult.Value;
// Media contributors are referenced by Id and are never created implicitly by editing a book, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
Result<Success> 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<BookContributorEntity> 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<string, MediaContributorEntity> contributorsByDisplayName = [];
foreach (MediaContributorDto contributor in command.Contributors!)
{
if (contributor.Name?.DisplayName is null)
continue;
if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity))
{
Result<MediaContributorEntity> 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))]);
// Convert the command to a domain aggregate to enforce invariants, preserving the identity and creation metadata of the stored book.
Result<Book> updateBookResult = command.ToDomainEntity(existingBook);
if (updateBookResult.IsFailure)
return updateBookResult.Errors;
// 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;
BookEntity updatedBook = updateBookResult.Value.ToRepositoryEntity();
// 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;
// The enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that the repository
// replaces the stored data with; without this, the stored artwork would be cleared.
updatedBook.MetadataStatus = existingBook.MetadataStatus;
updatedBook.LastMetadataUpdateUtc = existingBook.LastMetadataUpdateUtc;
updatedBook.MetadataProvider = existingBook.MetadataProvider;
@@ -147,8 +114,40 @@ public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Resul
if (updateResult.IsFailure)
return updateResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return updatedBook.ToResponse() with { Contributors = command.Contributors };
// Returns the book as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save.
Result<BookEntity?> getPersistedBookResult = await _unitOfWork.BookRepository.GetByIdAsync(existingBook.Id, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedBookResult.IsFailure)
return getPersistedBookResult.Errors;
if (getPersistedBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
return getPersistedBookResult.Value.ToResponse();
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(UpdateBookCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. command.Contributors!.Select(contributor => contributor.ContributorId).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return DomainErrors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
}
@@ -18,18 +18,34 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
/// </summary>
public UpdateBookCommandValidator()
{
RuleFor(command => command.Id)
// Validates the identifier of the media library the book belongs to, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the identifier of the book to update, taken from the route.
RuleFor(command => command.BookId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
RuleFor(command => command.BookId)
.Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
.When(command => command.BookId is not null && command.BookId.Length > 0)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
// Validates the metadata of the book: title, lengths, release information, languages, genres and tags.
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
@@ -125,7 +141,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
@@ -144,7 +160,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
@@ -171,6 +187,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero);
});
// Validates the physical characteristics of the book: format, edition and volume number.
RuleFor(command => command.Format)
.IsInEnum()
.When(command => command.Format is not null)
@@ -186,6 +203,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.When(command => command.VolumeNumber.HasValue)
.WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero);
// Validates the series the book is part of, when the request carries one.
RuleFor(command => command.Series)
.ChildRules(series =>
series.RuleFor(s => s!.Title)
@@ -195,6 +213,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong))
.When(command => command.Series is not null);
// Validates the external identifiers of the book.
RuleFor(command => command.ASIN)
.Length(10)
.When(command => command.ASIN is not null)
@@ -246,6 +265,7 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.When(command => command.AppleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat);
// Validates the ISBN list of the book.
RuleFor(command => command.ISBNs)
.NotNull()
.WithError(Errors.WrittenContent.IsbnListCannotBeNull);
@@ -272,48 +292,26 @@ public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
.WithError(Errors.WrittenContent.UnknownIsbnFormat);
});
// Validates the media contributors that contributed to the book.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
.WithError(Errors.WrittenContent.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.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
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);
});
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the ratings of the book.
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -12,7 +12,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// <summary>
/// Represents a request to update an existing book.
/// </summary>
/// <param name="Id">The Id of the book to update, taken from the route. Required.</param>
/// <param name="Metadata">Written content metadata of the book. Required.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback). Optional.</param>
/// <param name="Edition">The edition of the book. Optional.</param>
@@ -28,11 +27,10 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// <param name="BarnesAndNobleId">The Barnes & Noble Id of the book. Optional.</param>
/// <param name="AppleBooksId">The Apple Books Id of the book. Optional.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book. Required.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book. Required.</param>
/// <param name="Contributors">The list of media contributors of the book. Required.</param>
/// <param name="Ratings">The list of ratings for this book. Required.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record UpdateBookRequest(
string? Id,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
@@ -48,6 +46,6 @@ public record UpdateBookRequest(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
);
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
/// <summary>
/// API endpoint for the <c>/books/{id}</c> route.
/// API endpoint for the <c>/{libraryId}/books/{bookId}</c> route.
/// </summary>
public class UpdateBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
{
@@ -48,12 +48,10 @@ public class UpdateBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<BookResponse> result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
// take unique identifiers from the route
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString();
Result<BookResponse> result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -30,7 +30,6 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
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.");
@@ -57,8 +56,8 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
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.Series, "The series the book is part of. Book series are not yet supported and are ignored. Optional.");
RequestParam(r => r.Series!.Title, "The title of the book series. Book series are not yet supported and are ignored. 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.");
@@ -73,7 +72,6 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
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",
@@ -139,25 +137,13 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
],
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 MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Author
),
new MediaContributorDto(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: MediaContributorRoleCategory.Illustrator
)
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Illustrator
)
],
Ratings:
@@ -206,8 +192,8 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
ResponseParam<BookResponse>(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
ResponseParam<BookResponse>(r => r.Edition, "The edition of the book, if applicable.");
ResponseParam<BookResponse>(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
ResponseParam<BookResponse>(r => r.Series, "The series the book is part of, if applicable.");
ResponseParam<BookResponse>(r => r.Series!.Title, "The title of the series the book is part of.");
ResponseParam<BookResponse>(r => r.Series, "The series the book is part of. Book series are not yet supported and this is always null.");
ResponseParam<BookResponse>(r => r.Series!.Title, "The title of the series the book is part of. Book series are not yet supported and this is always null.");
ResponseParam<BookResponse>(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
ResponseParam<BookResponse>(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
@@ -218,7 +204,7 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
ResponseParam<BookResponse>(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
ResponseParam<BookResponse>(r => r.Contributors, "The list of media contributors starring in this book.");
ResponseParam<BookResponse>(r => r.Contributors, "The list of references to the media contributors that contributed to this book, each with the role they played.");
ResponseParam<BookResponse>(r => r.Ratings, "The list of ratings for the book.");
ResponseParam<BookResponse>(r => r.MetadataStatus, "The status of the metadata enrichment of the book.");
ResponseParam<BookResponse>(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable.");
@@ -297,25 +283,13 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
],
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 MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Author
),
new MediaContributorDto(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: MediaContributorRoleCategory.Illustrator
)
new MediaContributorReferenceDto(
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Illustrator
)
],
Ratings:
@@ -343,13 +317,32 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
);
Response(401, "Authentication required.", "application/problem+json",
example: new
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}"
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token has expired",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
}
}
);
@@ -360,20 +353,32 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/books/{id}",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
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
Response(404, "The request failed because the book, its media library, or one of the referenced media contributors 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"
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "BookNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "MediaContributorNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
}
);
@@ -384,12 +389,13 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books/{id}",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty",
"BookIdCannotBeEmpty",
"MetadataCannotBeNull",
"TitleCannotBeEmpty",
@@ -399,7 +405,6 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
"ReleaseInfoCannotBeNull",
"OriginalReleaseYearMustBeBetween1And9999",
"ReReleaseYearMustBeBetween1And9999",
"CountryCodeMustBe2CharactersLong",
"ReleaseVersionMustBeMaximum50CharactersLong",
"OriginalReleaseDateAndYearMustMatch",
"ReReleaseDateAndYearMustMatch",
@@ -438,14 +443,8 @@ public class UpdateBookEndpointSummary : Summary<UpdateBookEndpoint, UpdateBookR
"InvalidIsbn10Format",
"UnknownIsbnFormat",
"ContributorsListCannotBeNull",
"ContributorNameCannotBeEmpty",
"ContributorDisplayNameCannotBeEmpty",
"ContributorDisplayNameMustBeMaximum100CharactersLong",
"ContributorLegalNameMustBeMaximum100CharactersLong",
"ContributorRoleCannotBeNull",
"RoleNameCannotBeEmpty",
"RoleNameMustBeMaximum50CharactersLong",
"RoleCategoryCannotBeEmpty",
"MediaContributorIdCannotBeEmpty",
"UnknownMediaContributorRole",
"RatingsListCannotBeNull",
"RatingValueMustBePositive",
"RatingValueCannotBeGreaterThanMaxValue",
@@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.DTO.MediaContributors;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
@@ -18,7 +19,12 @@ public class UpdateBookRequest
/// <summary>
/// Gets or sets the Id of the book to update, taken from the route.
/// </summary>
public string? Id { get; set; }
public string? BookId { get; set; }
/// <summary>
/// Gets or sets the Id of the media library the book belongs to.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the written content metadata of the book.
@@ -96,7 +102,7 @@ public class UpdateBookRequest
public List<IsbnDto>? ISBNs { get; set; }
/// <summary>
/// Gets or sets the list of media contributors of the book.
/// Gets or sets the list of media contributors of the book. Required.
/// </summary>
public List<MediaContributorDto>? Contributors { get; set; }
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
/// <summary>
/// API endpoint for the <c>/{culture}/library/written-content-library/books-library/books/{id}/api-save-book</c> route.
/// API endpoint for the <c>/{culture}/library/written-content-library/books-library/books/{bookId}/api-save-book</c> route.
/// </summary>
public class SaveBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
{
@@ -50,14 +50,14 @@ public class SaveBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken)
{
// The book is identified by the {id} route value, not by the id posted in the form, so that a mismatched id can never redirect
// The book is identified by the {bookId} route value, not by the id posted in the form, so that a mismatched id can never redirect
// the update to another book; the value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted
// route value can never escape its URL segment, and an unparseable id is reported by the API as a missing book id.
string routeId = HttpContext.Request.RouteValues["id"]?.ToString() ?? string.Empty;
request.Id = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString();
string routeId = HttpContext.Request.RouteValues["bookId"]?.ToString() ?? string.Empty;
request.BookId = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString();
BookDetailsDto book = await _apiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(
ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", request.Id), request, cancellationToken).ConfigureAwait(false);
ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess(book);
}
}
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.MediaContributors;
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Web.Common.Enums.Common;
using System;
@@ -28,7 +29,8 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
Summary = "Updates a book.";
Description = "Updates the details of the book identified by the request.";
RequestParam(r => r.Id, "The unique identifier of the book to update. Required.");
RequestParam(r => r.BookId, "The unique identifier of the book to update. Required.");
RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. 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.");
@@ -72,7 +74,8 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
ExampleRequest = new UpdateBookRequest
{
Id = Guid.NewGuid().ToString(),
BookId = Guid.NewGuid().ToString(),
LibraryId = Guid.NewGuid(),
Metadata = new WrittenContentMetadataDto
{
Title = "The Fellowship of the Ring",
@@ -140,12 +143,12 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
new MediaContributorDto
{
Name = new MediaContributorNameDto { DisplayName = "J.R.R. Tolkien", LegalName = "John Ronald Reuel Tolkien" },
Role = new MediaContributorRoleDto { Name = "author", Category = "Author" }
Role = MediaContributorRole.Author
},
new MediaContributorDto
{
Name = new MediaContributorNameDto { DisplayName = "Alan Lee", LegalName = "Alan Lee" },
Role = new MediaContributorRoleDto { Name = "illustrator", Category = "Illustrator" }
Role = MediaContributorRole.Illustrator
}
],
Ratings =