Adds book details and editing with cover uploads across the stack

This commit is contained in:
BinaryAlley committed 2026-09-06 09:37:23 -07:00
1 parent c2715dea2e
commit 1bfa07ba5d
103 files changed
+8782 -387

No files matched your search

@@ -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;
/// <summary>
/// Extension methods for converting <see cref="GetBookRequest"/>.
/// </summary>
public static class GetBookRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetBookQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetBookQuery ToQuery(this GetBookRequest request)
{
return new GetBookQuery(
Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="UpdateBookCommand"/>.
/// </summary>
public static class UpdateBookCommandMapping
{
/// <summary>
/// Converts <paramref name="command"/> to <see cref="BookMetadataDto"/>, so that the edited data can be applied to the domain book.
/// </summary>
/// <param name="command">The command containing the edited data of the book.</param>
/// <returns>The built metadata.</returns>
public static BookMetadataDto ToBookMetadataDto(this UpdateBookCommand command)
{
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
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="UpdateBookRequest"/>.
/// </summary>
public static class UpdateBookRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="UpdateBookCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
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
);
}
}
@@ -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
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken);
/// <summary>
/// Stores the artwork uploaded in the <paramref name="artworkStream"/> of the book into the internal media directory, and returns the relative path of the stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="authorName">The name of the author of the book.</param>
/// <param name="bookTitle">The title of the book.</param>
/// <param name="artworkStream">The stream of the uploaded artwork file.</param>
/// <param name="fileName">The name of the uploaded artwork file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
Task<Result<string>> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, Stream artworkStream, string fileName, CancellationToken cancellationToken);
/// <summary>
/// Deletes the artwork of the book from the internal media directory.
/// </summary>
@@ -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<AddBookCommand, Result<BookResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<AddBookCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public AddBookCommandHandler(IUnitOfWork unitOfWork, IValidator<AddBookCommand> validator)
public AddBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<AddBookCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
@@ -58,24 +68,31 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
if (validationResult.Count > 0)
return validationResult;
// TODO: update Api.Book.md documentation when the functionality is fully implemented
List<MediaContributorId> 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<ILibraryOwnershipPolicy>(
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<Result<BookRating>> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create(
rating.Value ?? default,
rating.MaxValue ?? default,
Optional<BookRatingSource>.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null),
Optional<int>.FromNullable(rating.VoteCount)));
// check if any of the results contain errors
// Check if any of the results contain errors.
List<Error> 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<AddBookCommand, Result<Book
);
if (metadataResult.IsFailure)
return metadataResult.Errors;
// Link the media contributors typed by the user to the book, finding or creating a single contributor per person; the same person
// can be credited under several roles, so every distinct display name must resolve to the same media contributor row.
List<MediaContributorId> contributorIds = [];
Dictionary<string, MediaContributorEntity> contributorsByDisplayName = [];
foreach (MediaContributorDto contributor in command.Contributors!)
{
if (contributor.Name?.DisplayName is null)
continue;
if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity))
{
Result<MediaContributorEntity> findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false);
if (findOrCreateResult.IsFailure)
return findOrCreateResult.Errors;
contributorEntity = findOrCreateResult.Value;
contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity);
}
contributorIds.Add(MediaContributorId.Create(contributorEntity.Id));
}
Result<Book> createBookResult = Book.Create(
LibraryId.Create(command.LibraryId),
command.Path,
@@ -171,12 +210,27 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
if (createBookResult.IsFailure)
return createBookResult.Errors;
// The participation rows need the generated id of the book, so they are built once the domain book exists.
BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity();
persistenceBook.CreatedBy = userId;
persistenceBook.BookContributors = [.. command.Contributors!
.Where(contributor => 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<Created> 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 };
}
}
@@ -104,15 +104,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
!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)
@@ -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;
/// <summary>
/// Command for updating an existing book.
/// </summary>
/// <param name="Id">The Id of the book to update.</param>
/// <param name="Metadata">Written content metadata of the book.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback), if applicable.</param>
/// <param name="Edition">The edition of the book, if applicable.</param>
/// <param name="VolumeNumber">The volume or book number in the series, if applicable.</param>
/// <param name="Series">The series name, if the book is part of a series.</param>
/// <param name="ASIN">The ASIN (Amazon Standard Identification Number) of the book, if applicable.</param>
/// <param name="GoodreadsId">The Goodreads ID of the book, if applicable.</param>
/// <param name="LCCN">The Library of Congress Control Number (LCCN) of the book, if applicable.</param>
/// <param name="OCLCNumber">The OCLC Number (WorldCat identifier) of the book, if applicable.</param>
/// <param name="OpenLibraryId">The Open Library ID of the book, if applicable.</param>
/// <param name="LibraryThingId">The LibraryThing ID of the book, if applicable.</param>
/// <param name="GoogleBooksId">The Google Books ID of the book, if applicable.</param>
/// <param name="BarnesAndNobleId">The Barnes & Noble ID of the book, if applicable.</param>
/// <param name="AppleBooksId">The Apple Books ID of the book, if applicable.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book.</param>
/// <param name="Ratings">The list of ratings for this book.</param>
[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<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<BookRatingDto>? Ratings
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to update an existing book.
/// </summary>
public class UpdateBookCommandHandler : ICommandHandler<UpdateBookCommand, Result<BookResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateBookCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateBookCommand> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update an existing book.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the updated <see cref="BookResponse"/>, or an error message.
/// </returns>
public async Task<Result<BookResponse>> HandleAsync(UpdateBookCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Get the existing book with all its related data.
Result<BookEntity?> 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<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// Convert the book to a domain object and apply the edited metadata to it.
Result<Book> getDomainBookResult = existingBook.ToDomainEntity();
if (getDomainBookResult.IsFailure)
return getDomainBookResult.Errors;
Book book = getDomainBookResult.Value;
Result<Success> applyMetadataResult = book.ApplyMetadata(command.ToBookMetadataDto());
if (applyMetadataResult.IsFailure)
return applyMetadataResult.Errors;
// Link the media contributors typed by the user to the book, finding or creating a single contributor per person.
List<BookContributorEntity> linkedContributors = [];
// A person can be credited under several roles in the same book; each distinct display name must resolve to the same media
// contributor row, otherwise the duplicate inserts would violate the unique display name constraint when the changes are saved.
Dictionary<string, MediaContributorEntity> contributorsByDisplayName = [];
foreach (MediaContributorDto contributor in command.Contributors!)
{
if (contributor.Name?.DisplayName is null)
continue;
if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity))
{
Result<MediaContributorEntity> findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false);
if (findOrCreateResult.IsFailure)
return findOrCreateResult.Errors;
contributorEntity = findOrCreateResult.Value;
contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity);
}
string roleName = contributor.Role?.Name ?? "Contributor";
MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other;
linkedContributors.Add(new BookContributorEntity
{
Id = Guid.NewGuid(),
BookId = existingBook.Id,
MediaContributorId = contributorEntity.Id,
RoleName = roleName,
RoleCategory = roleCategory,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = userId,
UpdatedBy = null
});
}
book.UpdateContributors([.. linkedContributors.Select(linkedContributor => MediaContributorId.Create(linkedContributor.MediaContributorId))]);
// 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<Updated> 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 };
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateBookCommand"/>.
/// </summary>
public class UpdateBookCommandValidator : AbstractValidator<UpdateBookCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCommandValidator"/> class.
/// </summary>
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);
});
}
}
@@ -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;
/// <summary>
/// Command for updating the cover image of an existing book.
/// </summary>
/// <param name="BookId">The Id of the book whose cover image is updated.</param>
/// <param name="Cover">The stream of the uploaded cover image file.</param>
/// <param name="FileName">The name of the uploaded cover image file.</param>
[DebuggerDisplay("BookId: {BookId} FileName: {FileName}")]
public record UpdateBookCoverCommand(
Guid BookId,
Stream? Cover,
string? FileName
) : ICommand;
@@ -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;
/// <summary>
/// Handler for the command to update the cover image of an existing book.
/// </summary>
public class UpdateBookCoverCommandHandler : ICommandHandler<UpdateBookCoverCommand, Result<string>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<UpdateBookCoverCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCoverCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="bookArtworkService">Injected service for storing the artwork of a book.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateBookCoverCommandHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<UpdateBookCoverCommand> validator)
{
_unitOfWork = unitOfWork;
_bookArtworkService = bookArtworkService;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the command to update the cover image of an existing book.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the relative path of the stored cover image, or an error message.
/// </returns>
public async Task<Result<string>> HandleAsync(UpdateBookCoverCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Get the existing book with its artwork.
Result<BookEntity?> 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<ILibraryOwnershipPolicy>(
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<LibraryEntity?> 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<string> 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;
}
/// <summary>
/// Gets the display name of the author of the <paramref name="book"/>, used to build the artwork storage path, or an empty string when the book has no author.
/// </summary>
/// <param name="book">The book whose author is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The display name of the author of the book, or an empty string.</returns>
private async Task<string> GetAuthorNameAsync(BookEntity book, CancellationToken cancellationToken)
{
IReadOnlyCollection<Guid> authorIds = [.. book.BookContributors
.Where(participation => participation.RoleCategory == MediaContributorRoleCategory.Author)
.Select(participation => participation.MediaContributorId)
.Distinct()];
if (authorIds.Count == 0)
return string.Empty;
Result<IReadOnlyList<MediaContributorEntity>> 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;
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateBookCoverCommand"/>.
/// </summary>
public class UpdateBookCoverCommandValidator : AbstractValidator<UpdateBookCoverCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCoverCommandValidator"/> class.
/// </summary>
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);
}
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
/// <summary>
/// Query for getting a book by its Id.
/// </summary>
/// <param name="Id">The Id of the book to get.</param>
public record GetBookQuery(
Guid Id
) : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get a book by its Id.
/// </summary>
public class GetBookQueryHandler : IQueryHandler<GetBookQuery, Result<BookResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetBookQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetBookQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetBookQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetBookQuery> validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get a book by its Id.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the requested <see cref="BookResponse"/>, or an error message.
/// </returns>
public async Task<Result<BookResponse>> HandleAsync(GetBookQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Get the book with the specified id from the repository.
Result<BookEntity?> 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<ILibraryOwnershipPolicy>(
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<MediaContributorEntity> contributors = await GetContributorsAsync(getBookResult.Value, cancellationToken).ConfigureAwait(false);
if (contributors.Count == 0)
return response;
Dictionary<Guid, MediaContributorEntity> contributorsById = contributors.ToDictionary(contributor => contributor.Id);
List<MediaContributorDto> 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 };
}
/// <summary>
/// Gets the media contributors linked to the book of <paramref name="book"/>, by their unique identifiers.
/// </summary>
/// <param name="book">The book whose media contributors are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the media contributors of the book, or an error.</returns>
private async Task<List<MediaContributorEntity>> GetContributorsAsync(BookEntity book, CancellationToken cancellationToken)
{
IReadOnlyCollection<Guid> contributorIds = [.. book.BookContributors.Select(participation => participation.MediaContributorId).Distinct()];
if (contributorIds.Count == 0)
return [];
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return [];
return [.. getContributorsResult.Value];
}
}
@@ -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;
/// <summary>
/// Validates the needed validation rules for <see cref="GetBookQuery"/>.
/// </summary>
public class GetBookQueryValidator : AbstractValidator<GetBookQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBookQueryValidator"/> class.
/// </summary>
public GetBookQueryValidator()
{
RuleFor(query => query.Id)
.NotEmpty()
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}