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.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 API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCoverEndpointSummary() + { + Summary = "Updates the cover image of a book."; + Description = "Updates the cover image of the book identified by the request, with the image uploaded in the multipart form of the request."; + + Response(200, "The relative path of the stored cover image is returned.", + example: "/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}/cover" + } + ); + + 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}/cover", + 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}/cover", + 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}/cover", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "BookIdCannotBeEmpty", + "BookCoverCannotBeNull", + "FileTooLarge", + "CoverFileMustBeAnImage" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs index c3ee6d0f..667359ba 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointSummary.cs @@ -74,7 +74,7 @@ public class SetupApplicationEndpointSummary : Summary(stream, _jsonOptions, cancellationToken).ConfigureAwait(false)) { if (cancellationToken.IsCancellationRequested) @@ -110,17 +110,17 @@ public class ApiHttpClient : IApiHttpClient using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { - // read the content as a string, for error messages + // Read the content as a string, for error messages. string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); ProblemDetailsDto? problemDetails = null; try { problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } - catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } throw new ApiException(problemDetails, response.StatusCode); } - // if the response is successful, read it as a byte array + // If the response is successful, read it as a byte array. byte[] responseContent = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); string contentType = response.Content.Headers.ContentType?.ToString() ?? "application/octet-stream"; return new BlobDataDto { Data = responseContent, ContentType = contentType }; @@ -137,19 +137,18 @@ public class ApiHttpClient : IApiHttpClient AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); if (authenticationHeader is not null) request.Headers.Authorization = authenticationHeader; - //return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); - // send the HTTP request and read the response + // Send the HTTP request and read the response. HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { ProblemDetailsDto? problemDetails = null; string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // attempt to deserialize the response content to ProblemDetailsDto if the request fails + // Attempt to deserialize the response content to ProblemDetailsDto if the request fails. try { problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } - catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); } } @@ -204,7 +203,7 @@ public class ApiHttpClient : IApiHttpClient /// The deserialized response containing the result of the POST request. public async Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) { - // the file is streamed as a generic binary part, since the exact content type of the uploaded file is not known + // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. using MultipartFormDataContent form = []; using StreamContent fileContent = new(fileStream); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); @@ -220,6 +219,34 @@ public class ApiHttpClient : IApiHttpClient return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } + /// + /// Sends a PUT request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The stream of the file to upload. + /// The name of the file to upload. + /// The name of the form field carrying the file. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + public async Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) + { + // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. + using MultipartFormDataContent form = []; + using StreamContent fileContent = new(fileStream); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, fieldName, fileName); + + using HttpRequestMessage request = new(HttpMethod.Put, endpoint) + { + Content = form + }; + AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); + if (authenticationHeader is not null) + request.Headers.Authorization = authenticationHeader; + return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + } + /// /// Sends an HTTP request and deserializes the response into the specified type if the request is successful. /// If the request fails, it attempts to deserialize the response content into a and throws an . @@ -231,13 +258,13 @@ public class ApiHttpClient : IApiHttpClient /// Thrown if the response is not successful, with the if available. private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - // send the HTTP request and read the response + // Send the HTTP request and read the response. HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // if the response is successful, deserialize the content to TResponse and return it + // If the response is successful, deserialize the content to TResponse and return it. if (response.IsSuccessStatusCode) { - // handle empty content case + // Handle empty content case. if (string.IsNullOrEmpty(content)) return default!; return JsonSerializer.Deserialize(content, _jsonOptions)!; @@ -245,12 +272,12 @@ public class ApiHttpClient : IApiHttpClient else { ProblemDetailsDto? problemDetails = null; - // attempt to deserialize the response content to ProblemDetailsDto if the request fails + // Attempt to deserialize the response content to ProblemDetailsDto if the request fails. try { problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } - catch { /* if we can't deserialize to ProblemDetails, we'll just use the status code */ } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); } } diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index fa208872..ae7d9d45 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -57,6 +57,18 @@ public interface IApiHttpClient /// The deserialized response containing the result of the PUT request. Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); + /// + /// Sends a PUT request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The stream of the file to upload. + /// The name of the file to upload. + /// The name of the form field carrying the file. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the PUT request. + Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default); + /// /// Sends a POST request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. /// diff --git a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs new file mode 100644 index 00000000..087cdda6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +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 + +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Data transfer object carrying the full details of a book, as stored in the media library. +/// +[DebuggerDisplay("Title: {Metadata?.Title}")] +public class BookDetailsDto +{ + /// + /// Gets or sets the Id of the book. + /// + public Guid Id { get; set; } + + /// + /// Gets or sets the Id of the media library this book belongs to. + /// + public Guid LibraryId { get; set; } + + /// + /// Gets or sets the file system path of the book. + /// + public string Path { get; set; } = null!; + + /// + /// Gets or sets the written content metadata of the book. + /// + public WrittenContentMetadataDto? Metadata { get; set; } + + /// + /// Gets or sets the format of the book (e.g., Hardcover, Paperback), if applicable. + /// + public BookFormat? Format { get; set; } + + /// + /// Gets or sets the edition of the book, if applicable. + /// + public string? Edition { get; set; } + + /// + /// Gets or sets the volume or book number in the series, if applicable. + /// + public float? VolumeNumber { get; set; } + + /// + /// Gets or sets the ASIN (Amazon Standard Identification Number) of the book, if applicable. + /// + public string? ASIN { get; set; } + + /// + /// Gets or sets the Goodreads Id of the book, if applicable. + /// + public string? GoodreadsId { get; set; } + + /// + /// Gets or sets the Library of Congress Control Number (LCCN) of the book, if applicable. + /// + public string? LCCN { get; set; } + + /// + /// Gets or sets the OCLC Number (WorldCat identifier) of the book, if applicable. + /// + public string? OCLCNumber { get; set; } + + /// + /// Gets or sets the Open Library Id of the book, if applicable. + /// + public string? OpenLibraryId { get; set; } + + /// + /// Gets or sets the LibraryThing Id of the book, if applicable. + /// + public string? LibraryThingId { get; set; } + + /// + /// Gets or sets the Google Books Id of the book, if applicable. + /// + public string? GoogleBooksId { get; set; } + + /// + /// Gets or sets the Barnes & Noble Id of the book, if applicable. + /// + public string? BarnesAndNobleId { get; set; } + + /// + /// Gets or sets the Apple Books Id of the book, if applicable. + /// + public string? AppleBooksId { get; set; } + + /// + /// Gets or sets the list of ISBN (International Standard Book Number) of the book. + /// + public List? ISBNs { get; set; } + + /// + /// Gets or sets the list of media contributors of the book. + /// + public List? Contributors { get; set; } + + /// + /// Gets or sets the list of ratings of the book. + /// + public List? Ratings { get; set; } + + /// + /// Gets or sets the status of the metadata enrichment of the book. + /// + public string? MetadataStatus { get; set; } + + /// + /// Gets or sets the date and time when the metadata of the book was last enriched, if applicable. + /// + public DateTime? LastMetadataUpdateUtc { get; set; } + + /// + /// Gets or sets the name of the plugin that enriched the metadata of the book, if applicable. + /// + public string? MetadataProvider { get; set; } + + /// + /// Gets or sets the date and time when the book was created. + /// + public DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the optional date and time when the book was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the path of the cover image of the book, if available. + /// + public string? CoverPath { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs index d3596561..eff995d1 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using System; using System.Diagnostics; #endregion @@ -8,8 +7,8 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// /// Represents a request to get a book by the specified Id. /// -/// The unique identifier of the book to retrieve. Required. +/// The unique identifier of the book to retrieve, taken from the route. Required. [DebuggerDisplay("Id: {Id}")] public record GetBookRequest( - Guid Id + string Id ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs new file mode 100644 index 00000000..29ec1889 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +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.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents a request to update an existing book. +/// +[DebuggerDisplay("Title: {Metadata?.Title}")] +public class UpdateBookRequest +{ + /// + /// Gets or sets the Id of the book to update, taken from the route. + /// + public string? Id { get; set; } + + /// + /// Gets or sets the written content metadata of the book. + /// + public WrittenContentMetadataDto? Metadata { get; set; } + + /// + /// Gets or sets the format of the book (e.g., Hardcover, Paperback), if applicable. + /// + public BookFormat? Format { get; set; } + + /// + /// Gets or sets the edition of the book, if applicable. + /// + public string? Edition { get; set; } + + /// + /// Gets or sets the volume or book number in the series, if applicable. + /// + public float? VolumeNumber { get; set; } + + /// + /// Gets or sets the series name, if the book is part of a series. + /// + public BookSeriesDto? Series { get; set; } + + /// + /// Gets or sets the ASIN (Amazon Standard Identification Number) of the book, if applicable. + /// + public string? ASIN { get; set; } + + /// + /// Gets or sets the Goodreads Id of the book, if applicable. + /// + public string? GoodreadsId { get; set; } + + /// + /// Gets or sets the Library of Congress Control Number (LCCN) of the book, if applicable. + /// + public string? LCCN { get; set; } + + /// + /// Gets or sets the OCLC Number (WorldCat identifier) of the book, if applicable. + /// + public string? OCLCNumber { get; set; } + + /// + /// Gets or sets the Open Library Id of the book, if applicable. + /// + public string? OpenLibraryId { get; set; } + + /// + /// Gets or sets the LibraryThing Id of the book, if applicable. + /// + public string? LibraryThingId { get; set; } + + /// + /// Gets or sets the Google Books Id of the book, if applicable. + /// + public string? GoogleBooksId { get; set; } + + /// + /// Gets or sets the Barnes & Noble Id of the book, if applicable. + /// + public string? BarnesAndNobleId { get; set; } + + /// + /// Gets or sets the Apple Books Id of the book, if applicable. + /// + public string? AppleBooksId { get; set; } + + /// + /// Gets or sets the list of ISBN (International Standard Book Number) of the book. + /// + public List? ISBNs { get; set; } + + /// + /// Gets or sets the list of media contributors of the book. + /// + public List? Contributors { get; set; } + + /// + /// Gets or sets the list of ratings of the book. + /// + public List? Ratings { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs index e1363258..5956a3b3 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs @@ -11,6 +11,9 @@ public static partial class ApiRoutes public static class Books { public const string GET_BOOKS_LITE = "books/lite"; + public const string GET_BOOK = "books/{id}"; + 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.Web/Common/Routes/WebRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs index 9d52a31e..1eed9199 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs @@ -13,6 +13,9 @@ public static partial class WebRoutes public const string INDEX = "{culture}/library/written-content-library/books-library/books"; public const string GET_LIBRARY_ITEMS = "{culture}/library/written-content-library/books-library/books/api-get-library-items"; public const string EDIT_BOOK = "{culture}/library/written-content-library/books-library/books/{id}"; + public const string GET_BOOK_DETAILS = "{culture}/library/written-content-library/books-library/books/{id}/api-get-book"; + public const string SAVE_BOOK = "{culture}/library/written-content-library/books-library/books/{id}/api-save-book"; + public const string UPDATE_BOOK_COVER = "{culture}/library/written-content-library/books-library/books/{id}/api-update-cover"; public const string READ = "{culture}/library/written-content-library/books-library/books/{bookId}/read"; public const string GET_READING_MANIFEST = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest"; public const string GET_READING_AVAILABILITY = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs index a6fd1b71..dc80331c 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs @@ -1,10 +1,21 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; #endregion @@ -16,6 +27,42 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.B /// public class EditBookViewEndpoint : BaseEndpoint { + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath, + // so "Lumina.Presentation.Web.Views.X" resolves to the embedded "Lumina.Presentation.Web.Core.Resources.Views.X" resource; including "Core" here would insert it twice. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Library.WrittenContentLibrary.BookLibrary.Books.Item"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "library/written-content-library/book-library/books/item"; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly IApiHttpClient _apiHttpClient; + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public EditBookViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _apiHttpClient = apiHttpClient; + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + /// /// Configures the endpoint. /// @@ -29,12 +76,58 @@ public class EditBookViewEndpoint : BaseEndpoint } /// - /// Displays the book editing view. + /// Displays the book editing view, rendered by the active theme with a fallback to the Razor view. /// - /// The request object. + /// The request containing the Id of the book to view. /// Cancellation token that can be used to stop the execution. - public override Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) { - return Task.FromResult(View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml")); + // The view needs the full details of the book to show its current values, so they are fetched from the API up front; the route + // 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. + request = request with { Id = Guid.TryParse(request.Id, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString() }; + BookDetailsDto book = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id), cancellationToken).ConfigureAwait(false); + string title = book.Metadata?.Title ?? string.Empty; + + // The themed view is a regular page that submits its own requests, so a fresh anti-forgery token must be issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + + // The theme template receives the book data, the URLs of the actions of the view and the localized strings as page data, + // serialized as JSON so that the template can bind them without executing server side code of its own. + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["bookId"] = book.Id.ToString(), + ["libraryId"] = book.LibraryId.ToString(), + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["saveUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { id = default(Guid) }) ?? string.Empty, + ["coverUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.UPDATE_BOOK_COVER, new { id = default(Guid) }) ?? string.Empty, + ["backUrl"] = (_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX) ?? string.Empty) + "?libraryId=" + book.LibraryId, + ["bookJson"] = JsonSerializer.Serialize(book, s_camelCaseJsonOptions), + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer), + ["stringsJson"] = JsonSerializer.Serialize(ThemePageDataFactory.CreateLocalizedStrings(_localizer), s_camelCaseJsonOptions) + } + }; + + // Themed rendering is best effort: when the active theme does not provide the item template, the plain Razor fallback is rendered instead. + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + { + Dictionary viewData = new() + { + ["Title"] = title + }; + return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml", book, viewData); + } + + // On a healthy site the page is composed by the theme, so the theme content and script are wrapped in the shared themed view. + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = title }); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs index 99d323d5..f00e4870 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs @@ -24,7 +24,7 @@ public class EditBookViewEndpointSummary : Summary r.Id, "The unique identifier of the book to edit. Required."); ExampleRequest = new GetBookRequest( - Id: Guid.NewGuid() + Id: Guid.NewGuid().ToString() ); Response(200, "The view for editing the book is rendered."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs new file mode 100644 index 00000000..34c07891 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-get-book route. +/// +public class GetBookDetailsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetBookDetailsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Books.GET_BOOK_DETAILS); + DontAutoTag(); + Options(options => options.WithTags("Books")); + } + + /// + /// Retrieves the full details of the book identified by . + /// + /// The request containing the Id of the book to retrieve. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) + { + // The route 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. + request = request with { Id = Guid.TryParse(request.Id, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString() }; + + BookDetailsDto book = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id), cancellationToken).ConfigureAwait(false); + return JsonSuccess(book); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs new file mode 100644 index 00000000..c8a50e2f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetBookDetailsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetBookDetailsEndpointSummary() + { + Summary = "Gets the details of a book."; + Description = "Gets the full details of the book identified by the request, for the details and editing view."; + + RequestParam(r => r.Id, "The unique identifier of the book to get. Required."); + + ExampleRequest = new GetBookRequest( + Id: Guid.NewGuid().ToString() + ); + + Response(200, "The details of the book are returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs index 9874ba4b..851f1489 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -87,6 +87,7 @@ public class BooksIndexViewEndpoint : BaseEndpoint ["itemsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS) ?? string.Empty, ["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty, ["readUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) }) ?? string.Empty, + ["detailsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { id = default(Guid) }) ?? string.Empty, ["availabilityUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) }) ?? string.Empty, ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs new file mode 100644 index 00000000..e51e1720 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-save-book route. +/// +public class SaveBookEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public SaveBookEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Books.SAVE_BOOK); + DontAutoTag(); + Options(options => options.WithTags("Books")); + EnableAntiforgery(); + } + + /// + /// Updates the book described by . + /// + /// 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 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(); + + BookDetailsDto book = await _apiHttpClient.PutAsync( + ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", request.Id), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(book); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs new file mode 100644 index 00000000..22a8b39c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs @@ -0,0 +1,159 @@ +#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.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SaveBookEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SaveBookEndpointSummary() + { + 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.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 = new DateOnly(1954, 7, 29), + OriginalReleaseYear = 1954, + ReReleaseDate = new DateOnly(2001, 9, 6), + ReReleaseYear = 2001, + ReleaseCountry = "uk", + ReleaseVersion = "50th Anniversary Edition" + }, + Genres = + [ + new GenreDto { Name = "fantasy" }, + new GenreDto { Name = "adventure" }, + new GenreDto { Name = "classic" } + ], + Tags = + [ + new TagDto { Name = "epic fantasy" }, + new TagDto { Name = "quest" }, + new TagDto { 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 = "Author" } + }, + new MediaContributorDto + { + Name = new MediaContributorNameDto { DisplayName = "Alan Lee", LegalName = "Alan Lee" }, + Role = new MediaContributorRoleDto { Name = "illustrator", Category = "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 } + ] + }; + + Response(200, "The updated book is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs new file mode 100644 index 00000000..d6a5ee7b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-update-cover route. +/// +public class UpdateBookCoverEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdateBookCoverEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Books.UPDATE_BOOK_COVER); + DontAutoTag(); + Options(options => options.WithTags("Books")); + EnableAntiforgery(); + } + + /// + /// 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 upstream API reports as a missing book id. + Guid bookId = Guid.TryParse(HttpContext.Request.RouteValues["id"]?.ToString(), out Guid parsedBookId) ? parsedBookId : Guid.Empty; + + // The cover is the first file of the multipart form, and without it the request cannot update anything. + IFormFile? cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null; + if (cover is null) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The uploaded cover image is missing."); + + // The cover stream must stay open while the file is streamed to the API, and is disposed when the request completes. + await using Stream coverStream = cover.OpenReadStream(); + string? coverPath = await _apiHttpClient.PutMultipartAsync( + ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", bookId.ToString()), coverStream, cover.FileName, "cover", cancellationToken).ConfigureAwait(false); + return JsonSuccess(coverPath); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs new file mode 100644 index 00000000..d86133f0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateBookCoverEndpointSummary() + { + Summary = "Updates the cover image of a book."; + Description = "Updates the cover image of the book identified by the request, with the image uploaded in the multipart form of the request."; + + Response(200, "The relative path of the stored cover image is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx index ca9830c2..d3ef82d9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ar-SA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ قارئ الكتب الذي يفتح هذا الكتاب معطل لهذه المكتبة. قم بتمكينه في إعدادات المكتبة لقراءة الكتاب. + + اقرأ + + + عرض التفاصيل + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx index 2fba039b..af0edfce 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.de-DE.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Der Buchleser, der dieses Buch öffnet, ist für diese Mediathek deaktiviert. Aktivieren Sie ihn in den Mediathek-Einstellungen, um das Buch zu lesen. + + Lesen + + + Details anzeigen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx index 93f29cbc..7effa290 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.en-US.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ The book reader that opens this book is disabled for this library. Enable it in the library settings to read the book. + + Read + + + View details + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx index 7af89bbb..a9f6ee25 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.es-ES.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ El lector de libros que abre este libro está deshabilitado para esta biblioteca. Habilítelo en la configuración de la biblioteca para leer el libro. + + Leer + + + Ver detalles + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx index 79d38825..29e1131e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.fr-FR.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Le lecteur de livres qui ouvre ce livre est désactivé pour cette bibliothèque. Activez-le dans les paramètres de la bibliothèque pour lire le livre. + + Lire + + + Voir les détails + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx index bdf944bd..4ba88908 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.it-IT.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Il lettore di libri che apre questo libro è disabilitato per questa biblioteca. Abilitalo nelle impostazioni della biblioteca per leggere il libro. + + Leggi + + + Visualizza dettagli + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx index cf1308f1..87fc1d44 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ja-JP.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ この本を開くブックリーダーは、このライブラリで無効になっています。ライブラリ設定で有効にすると本を読めます。 + + 読む + + + 詳細を表示 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx index 93f29cbc..7effa290 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ The book reader that opens this book is disabled for this library. Enable it in the library settings to read the book. + + Read + + + View details + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx index 244e911c..49c172e6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.ro-RO.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Cititorul de cărți care deschide această carte este dezactivat pentru această bibliotecă. Activați-l în setările bibliotecii pentru a citi cartea. + + Citește + + + Vezi detalii + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx index e20352f4..32a25ba4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.uk-UA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ Читач книг, який відкриває цю книгу, вимкнено для цієї бібліотеки. Увімкніть його в налаштуваннях бібліотеки, щоб читати книгу. + + Читати + + + Переглянути деталі + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx index de258336..5b5e8e0f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.zh-CN.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -51,4 +51,10 @@ 打开此图书的图书阅读器已在此媒体库中禁用。在媒体库设置中启用它即可阅读该图书。 + + 阅读 + + + 查看详情 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx new file mode 100644 index 00000000..c868feea --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + إضافة مساهم + + + إضافة تقييم + + + إضافة + + + معرّف الكتاب على Apple Books. + + + رقم التعريف القياسي لأمازون الخاص بالكتاب. + + + كتاب صوتي + + + مؤلف + + + العودة إلى المكتبة + + + معرّف الكتاب على Barnes & Noble. + + + كتاب من الورق المقوى + + + تفاصيل الكتاب + + + تم حفظ الكتاب. + + + تغيير الغلاف + + + الاسم + + + الأشخاص الذين ساهموا في الكتاب، مثل مؤلفيه. + + + صورة الغلاف + + + تم تحديث صورة الغلاف. + + + تعذر رفع صورة الغلاف. + + + الوصف + + + ملخص قصير أو وصف للكتاب. + + + كتاب إلكتروني + + + الطبعة + + + طبعة الكتاب. + + + الصيغة + + + الصيغة المادية أو الرقمية للكتاب. + + + معلومات عامة + + + الأنواع + + + أنواع الكتاب، مفصولة بفواصل. + + + المعرّف الرقمي للكتاب على Goodreads. + + + معرّف الكتاب على Google Books. + + + غلاف مقوى + + + المعرّفات + + + رسام + + + صيغة ISBN + + + أرقام الكتاب الدولية المعيارية (ISBN). + + + قيمة ISBN + + + اللغة + + + رمز اللغة + + + رمز الحرفين للغة الكتاب. + + + اسم اللغة + + + اسم لغة الكتاب. + + + حرف كبير + + + رقم ضبط مكتبة الكونغرس للكتاب. + + + تجليد جلدي + + + تجليد مكتبي + + + معرّف الكتاب على LibraryThing. + + + ورقي للسوق الشامل + + + راوٍ + + + الاسم الأصلي للغة + + + الاسم الأصلي للغة الكتاب. + + + لا يوجد غلاف + + + رقم OCLC + + + رقم OCLC للكتاب. + + + معرّف الكتاب على Open Library. + + + اللغة الأصلية + + + رمز اللغة الأصلية + + + رمز الحرفين للغة الأصلية للكتاب. + + + اسم اللغة الأصلية + + + اسم اللغة الأصلية للكتاب. + + + الاسم الأصلي للغة الأصلية + + + الاسم الأصلي للغة الأصلية للكتاب. + + + تاريخ الإصدار الأصلي + + + التاريخ الذي صدر فيه الكتاب لأول مرة. + + + سنة الإصدار الأصلي + + + السنة التي صدر فيها الكتاب لأول مرة. + + + العنوان الأصلي + + + العنوان الأصلي للكتاب، عندما يختلف عن العنوان الحالي. + + + أخرى + + + عدد الصفحات + + + عدد صفحات الكتاب. + + + غلاف ورقي + + + كتاب منبثق + + + الناشر + + + ناشر الكتاب. + + + ناشر + + + أقصى تقييم + + + التقييمات + + + تقييمات الكتاب من مصادر مختلفة. + + + المصدر + + + التقييم + + + عدد الأصوات + + + بلد الإصدار + + + رمز الحرفين لبلد الإصدار. + + + معلومات الإصدار + + + نسخة الإصدار + + + نسخة الإصدار، مثل النسخة الأصلية. + + + إزالة + + + تاريخ إعادة الإصدار + + + التاريخ الذي أعيد فيه إصدار الكتاب. + + + سنة إعادة الإصدار + + + السنة التي أعيد فيها إصدار الكتاب. + + + فئة الدور + + + الدور + + + حفظ + + + تعذر حفظ الكتاب. + + + تجليد حلزوني + + + الوسوم + + + وسوم الكتاب، مفصولة بفواصل. + + + العنوان + + + العنوان الرئيسي للكتاب. + + + ورقي تجاري + + + مترجم + + + مستخدم + + + رقم المجلد + + + رقم مجلد الكتاب ضمن سلسلته. + + + ISBN-13 + + + LCCN + + + Calibre + + + معرّف Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + معرّف Google Books + + + معرّف LibraryThing + + + Goodreads + + + Amazon + + + معرّف Barnes & Noble + + + معرّف Open Library + + + ISBN + + + المساهمون + + + معرّف Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx new file mode 100644 index 00000000..60701ae8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Mitwirkenden hinzufügen + + + Bewertung hinzufügen + + + Hinzufügen + + + Die Kennung des Buches bei Apple Books. + + + Die Amazon-Standard-Identifikationsnummer des Buches. + + + Hörbuch + + + Autor + + + Zurück zur Bibliothek + + + Die Kennung des Buches bei Barnes & Noble. + + + Pappbilderbuch + + + Buchdetails + + + Das Buch wurde gespeichert. + + + Titelbild ändern + + + Name + + + Die Personen, die zum Buch beigetragen haben, wie seine Autoren. + + + Titelbild + + + Das Titelbild wurde aktualisiert. + + + Das Titelbild konnte nicht hochgeladen werden. + + + Beschreibung + + + Eine kurze Zusammenfassung oder Beschreibung des Buches. + + + eBook + + + Ausgabe + + + Die Ausgabe des Buches. + + + Format + + + Das physische oder digitale Format des Buches. + + + Allgemeine Informationen + + + Genres + + + Die Genres des Buches, durch Kommas getrennt. + + + Die numerische Kennung des Buches bei Goodreads. + + + Die Kennung des Buches bei Google Books. + + + Gebundene Ausgabe + + + Kennungen + + + Illustrator + + + ISBN-Format + + + Die Internationalen Standardbuchnummern des Buches. + + + ISBN-Wert + + + Sprache + + + Sprachcode + + + Der zweibuchstabige Code der Sprache des Buches. + + + Sprachname + + + Der Name der Sprache des Buches. + + + Großdruck + + + Die Library-of-Congress-Kontrollnummer des Buches. + + + Ledereinband + + + Bibliothekseinband + + + Die Kennung des Buches bei LibraryThing. + + + Massenmarkt-Taschenbuch + + + Erzähler + + + Muttersprachlicher Name + + + Der muttersprachliche Name der Sprache des Buches. + + + Kein Titelbild + + + OCLC-Nummer + + + Die OCLC-Nummer des Buches. + + + Die Kennung des Buches bei Open Library. + + + Originalsprache + + + Code der Originalsprache + + + Der zweibuchstabige Code der Originalsprache des Buches. + + + Name der Originalsprache + + + Der Name der Originalsprache des Buches. + + + Muttersprachlicher Name der Originalsprache + + + Der muttersprachliche Name der Originalsprache des Buches. + + + Datum der Erstveröffentlichung + + + Das Datum, an dem das Buch ursprünglich veröffentlicht wurde. + + + Jahr der Erstveröffentlichung + + + Das Jahr, in dem das Buch ursprünglich veröffentlicht wurde. + + + Originaltitel + + + Der Originaltitel des Buches, wenn er vom aktuellen Titel abweicht. + + + Sonstige + + + Seitenzahl + + + Die Seitenzahl des Buches. + + + Taschenbuch + + + Pop-up-Buch + + + Verlag + + + Der Verlag des Buches. + + + Verlag + + + Höchstbewertung + + + Bewertungen + + + Die Bewertungen des Buches aus verschiedenen Quellen. + + + Quelle + + + Bewertung + + + Stimmenzahl + + + Erscheinungsland + + + Der zweibuchstabige Code des Erscheinungslandes. + + + Veröffentlichungsinformationen + + + Veröffentlichungsversion + + + Die Version der Veröffentlichung, wie die ursprüngliche. + + + Entfernen + + + Datum der Neuveröffentlichung + + + Das Datum, an dem das Buch erneut veröffentlicht wurde. + + + Jahr der Neuveröffentlichung + + + Das Jahr, in dem das Buch erneut veröffentlicht wurde. + + + Rollenkategorie + + + Rolle + + + Speichern + + + Das Buch konnte nicht gespeichert werden. + + + Spiralbindung + + + Schlagwörter + + + Die Schlagwörter des Buches, durch Kommas getrennt. + + + Titel + + + Der Haupttitel des Buches. + + + Trade-Taschenbuch + + + Übersetzer + + + Benutzer + + + Bandnummer + + + Die Bandnummer des Buches innerhalb seiner Reihe. + + + ISBN-13 + + + LCCN + + + Calibre + + + Apple-Books-ID + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + Google-Books-ID + + + LibraryThing-ID + + + Goodreads + + + Amazon + + + Barnes-&-Noble-ID + + + Open-Library-ID + + + ISBNs + + + Mitwirkende + + + Goodreads-ID + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx new file mode 100644 index 00000000..53d224d1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Book details + + + Back to library + + + Save + + + Add + + + General information + + + Title + + + Original title + + + Description + + + Publisher + + + Page count + + + Format + + + Edition + + + Volume number + + + Release information + + + Original release date + + + Original release year + + + Re-release date + + + Re-release year + + + Release country + + + Release version + + + Language + + + Language code + + + Language name + + + Native name + + + Original language + + + Original language code + + + Original language name + + + Original language native name + + + Genres + + + Tags + + + Identifiers + + + ASIN + + + Goodreads Id + + + LCCN + + + OCLC number + + + Open Library Id + + + LibraryThing Id + + + Google Books Id + + + Barnes & Noble Id + + + Apple Books Id + + + ISBNs + + + ISBN value + + + ISBN format + + + ISBN-10 + + + ISBN-13 + + + Contributors + + + Name + + + Role + + + Role category + + + Add contributor + + + Ratings + + + Rating + + + Maximum rating + + + Source + + + Vote count + + + Add rating + + + Cover image + + + Change cover + + + No cover + + + Remove + + + The main title of the book. + + + The original title of the book, when it differs from the current one. + + + A short summary or description of the book. + + + The publisher of the book. + + + The number of pages of the book. + + + The physical or digital format of the book. + + + The edition of the book. + + + The volume number of the book within its series. + + + The date when the book was originally released. + + + The year when the book was originally released. + + + The date when the book was released again. + + + The year when the book was released again. + + + The two letter code of the country of release. + + + The version of the release, like the original one. + + + The two letter code of the language of the book. + + + The name of the language of the book. + + + The native name of the language of the book. + + + The two letter code of the original language of the book. + + + The name of the original language of the book. + + + The native name of the original language of the book. + + + The genres of the book, separated by commas. + + + The tags of the book, separated by commas. + + + The Amazon Standard Identification Number of the book. + + + The numeric identifier of the book on Goodreads. + + + The Library of Congress Control Number of the book. + + + The OCLC number of the book. + + + The identifier of the book on Open Library. + + + The identifier of the book on LibraryThing. + + + The identifier of the book on Google Books. + + + The identifier of the book on Barnes & Noble. + + + The identifier of the book on Apple Books. + + + The International Standard Book Numbers of the book. + + + The people that contributed to the book, like its authors. + + + The ratings of the book from different sources. + + + Other + + + Author + + + Translator + + + Illustrator + + + Publisher + + + Narrator + + + User + + + Open Library + + + Goodreads + + + Amazon + + + Google Books + + + Calibre + + + Hardcover + + + Paperback + + + Mass market paperback + + + Trade paperback + + + eBook + + + Audiobook + + + Large print + + + Board book + + + Spiral bound + + + Library binding + + + Leather bound + + + Pop-up book + + + The book was saved. + + + The cover image was updated. + + + The book could not be saved. + + + The cover image could not be uploaded. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx new file mode 100644 index 00000000..de95fe36 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Añadir colaborador + + + Añadir valoración + + + Añadir + + + El identificador del libro en Apple Books. + + + El número de identificación estándar de Amazon del libro. + + + Audiolibro + + + Autor + + + Volver a la biblioteca + + + El identificador del libro en Barnes & Noble. + + + Libro de cartón + + + Detalles del libro + + + El libro se ha guardado. + + + Cambiar portada + + + Nombre + + + Las personas que contribuyeron al libro, como sus autores. + + + Imagen de portada + + + La imagen de portada se ha actualizado. + + + La imagen de portada no se ha podido subir. + + + Descripción + + + Un breve resumen o descripción del libro. + + + Libro electrónico + + + Edición + + + La edición del libro. + + + Formato + + + El formato físico o digital del libro. + + + Información general + + + Géneros + + + Los géneros del libro, separados por comas. + + + El identificador numérico del libro en Goodreads. + + + El identificador del libro en Google Books. + + + Tapa dura + + + Identificadores + + + Ilustrador + + + Formato ISBN + + + Los números internacionales normalizados del libro (ISBN). + + + Valor ISBN + + + Idioma + + + Código de idioma + + + El código de dos letras del idioma del libro. + + + Nombre del idioma + + + El nombre del idioma del libro. + + + Letra grande + + + El número de control de la Biblioteca del Congreso del libro. + + + Encuadernación en piel + + + Encuadernación de biblioteca + + + El identificador del libro en LibraryThing. + + + Bolsillo + + + Narrador + + + Nombre nativo + + + El nombre nativo del idioma del libro. + + + Sin portada + + + Número OCLC + + + El número OCLC del libro. + + + El identificador del libro en Open Library. + + + Idioma original + + + Código del idioma original + + + El código de dos letras del idioma original del libro. + + + Nombre del idioma original + + + El nombre del idioma original del libro. + + + Nombre nativo del idioma original + + + El nombre nativo del idioma original del libro. + + + Fecha de publicación original + + + La fecha en la que el libro se publicó originalmente. + + + Año de publicación original + + + El año en el que el libro se publicó originalmente. + + + Título original + + + El título original del libro, cuando difiere del actual. + + + Otro + + + Número de páginas + + + El número de páginas del libro. + + + Tapa blanda + + + Libro pop-up + + + Editorial + + + La editorial del libro. + + + Editorial + + + Valoración máxima + + + Valoraciones + + + Las valoraciones del libro de distintas fuentes. + + + Fuente + + + Valoración + + + Número de votos + + + País de publicación + + + El código de dos letras del país de publicación. + + + Información de publicación + + + Versión de publicación + + + La versión de la publicación, como la original. + + + Eliminar + + + Fecha de reedición + + + La fecha en la que el libro se volvió a publicar. + + + Año de reedición + + + El año en el que el libro se volvió a publicar. + + + Categoría de rol + + + Rol + + + Guardar + + + El libro no se ha podido guardar. + + + Encuadernación en espiral + + + Etiquetas + + + Las etiquetas del libro, separadas por comas. + + + Título + + + El título principal del libro. + + + Rústica + + + Traductor + + + Usuario + + + Número de volumen + + + El número de volumen del libro dentro de su serie. + + + ISBN-13 + + + LCCN + + + Calibre + + + ID de Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + ID de Google Books + + + ID de LibraryThing + + + Goodreads + + + Amazon + + + ID de Barnes & Noble + + + ID de Open Library + + + ISBNs + + + Colaboradores + + + ID de Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx new file mode 100644 index 00000000..24f103cc --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Ajouter un contributeur + + + Ajouter une évaluation + + + Ajouter + + + L'identifiant du livre sur Apple Books. + + + Le numéro d'identification standard Amazon du livre. + + + Livre audio + + + Auteur + + + Retour à la bibliothèque + + + L'identifiant du livre sur Barnes & Noble. + + + Livre cartonné + + + Détails du livre + + + Le livre a été enregistré. + + + Changer la couverture + + + Nom + + + Les personnes ayant contribué au livre, comme ses auteurs. + + + Image de couverture + + + L'image de couverture a été mise à jour. + + + L'image de couverture n'a pas pu être téléchargée. + + + Description + + + Un bref résumé ou une description du livre. + + + Livre numérique + + + Édition + + + L'édition du livre. + + + Format + + + Le format physique ou numérique du livre. + + + Informations générales + + + Genres + + + Les genres du livre, séparés par des virgules. + + + L'identifiant numérique du livre sur Goodreads. + + + L'identifiant du livre sur Google Books. + + + Couverture rigide + + + Identifiants + + + Illustrateur + + + Format ISBN + + + Les numéros internationaux normalisés du livre (ISBN). + + + Valeur ISBN + + + Langue + + + Code de langue + + + Le code à deux lettres de la langue du livre. + + + Nom de la langue + + + Le nom de la langue du livre. + + + Gros caractères + + + Le numéro de contrôle de la Library of Congress du livre. + + + Reliure cuir + + + Reliure de bibliothèque + + + L'identifiant du livre sur LibraryThing. + + + Poche + + + Narrateur + + + Nom natif + + + Le nom natif de la langue du livre. + + + Aucune couverture + + + Numéro OCLC + + + Le numéro OCLC du livre. + + + L'identifiant du livre sur Open Library. + + + Langue originale + + + Code de la langue originale + + + Le code à deux lettres de la langue originale du livre. + + + Nom de la langue originale + + + Le nom de la langue originale du livre. + + + Nom natif de la langue originale + + + Le nom natif de la langue originale du livre. + + + Date de publication originale + + + La date de publication originale du livre. + + + Année de publication originale + + + L'année de publication originale du livre. + + + Titre original + + + Le titre original du livre, lorsqu'il diffère du titre actuel. + + + Autre + + + Nombre de pages + + + Le nombre de pages du livre. + + + Broché + + + Livre animé + + + Éditeur + + + L'éditeur du livre. + + + Éditeur + + + Évaluation maximale + + + Évaluations + + + Les évaluations du livre provenant de différentes sources. + + + Source + + + Évaluation + + + Nombre de votes + + + Pays de publication + + + Le code à deux lettres du pays de publication. + + + Informations de publication + + + Version de publication + + + La version de la publication, comme la version originale. + + + Supprimer + + + Date de réédition + + + La date de réédition du livre. + + + Année de réédition + + + L'année de réédition du livre. + + + Catégorie de rôle + + + Rôle + + + Enregistrer + + + Le livre n'a pas pu être enregistré. + + + Reliure spirale + + + Étiquettes + + + Les étiquettes du livre, séparées par des virgules. + + + Titre + + + Le titre principal du livre. + + + Grand format broché + + + Traducteur + + + Utilisateur + + + Numéro de volume + + + Le numéro de volume du livre au sein de sa série. + + + ISBN-13 + + + LCCN + + + Calibre + + + Identifiant Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + Identifiant Google Books + + + Identifiant LibraryThing + + + Goodreads + + + Amazon + + + Identifiant Barnes & Noble + + + Identifiant Open Library + + + ISBNs + + + Contributeurs + + + Identifiant Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx new file mode 100644 index 00000000..cbd9098d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Aggiungi collaboratore + + + Aggiungi valutazione + + + Aggiungi + + + L'identificatore del libro su Apple Books. + + + Il numero di identificazione standard Amazon del libro. + + + Audiolibro + + + Autore + + + Torna alla biblioteca + + + L'identificatore del libro su Barnes & Noble. + + + Libro cartonato + + + Dettagli del libro + + + Il libro è stato salvato. + + + Cambia copertina + + + Nome + + + Le persone che hanno contribuito al libro, come i suoi autori. + + + Immagine di copertina + + + L'immagine di copertina è stata aggiornata. + + + L'immagine di copertina non è stato possibile caricarla. + + + Descrizione + + + Un breve riassunto o descrizione del libro. + + + Libro elettronico + + + Edizione + + + L'edizione del libro. + + + Formato + + + Il formato fisico o digitale del libro. + + + Informazioni generali + + + Generi + + + I generi del libro, separati da virgole. + + + L'identificatore numerico del libro su Goodreads. + + + L'identificatore del libro su Google Books. + + + Copertina rigida + + + Identificatori + + + Illustratore + + + Formato ISBN + + + I numeri internazionali normalizzati del libro (ISBN). + + + Valore ISBN + + + Lingua + + + Codice lingua + + + Il codice di due lettere della lingua del libro. + + + Nome della lingua + + + Il nome della lingua del libro. + + + Caratteri grandi + + + Il numero di controllo della Library of Congress del libro. + + + Legatura in pelle + + + Legatura da biblioteca + + + L'identificatore del libro su LibraryThing. + + + Tascabile + + + Narratore + + + Nome nativo + + + Il nome nativo della lingua del libro. + + + Nessuna copertina + + + Numero OCLC + + + Il numero OCLC del libro. + + + L'identificatore del libro su Open Library. + + + Lingua originale + + + Codice della lingua originale + + + Il codice di due lettere della lingua originale del libro. + + + Nome della lingua originale + + + Il nome della lingua originale del libro. + + + Nome nativo della lingua originale + + + Il nome nativo della lingua originale del libro. + + + Data di pubblicazione originale + + + La data di pubblicazione originale del libro. + + + Anno di pubblicazione originale + + + L'anno di pubblicazione originale del libro. + + + Titolo originale + + + Il titolo originale del libro, quando differisce da quello attuale. + + + Altro + + + Numero di pagine + + + Il numero di pagine del libro. + + + Brossura + + + Libro animato + + + Editore + + + L'editore del libro. + + + Editore + + + Valutazione massima + + + Valutazioni + + + Le valutazioni del libro da diverse fonti. + + + Fonte + + + Valutazione + + + Numero di voti + + + Paese di pubblicazione + + + Il codice di due lettere del paese di pubblicazione. + + + Informazioni di pubblicazione + + + Versione di pubblicazione + + + La versione della pubblicazione, come quella originale. + + + Rimuovi + + + Data di ripubblicazione + + + La data di ripubblicazione del libro. + + + Anno di ripubblicazione + + + L'anno di ripubblicazione del libro. + + + Categoria del ruolo + + + Ruolo + + + Salva + + + Il libro non è stato possibile salvarlo. + + + Rilegatura a spirale + + + Etichette + + + Le etichette del libro, separate da virgole. + + + Titolo + + + Il titolo principale del libro. + + + Brossura editoriale + + + Traduttore + + + Utente + + + Numero del volume + + + Il numero del volume del libro all'interno della sua serie. + + + ISBN-13 + + + LCCN + + + Calibre + + + ID Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + ID Google Books + + + ID LibraryThing + + + Goodreads + + + Amazon + + + ID Barnes & Noble + + + ID Open Library + + + ISBN + + + Collaboratori + + + ID Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx new file mode 100644 index 00000000..20364219 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 貢献者を追加 + + + 評価を追加 + + + 追加 + + + Apple Books上の本のID。 + + + 本のAmazon標準識別番号。 + + + オーディオブック + + + 著者 + + + ライブラリに戻る + + + Barnes & Noble上の本のID。 + + + ボードブック + + + 本の詳細 + + + 本が保存されました。 + + + 表紙を変更 + + + 名前 + + + 著者など、本に貢献した人々。 + + + 表紙画像 + + + 表紙画像が更新されました。 + + + 表紙画像をアップロードできませんでした。 + + + 説明 + + + 本の簡単な要約または説明。 + + + 電子書籍 + + + 版 + + + 本の版。 + + + 形式 + + + 本の物理的またはデジタル形式。 + + + 一般情報 + + + ジャンル + + + 本のジャンル。カンマ区切り。 + + + Goodreads上の本の数値ID。 + + + Google Books上の本のID。 + + + ハードカバー + + + 識別子 + + + イラストレーター + + + ISBN形式 + + + 本の国際標準図書番号(ISBN)。 + + + ISBN + + + 言語 + + + 言語コード + + + 本の言語の2文字コード。 + + + 言語名 + + + 本の言語名。 + + + 大活字 + + + 本の米国議会図書館管理番号。 + + + 革装 + + + 図書館製本 + + + LibraryThing上の本のID。 + + + マスマーケットペーパーバック + + + ナレーター + + + 現地語名 + + + 本の言語の現地語名。 + + + 表紙なし + + + OCLC番号 + + + 本のOCLC番号。 + + + Open Library上の本のID。 + + + 原語 + + + 原語コード + + + 本の原語の2文字コード。 + + + 原語名 + + + 本の原語名。 + + + 原語の現地語名 + + + 本の原語の現地語名。 + + + 初版発売日 + + + 本が最初に発売された日付。 + + + 初版発売年 + + + 本が最初に発売された年。 + + + 原題 + + + 現在のタイトルと異なる場合の本の原題。 + + + その他 + + + ページ数 + + + 本のページ数。 + + + ペーパーバック + + + 飛び出す絵本 + + + 出版社 + + + 本の出版社。 + + + 出版社 + + + 最大評価 + + + 評価 + + + さまざまな出典による本の評価。 + + + 出典 + + + 評価 + + + 投票数 + + + 発売国 + + + 発売国の2文字コード。 + + + リリース情報 + + + リリース版 + + + オリジナル版など、リリースのバージョン。 + + + 削除 + + + 再発売日 + + + 本が再発売された日付。 + + + 再発売年 + + + 本が再発売された年。 + + + 役割カテゴリ + + + 役割 + + + 保存 + + + 本を保存できませんでした。 + + + リング製本 + + + タグ + + + 本のタグ。カンマ区切り。 + + + タイトル + + + 本の主タイトル。 + + + トレードペーパーバック + + + 翻訳者 + + + ユーザー + + + 巻数 + + + シリーズ内の本の巻数。 + + + ISBN-13 + + + LCCN + + + Calibre + + + Apple Books ID + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + Google Books ID + + + LibraryThing ID + + + Goodreads + + + Amazon + + + Barnes & Noble ID + + + Open Library ID + + + ISBN + + + 貢献者 + + + Goodreads ID + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx new file mode 100644 index 00000000..53d224d1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Book details + + + Back to library + + + Save + + + Add + + + General information + + + Title + + + Original title + + + Description + + + Publisher + + + Page count + + + Format + + + Edition + + + Volume number + + + Release information + + + Original release date + + + Original release year + + + Re-release date + + + Re-release year + + + Release country + + + Release version + + + Language + + + Language code + + + Language name + + + Native name + + + Original language + + + Original language code + + + Original language name + + + Original language native name + + + Genres + + + Tags + + + Identifiers + + + ASIN + + + Goodreads Id + + + LCCN + + + OCLC number + + + Open Library Id + + + LibraryThing Id + + + Google Books Id + + + Barnes & Noble Id + + + Apple Books Id + + + ISBNs + + + ISBN value + + + ISBN format + + + ISBN-10 + + + ISBN-13 + + + Contributors + + + Name + + + Role + + + Role category + + + Add contributor + + + Ratings + + + Rating + + + Maximum rating + + + Source + + + Vote count + + + Add rating + + + Cover image + + + Change cover + + + No cover + + + Remove + + + The main title of the book. + + + The original title of the book, when it differs from the current one. + + + A short summary or description of the book. + + + The publisher of the book. + + + The number of pages of the book. + + + The physical or digital format of the book. + + + The edition of the book. + + + The volume number of the book within its series. + + + The date when the book was originally released. + + + The year when the book was originally released. + + + The date when the book was released again. + + + The year when the book was released again. + + + The two letter code of the country of release. + + + The version of the release, like the original one. + + + The two letter code of the language of the book. + + + The name of the language of the book. + + + The native name of the language of the book. + + + The two letter code of the original language of the book. + + + The name of the original language of the book. + + + The native name of the original language of the book. + + + The genres of the book, separated by commas. + + + The tags of the book, separated by commas. + + + The Amazon Standard Identification Number of the book. + + + The numeric identifier of the book on Goodreads. + + + The Library of Congress Control Number of the book. + + + The OCLC number of the book. + + + The identifier of the book on Open Library. + + + The identifier of the book on LibraryThing. + + + The identifier of the book on Google Books. + + + The identifier of the book on Barnes & Noble. + + + The identifier of the book on Apple Books. + + + The International Standard Book Numbers of the book. + + + The people that contributed to the book, like its authors. + + + The ratings of the book from different sources. + + + Other + + + Author + + + Translator + + + Illustrator + + + Publisher + + + Narrator + + + User + + + Open Library + + + Goodreads + + + Amazon + + + Google Books + + + Calibre + + + Hardcover + + + Paperback + + + Mass market paperback + + + Trade paperback + + + eBook + + + Audiobook + + + Large print + + + Board book + + + Spiral bound + + + Library binding + + + Leather bound + + + Pop-up book + + + The book was saved. + + + The cover image was updated. + + + The book could not be saved. + + + The cover image could not be uploaded. + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx new file mode 100644 index 00000000..ed005b8d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Adaugă contributor + + + Adaugă rating + + + Adaugă + + + Identificatorul cărții pe Apple Books. + + + Numărul standard de identificare Amazon al cărții. + + + Carte audio + + + Autor + + + Înapoi la bibliotecă + + + Identificatorul cărții pe Barnes & Noble. + + + Carte de carton + + + Detalii carte + + + Cartea a fost salvată. + + + Schimbă coperta + + + Nume + + + Persoanele care au contribuit la carte, precum autorii ei. + + + Imagine de copertă + + + Imaginea de copertă a fost actualizată. + + + Imaginea de copertă nu a putut fi încărcată. + + + Descriere + + + Un scurt rezumat sau o descriere a cărții. + + + Carte electronică + + + Ediție + + + Ediția cărții. + + + Format + + + Formatul fizic sau digital al cărții. + + + Informații generale + + + Genuri + + + Genurile cărții, separate prin virgule. + + + Identificatorul numeric al cărții pe Goodreads. + + + Identificatorul cărții pe Google Books. + + + Copertă cartonată + + + Identificatori + + + Ilustrator + + + Format ISBN + + + Numerele internaționale standardizate ale cărții (ISBN). + + + Valoare ISBN + + + Limbă + + + Codul limbii + + + Codul din două litere al limbii cărții. + + + Denumirea limbii + + + Denumirea limbii cărții. + + + Tipar mare + + + Numărul de control al Library of Congress al cărții. + + + Legare în piele + + + Legare de bibliotecă + + + Identificatorul cărții pe LibraryThing. + + + Ediție de buzunar + + + Narator + + + Denumire nativă + + + Denumirea nativă a limbii cărții. + + + Fără copertă + + + Număr OCLC + + + Numărul OCLC al cărții. + + + Identificatorul cărții pe Open Library. + + + Limba originală + + + Codul limbii originale + + + Codul din două litere al limbii originale a cărții. + + + Denumirea limbii originale + + + Denumirea limbii originale a cărții. + + + Denumirea nativă a limbii originale + + + Denumirea nativă a limbii originale a cărții. + + + Data lansării originale + + + Data la care cartea a fost lansată inițial. + + + Anul lansării originale + + + Anul în care cartea a fost lansată inițial. + + + Titlu original + + + Titlul original al cărții, când diferă de cel actual. + + + Altul + + + Număr de pagini + + + Numărul de pagini al cărții. + + + Copertă broșată + + + Carte pop-up + + + Editură + + + Editura cărții. + + + Editură + + + Rating maxim + + + Ratinguri + + + Ratingurile cărții din diferite surse. + + + Sursă + + + Rating + + + Număr de voturi + + + Țara de lansare + + + Codul din două litere al țării de lansare. + + + Informații de lansare + + + Versiunea lansării + + + Versiunea lansării, precum cea originală. + + + Elimină + + + Data relansării + + + Data la care cartea a fost relansată. + + + Anul relansării + + + Anul în care cartea a fost relansată. + + + Categoria rolului + + + Rol + + + Salvează + + + Cartea nu a putut fi salvată. + + + Legare spirală + + + Etichete + + + Etichetele cărții, separate prin virgule. + + + Titlu + + + Titlul principal al cărții. + + + Broșat trade + + + Traducător + + + Utilizator + + + Număr volum + + + Numărul volumului cărții în cadrul seriei sale. + + + ISBN-13 + + + LCCN + + + Calibre + + + ID Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + ID Google Books + + + ID LibraryThing + + + Goodreads + + + Amazon + + + ID Barnes & Noble + + + ID Open Library + + + ISBN-uri + + + Contribuitori + + + ID Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx new file mode 100644 index 00000000..34a49dc7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Додати учасника + + + Додати оцінку + + + Додати + + + Ідентифікатор книги на Apple Books. + + + Стандартний ідентифікаційний номер Amazon книги. + + + Аудіокнига + + + Автор + + + Повернутися до бібліотеки + + + Ідентифікатор книги на Barnes & Noble. + + + Картонна книга + + + Деталі книги + + + Книгу збережено. + + + Змінити обкладинку + + + Ім'я + + + Люди, які долучилися до створення книги, як-от її автори. + + + Зображення обкладинки + + + Зображення обкладинки оновлено. + + + Не вдалося завантажити зображення обкладинки. + + + Опис + + + Короткий зміст або опис книги. + + + Електронна книга + + + Видання + + + Видання книги. + + + Формат + + + Фізичний або цифровий формат книги. + + + Загальна інформація + + + Жанри + + + Жанри книги, розділені комами. + + + Числовий ідентифікатор книги на Goodreads. + + + Ідентифікатор книги на Google Books. + + + Тверда палітурка + + + Ідентифікатори + + + Ілюстратор + + + Формат ISBN + + + Міжнародні стандартні номери книги (ISBN). + + + Значення ISBN + + + Мова + + + Код мови + + + Дволітерний код мови книги. + + + Назва мови + + + Назва мови книги. + + + Великий шрифт + + + Контрольний номер Бібліотеки Конгресу книги. + + + Шкіряна палітурка + + + Бібліотечна палітурка + + + Ідентифікатор книги на LibraryThing. + + + Кишеньковий формат + + + Оповідач + + + Власна назва + + + Власна назва мови книги. + + + Без обкладинки + + + Номер OCLC + + + Номер OCLC книги. + + + Ідентифікатор книги на Open Library. + + + Оригінальна мова + + + Код оригінальної мови + + + Дволітерний код оригінальної мови книги. + + + Назва оригінальної мови + + + Назва оригінальної мови книги. + + + Власна назва оригінальної мови + + + Власна назва оригінальної мови книги. + + + Дата першого випуску + + + Дата першого випуску книги. + + + Рік першого випуску + + + Рік першого випуску книги. + + + Оригінальна назва + + + Оригінальна назва книги, якщо вона відрізняється від поточної. + + + Інше + + + Кількість сторінок + + + Кількість сторінок книги. + + + М'яка палітурка + + + Книга-панорама + + + Видавництво + + + Видавництво книги. + + + Видавництво + + + Максимальна оцінка + + + Оцінки + + + Оцінки книги з різних джерел. + + + Джерело + + + Оцінка + + + Кількість голосів + + + Країна випуску + + + Дволітерний код країни випуску. + + + Інформація про випуск + + + Версія випуску + + + Версія випуску, як-от оригінальна. + + + Видалити + + + Дата перевипуску + + + Дата перевипуску книги. + + + Рік перевипуску + + + Рік перевипуску книги. + + + Категорія ролі + + + Роль + + + Зберегти + + + Не вдалося зберегти книгу. + + + Спіральна палітурка + + + Теги + + + Теги книги, розділені комами. + + + Назва + + + Основна назва книги. + + + Трейд-пап’пербек + + + Перекладач + + + Користувач + + + Номер тому + + + Номер тому книги в межах її серії. + + + ISBN-13 + + + LCCN + + + Calibre + + + ID на Apple Books + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + ID на Google Books + + + ID на LibraryThing + + + Goodreads + + + Amazon + + + ID на Barnes & Noble + + + ID на Open Library + + + ISBN + + + Учасники + + + ID на Goodreads + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx new file mode 100644 index 00000000..2d9aff0a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx @@ -0,0 +1,381 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 添加贡献者 + + + 添加评分 + + + 添加 + + + 图书在 Apple Books 上的标识。 + + + 图书的亚马逊标准识别号。 + + + 有声书 + + + 作者 + + + 返回图书馆 + + + 图书在 Barnes & Noble 上的标识。 + + + 纸板书 + + + 图书详情 + + + 图书已保存。 + + + 更换封面 + + + 姓名 + + + 为图书作出贡献的人,例如其作者。 + + + 封面图片 + + + 封面图片已更新。 + + + 无法上传封面图片。 + + + 简介 + + + 图书的简短摘要或简介。 + + + 电子书 + + + 版本 + + + 图书的版本。 + + + 格式 + + + 图书的实体或数字格式。 + + + 常规信息 + + + 体裁 + + + 图书的体裁,以逗号分隔。 + + + 图书在 Goodreads 上的数字标识。 + + + 图书在 Google Books 上的标识。 + + + 精装本 + + + 标识符 + + + 插画师 + + + ISBN 格式 + + + 图书的国际标准书号(ISBN)。 + + + ISBN 值 + + + 语言 + + + 语言代码 + + + 图书语言的两位代码。 + + + 语言名称 + + + 图书语言的名称。 + + + 大字版 + + + 图书的美国国会图书馆控制号。 + + + 皮面装订 + + + 图书馆装订 + + + 图书在 LibraryThing 上的标识。 + + + 大众平装本 + + + 叙述者 + + + 本地语名称 + + + 图书语言的本地语名称。 + + + 无封面 + + + OCLC 编号 + + + 图书的 OCLC 编号。 + + + 图书在 Open Library 上的标识。 + + + 原语言 + + + 原语言代码 + + + 图书原语言的两位代码。 + + + 原语言名称 + + + 图书原语言的名称。 + + + 原语言本地语名称 + + + 图书原语言的本地语名称。 + + + 首次发行日期 + + + 图书首次发行的日期。 + + + 首次发行年份 + + + 图书首次发行的年份。 + + + 原标题 + + + 图书的原标题,如果与当前标题不同。 + + + 其他 + + + 页数 + + + 图书的页数。 + + + 平装本 + + + 立体书 + + + 出版社 + + + 图书的出版社。 + + + 出版者 + + + 最高评分 + + + 评分 + + + 不同来源对图书的评分。 + + + 来源 + + + 评分 + + + 票数 + + + 发行国家 + + + 发行国家的两位代码。 + + + 发行信息 + + + 发行版本 + + + 发行版本,例如原版。 + + + 移除 + + + 再发行日期 + + + 图书再次发行的日期。 + + + 再发行年份 + + + 图书再次发行的年份。 + + + 角色类别 + + + 角色 + + + 保存 + + + 无法保存图书。 + + + 螺旋装订 + + + 标签 + + + 图书的标签,以逗号分隔。 + + + 标题 + + + 图书的主标题。 + + + 贸易平装本 + + + 译者 + + + 用户 + + + 卷号 + + + 图书在其系列中的卷号。 + + + ISBN-13 + + + LCCN + + + Calibre + + + Apple Books ID + + + Open Library + + + Google Books + + + ASIN + + + ISBN-10 + + + Google Books ID + + + LibraryThing ID + + + Goodreads + + + Amazon + + + Barnes & Noble ID + + + Open Library ID + + + ISBN + + + 贡献者 + + + Goodreads ID + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx index b06b1dad..d927d760 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.ar-SA.resx @@ -1,4 +1,4 @@ - + +
@@ -48,7 +48,7 @@
- +
@@ -72,7 +72,7 @@
- +
@@ -95,7 +95,7 @@
- +
@@ -105,9 +105,10 @@ @section Scripts { +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml index a44592ef..dd8e3272 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml @@ -18,7 +18,7 @@
- + @@ -54,6 +54,7 @@ return String(value).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); } + // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const readerTitle = document.getElementById('reader-title'); const readerContent = document.getElementById('reader-content'); const readerStatus = document.getElementById('reader-status'); diff --git a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml index 74328465..a4afdc8d 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml @@ -16,8 +16,8 @@ @model UserSettingsDto -
-
+
+
@@ -52,7 +52,7 @@
@_localizer["DescriptionItemsPerPage"]
- +
: @@ -118,6 +118,7 @@ const cleanupFunctions = []; let isInitialized = false; + // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const form = document.getElementById('user-settings-form'); const checkboxIsPaginationEnabled = document.getElementById('IsPaginationEnabled'); const inputItemsPerPage = document.getElementById('ItemsPerPage');