Refactors the add book slice and shared media contributor model across the stack

This commit is contained in:
BinaryAlley committed 2026-09-12 12:12:22 -07:00
1 parent 3a2c80b615
commit 9a71a6d32b
61 files changed
+5223 -1384

No files matched your search

@@ -5,12 +5,11 @@ using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors;
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Repository entity for the participation of a media contributor in a book, carrying the role the contributor
/// played in that book. The role is tracked per participation, so that a single contributor can play multiple
/// roles in the same book, or different roles in different books.
/// Repository entity for the participation of a media contributor in a book, carrying the role the contributor played in that book.
/// The role is tracked per participation, so that a single contributor can play multiple roles in the same book, or different roles in different books.
/// </summary>
[DebuggerDisplay("BookId: {BookId} MediaContributorId: {MediaContributorId}")]
public class BookContributorEntity : IStorageEntity, IAuditableEntity
@@ -21,24 +20,19 @@ public class BookContributorEntity : IStorageEntity, IAuditableEntity
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the Id of the book the contributor participated in.
/// Gets the Id of the book the contributor participated in.
/// </summary>
public required Guid BookId { get; set; }
public required Guid BookId { get; init; }
/// <summary>
/// Gets or sets the Id of the media contributor.
/// Gets the Id of the media contributor.
/// </summary>
public required Guid MediaContributorId { get; set; }
public required Guid MediaContributorId { get; init; }
/// <summary>
/// Gets or sets the display name of the role the contributor played in the book.
/// Gets the role the contributor played in the book.
/// </summary>
public required string RoleName { get; set; }
/// <summary>
/// Gets or sets the canonical category of the role the contributor played in the book.
/// </summary>
public required MediaContributorRoleCategory RoleCategory { get; set; }
public required MediaContributorRole Role { get; init; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
@@ -58,5 +52,5 @@ public class BookContributorEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
public Guid? UpdatedBy { get; set; }
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
@@ -185,7 +184,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// <summary>
/// Gets or sets the Barnes & Noble ID of the book.
/// </summary>
public string? BarnesAndNobleId { get; set; } = null!;
public string? BarnesAndNobleId { get; set; }
/// <summary>
/// Gets or sets the Apple Books ID of the book.
@@ -3,6 +3,7 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -19,7 +20,7 @@ public interface IBookRepository : IRepository<BookEntity>,
IUpdateRepositoryAction<BookEntity>,
IGetByIdRepositoryAction<BookEntity, Guid>,
IGetAllRepositoryAction<BookEntity>,
IGetPaginatedRepositoryAction<BookEntity>
IGetAllLiteRepositoryAction<BookEntity, BookLiteRow>
{
/// <summary>
/// Gets all the books of the media library identified by <paramref name="libraryId"/>.
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Linq;
using AudioMediaContributorId = Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate.MediaContributorId;
using BookMediaContributorId = Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate.MediaContributorId;
#endregion
namespace Lumina.Application.Common.Mapping.MediaContributors;
/// <summary>
/// Extension methods for converting <see cref="MediaContributorReferenceDto"/>.
/// </summary>
public static class MediaContributorReferenceDtoMapping
{
/// <summary>
/// Converts <paramref name="dto"/> to a domain <see cref="BookMediaContributor"/>.
/// </summary>
/// <param name="dto">The data transfer object to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="BookMediaContributor"/>, or an error message.
/// </returns>
public static Result<BookMediaContributor> ToBookDomainEntity(this MediaContributorReferenceDto dto)
{
return BookMediaContributor.Create(BookMediaContributorId.Create(dto.ContributorId), dto.Role);
}
/// <summary>
/// Converts <paramref name="dtos"/> to a collection of <see cref="BookMediaContributor"/>.
/// </summary>
/// <param name="dtos">The DTOs to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a collection of converted <see cref="BookMediaContributor"/>, or an error message.
/// </returns>
public static IEnumerable<Result<BookMediaContributor>> ToBookDomainEntities(this IEnumerable<MediaContributorReferenceDto> dtos)
{
return dtos.Select(domainEntity => domainEntity.ToBookDomainEntity());
}
/// <summary>
/// Converts <paramref name="dto"/> to a domain <see cref="MusicMediaContributor"/>.
/// </summary>
/// <param name="dto">The data transfer object to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="MusicMediaContributor"/>, or an error message.
/// </returns>
public static Result<MusicMediaContributor> ToMusicDomainEntity(this MediaContributorReferenceDto dto)
{
return MusicMediaContributor.Create(AudioMediaContributorId.Create(dto.ContributorId), dto.Role);
}
/// <summary>
/// Converts <paramref name="dtos"/> to a collection of <see cref="MusicMediaContributor"/>.
/// </summary>
/// <param name="dtos">The DTOs to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a collection of converted <see cref="MusicMediaContributor"/>, or an error message.
/// </returns>
public static IEnumerable<Result<MusicMediaContributor>> ToMusicDomainEntities(this IEnumerable<MediaContributorReferenceDto> dtos)
{
return dtos.Select(domainEntity => domainEntity.ToMusicDomainEntity());
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaContributors;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Extension methods for converting <see cref="AddBookCommand"/>.
/// </summary>
public static class AddBookCommandMapping
{
/// <summary>
/// Converts <paramref name="command"/> to <see cref="Book"/>.
/// </summary>
/// <param name="command">The command to be converted.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="Book"/>, or an error message.
/// </returns>
public static Result<Book> ToDomainEntity(this AddBookCommand command, Guid libraryId)
{
IEnumerable<Result<BookRating>> domainRatingsResult = command.Ratings!.ToDomainEntities();
List<Error> errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors) ?? []];
if (errors.Count > 0)
return errors;
IEnumerable<Result<Isbn>> domainIsbnsResult = command.ISBNs!.ToDomainEntities();
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors) ?? []];
if (errors.Count > 0)
return errors;
Result<WrittenContentMetadata> metadataResult = command.Metadata!.ToDomainEntity();
if (metadataResult.IsFailure)
return metadataResult.Errors;
// TODO: update Api.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.
}
// Map the media contributors referenced by the user to their domain counterparts; a contributor is identified by its id and carries the role it played.
IEnumerable<Result<BookMediaContributor>> domainContributorsResult = command.Contributors!.ToBookDomainEntities();
errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors) ?? []];
if (errors.Count > 0)
return errors;
return Book.Create(
LibraryId.Create(libraryId),
command.Path,
metadataResult.Value,
Optional<BookFormat>.FromNullable(command.Format),
Optional<string>.FromNullable(command.Edition),
Optional<float>.FromNullable(command.VolumeNumber),
Optional<BookSeries>.FromNullable(bookSeries),
Optional<string>.FromNullable(command.ASIN),
Optional<string>.FromNullable(command.GoodreadsId),
Optional<string>.FromNullable(command.LCCN),
Optional<string>.FromNullable(command.OCLCNumber),
Optional<string>.FromNullable(command.OpenLibraryId),
Optional<string>.FromNullable(command.LibraryThingId),
Optional<string>.FromNullable(command.GoogleBooksId),
Optional<string>.FromNullable(command.BarnesAndNobleId),
Optional<string>.FromNullable(command.AppleBooksId),
[.. domainIsbnsResult.Select(isbn => isbn.Value)],
[.. domainContributorsResult.Select(domainContributor => domainContributor.Value)],
[.. domainRatingsResult.Select(domainRating => domainRating.Value)]
);
}
}
@@ -15,11 +15,12 @@ public static class AddBookRequestMapping
/// Converts <paramref name="request"/> to <see cref="AddBookCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="libraryId">The Id of the library the book is added to, taken from the route.</param>
/// <returns>The converted command.</returns>
public static AddBookCommand ToCommand(this AddBookRequest request)
public static AddBookCommand ToCommand(this AddBookRequest request, string? libraryId)
{
return new AddBookCommand(
request.LibraryId,
libraryId,
request.Path,
request.Metadata,
request.Format,
@@ -1,20 +1,21 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Responses.Common;
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.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
@@ -59,6 +60,16 @@ public static class BookEntityMapping
if (bookRatingResult.IsFailure)
return bookRatingResult.Errors;
List<BookMediaContributor> domainContributors = [];
foreach (BookContributorEntity bookContributor in repositoryEntity.BookContributors)
{
Result<BookMediaContributor> contributorResult = BookMediaContributor.Create(
MediaContributorId.Create(bookContributor.MediaContributorId), bookContributor.Role);
if (contributorResult.IsFailure)
return contributorResult.Errors;
domainContributors.Add(contributorResult.Value);
}
Result<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(repositoryEntity.OriginalReleaseDate),
Optional<int>.FromNullable(repositoryEntity.OriginalReleaseYear),
@@ -71,30 +82,20 @@ public static class BookEntityMapping
return releaseInfoResult.Errors;
Optional<LanguageInfo> languageInfo = Optional<LanguageInfo>.None();
if (repositoryEntity.LanguageCode is not null)
{
Result<LanguageInfo> languageInfoResult = LanguageInfo.Create(
if (repositoryEntity.LanguageCode is not null && repositoryEntity.LanguageName is not null)
languageInfo = LanguageInfo.Create(
repositoryEntity.LanguageCode,
repositoryEntity.LanguageName,
Optional<string>.FromNullable(repositoryEntity.LanguageNativeName)
);
if (languageInfoResult.IsFailure)
return languageInfoResult.Errors;
languageInfo = languageInfoResult.Value;
}
Optional<LanguageInfo> originalLanguageCode = Optional<LanguageInfo>.None();
if (repositoryEntity.OriginalLanguageCode is not null)
{
Result<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(
if (repositoryEntity.OriginalLanguageCode is not null && repositoryEntity.OriginalLanguageName is not null)
originalLanguageCode = LanguageInfo.Create(
repositoryEntity.OriginalLanguageCode,
repositoryEntity.OriginalLanguageName!,
repositoryEntity.OriginalLanguageName,
Optional<string>.FromNullable(repositoryEntity.OriginalLanguageNativeName)
);
if (originalLanguageInfoResult.IsFailure)
return originalLanguageInfoResult.Errors;
originalLanguageCode = originalLanguageInfoResult.Value;
}
Result<WrittenContentMetadata> writtenContentMetadataResult = WrittenContentMetadata.Create(
repositoryEntity.Title,
@@ -134,7 +135,7 @@ public static class BookEntityMapping
repositoryEntity.CreatedOnUtc,
Optional<DateTime>.FromNullable(repositoryEntity.UpdatedOnUtc),
[.. isbnsResult.Select(isbn => isbn.Value)],
[.. repositoryEntity.BookContributors.Select(bookContributor => MediaContributorId.Create(bookContributor.MediaContributorId))],
domainContributors,
[.. bookRatingsResult.Select(bookRating => bookRating.Value)]);
if (bookResult.IsFailure)
return bookResult.Errors;
@@ -218,7 +219,7 @@ public static class BookEntityMapping
repositoryEntity.BarnesAndNobleId,
repositoryEntity.AppleBooksId,
[.. repositoryEntity.ISBNs.ToResponses()],
null,
[.. repositoryEntity.BookContributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))],
[.. repositoryEntity.Ratings.ToResponses()],
repositoryEntity.MetadataStatus,
repositoryEntity.LastMetadataUpdateUtc,
@@ -4,6 +4,7 @@ using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using System;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -57,9 +58,19 @@ public static class BookMapping
BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null,
AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null,
ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()],
BookContributors = [.. domainEntity.Contributors.Select(contributor => new BookContributorEntity
{
Id = Guid.NewGuid(),
BookId = domainEntity.Id.Value,
MediaContributorId = contributor.ContributorId.Value,
Role = contributor.Role,
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.Empty,
UpdatedBy = null
})],
Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()],
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.NewGuid(),
CreatedBy = Guid.Empty,
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : null,
};
@@ -58,22 +58,18 @@ public static class BookMetadataDtoMapping
return tagsErrors;
Optional<LanguageInfo> languageInfo = Optional<LanguageInfo>.None();
if (metadata.Language is not null)
{
Result<LanguageInfo> languageInfoResult = LanguageInfo.Create(metadata.Language.LanguageCode, metadata.Language.LanguageName, Optional<string>.FromNullable(metadata.Language.NativeName));
if (languageInfoResult.IsFailure)
return languageInfoResult.Errors;
languageInfo = languageInfoResult.Value;
}
if (metadata.Language is not null && metadata.Language.LanguageCode is not null && metadata.Language.LanguageName is not null)
languageInfo = LanguageInfo.Create(
metadata.Language.LanguageCode,
metadata.Language.LanguageName,
Optional<string>.FromNullable(metadata.Language.NativeName));
Optional<LanguageInfo> originalLanguageInfo = Optional<LanguageInfo>.None();
if (metadata.OriginalLanguage is not null)
{
Result<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(metadata.OriginalLanguage.LanguageCode, metadata.OriginalLanguage.LanguageName, Optional<string>.FromNullable(metadata.OriginalLanguage.NativeName));
if (originalLanguageInfoResult.IsFailure)
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
if (metadata.OriginalLanguage is not null && metadata.OriginalLanguage.LanguageCode is not null && metadata.OriginalLanguage.LanguageName is not null)
originalLanguageInfo = LanguageInfo.Create(
metadata.OriginalLanguage.LanguageCode,
metadata.OriginalLanguage.LanguageName,
Optional<string>.FromNullable(metadata.OriginalLanguage.NativeName));
Result<WrittenContentMetadata> writtenContentMetadataResult = WrittenContentMetadata.Create(
metadata.Title,
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
@@ -14,7 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <summary>
/// Command for adding a book.
/// </summary>
/// <param name="LibraryId">The Id of the media library this book belongs to.</param>
/// <param name="LibraryId">The unique identifier of the media library this book belongs to, taken from the route.</param>
/// <param name="Path">The file system path of the book.</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>
@@ -35,7 +35,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary
/// <param name="Ratings">The list of ratings for this book.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record AddBookCommand(
Guid LibraryId,
string? LibraryId,
string Path,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
@@ -52,6 +52,6 @@ public record AddBookCommand(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
) : ICommand;
@@ -1,6 +1,7 @@
#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;
@@ -8,24 +9,17 @@ 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.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
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.Common;
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.AddBook;
@@ -39,6 +33,7 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<AddBookCommand> _validator;
private readonly IPathService _pathService;
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandHandler"/> class.
@@ -47,12 +42,14 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
/// <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, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<AddBookCommand> validator)
/// <param name="pathService">Injected service for file system path related functionality.</param>
public AddBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<AddBookCommand> validator, IPathService pathService)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_validator = validator;
_pathService = pathService;
}
/// <summary>
@@ -75,163 +72,75 @@ public class AddBookCommandHandler : ICommandHandler<AddBookCommand, Result<Book
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// The validator guarantees that the library id of the route is a non-empty Guid before this point.
Guid libraryId = Guid.Parse(command.LibraryId!);
// 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);
userId, new LibraryOwnershipPolicyContext(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.
}
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.
List<Error> errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)];
if (errors.Count != 0) // if there are errors, return them
return errors;
// A book is only readable if it is stored inside one of the content locations of its library, so a client can never register an entry that points the reading pipeline at an arbitrary file of the host.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
List<BookRating> domainRatings = [.. domainRatingsResult.Select(rating => rating.Value)];
if (!getLibraryResult.Value.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path, contentLocation.Path)))
return DomainErrors.WrittenContent.BookPathMustBeWithinLibraryContentLocations;
List<Result<Genre>> domainGenresResult = command.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!));
errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)];
if (errors.Count != 0)
return errors;
List<Genre> domainGenres = [.. domainGenresResult.Select(genre => genre.Value)];
// Media contributors are referenced by Id and are never created implicitly by adding a book, so each one must already exist.
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
List<Result<Tag>> domainTagsResult = command.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!));
errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)];
if (errors.Count != 0)
return errors;
List<Tag> domainTags = [.. domainTagsResult.Select(tag => tag.Value)];
List<Result<Isbn>> domainIsbnsResult = command.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!));
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)];
if (errors.Count != 0)
return errors;
List<Isbn> domainIsbns = [.. domainIsbnsResult.Select(isbn => isbn.Value)];
Result<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(command.Metadata.ReleaseInfo!.OriginalReleaseDate),
Optional<int>.FromNullable(command.Metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(command.Metadata.ReleaseInfo.ReReleaseDate),
Optional<int>.FromNullable(command.Metadata.ReleaseInfo.ReReleaseYear),
Optional<ReleaseCountry>.FromNullable(command.Metadata.ReleaseInfo!.ReleaseCountry),
Optional<string>.FromNullable(command.Metadata.ReleaseInfo.ReleaseVersion)
);
if (releaseInfoResult.IsFailure)
return releaseInfoResult.Errors;
ReleaseInfo releaseInfo = releaseInfoResult.Value;
LanguageInfo? languageInfo = null;
if (command.Metadata.Language is not null)
{
Result<LanguageInfo> languageInfoResult = LanguageInfo.Create(
command.Metadata.Language.LanguageCode!,
command.Metadata.Language.LanguageName!,
Optional<string>.FromNullable(command.Metadata.Language.NativeName));
if (languageInfoResult.IsFailure)
return languageInfoResult.Errors;
languageInfo = languageInfoResult.Value;
}
LanguageInfo? originalLanguageInfo = null;
if (command.Metadata.OriginalLanguage is not null)
{
Result<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(
command.Metadata.OriginalLanguage.LanguageCode!,
command.Metadata.OriginalLanguage.LanguageName!,
Optional<string>.FromNullable(command.Metadata.OriginalLanguage.NativeName));
if (originalLanguageInfoResult.IsFailure)
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
Result<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
command.Metadata.Title!,
Optional<string>.FromNullable(command.Metadata.OriginalTitle),
Optional<string>.FromNullable(command.Metadata.Description),
releaseInfo,
domainGenres,
domainTags,
Optional<LanguageInfo>.FromNullable(languageInfo),
Optional<LanguageInfo>.FromNullable(originalLanguageInfo),
Optional<string>.FromNullable(command.Metadata.Publisher),
Optional<int>.FromNullable(command.Metadata.PageCount)
);
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,
metadataResult.Value,
Optional<BookFormat>.FromNullable(command.Format),
Optional<string>.FromNullable(command.Edition),
command.VolumeNumber ?? default,
Optional<BookSeries>.FromNullable(bookSeries),
Optional<string>.FromNullable(command.ASIN),
Optional<string>.FromNullable(command.GoodreadsId),
Optional<string>.FromNullable(command.LCCN),
Optional<string>.FromNullable(command.OCLCNumber),
Optional<string>.FromNullable(command.OpenLibraryId),
Optional<string>.FromNullable(command.LibraryThingId),
Optional<string>.FromNullable(command.GoogleBooksId),
Optional<string>.FromNullable(command.BarnesAndNobleId),
Optional<string>.FromNullable(command.AppleBooksId),
domainIsbns,
contributorIds,
ratings: domainRatings
);
// Convert the command to a domain aggregate to enforce invariants, then persist it in the repository.
Result<Book> createBookResult = command.ToDomainEntity(libraryId);
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);
Result<Created> insertBookResult = await _unitOfWork.BookRepository.InsertAsync(createBookResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsFailure)
return insertBookResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return persistenceBook.ToResponse() with { Contributors = command.Contributors };
// The pre-insert checks handle the common cases; a concurrent request could still persist a book at the same path of the same
// library between them and the save, in which case the persistence medium reports the unique constraint violation as a conflict.
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
// Returns the book as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save.
Result<BookEntity?> getPersistedBookResult = await _unitOfWork.BookRepository.GetByIdAsync(createBookResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPersistedBookResult.IsFailure)
return getPersistedBookResult.Errors;
if (getPersistedBookResult.Value is null)
return DomainErrors.WrittenContent.BookNotFound;
return getPersistedBookResult.Value.ToResponse();
}
/// <summary>
/// Gets the media contributors referenced by <paramref name="command"/>, requiring each referenced Id to already exist.
/// </summary>
/// <param name="command">The command carrying the referenced media contributors.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the existing media contributors, or an error when at least one referenced contributor does not exist.
/// </returns>
private async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetExistingContributorsAsync(AddBookCommand command, CancellationToken cancellationToken)
{
List<Guid> contributorIds = [.. command.Contributors!.Select(contributor => contributor.ContributorId).Distinct()];
if (contributorIds.Count == 0)
return Result.From<IReadOnlyList<MediaContributorEntity>>([]);
Result<IReadOnlyList<MediaContributorEntity>> getContributorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false);
if (getContributorsResult.IsFailure)
return getContributorsResult.Errors;
if (getContributorsResult.Value.Count != contributorIds.Count)
return DomainErrors.MediaContributor.MediaContributorNotFound;
return Result.From(getContributorsResult.Value);
}
}
@@ -18,22 +18,31 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
/// </summary>
public AddBookCommandValidator()
{
// Validates the identifier of the media library that will own the book, taken from the route.
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull)
.Must(id => id != Guid.Empty)
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull);
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
// Validates the file system path of the book.
RuleFor(command => command.Path)
.NotEmpty()
.WithError(Errors.WrittenContent.BookPathCannotBeEmpty);
.WithError(Errors.WrittenContent.BookPathCannotBeEmpty)
.MaximumLength(2048)
.WithError(Errors.WrittenContent.BookPathMustBeMaximum2048CharactersLong);
// Validates the metadata of the book: title, lengths, release information, languages, genres and tags.
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotNull()
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
@@ -130,7 +139,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
@@ -148,7 +157,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty().WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.Length(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
@@ -175,6 +184,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
.WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero);
});
// Validates the physical characteristics of the book: format, edition and volume number.
RuleFor(command => command.Format)
.IsInEnum()
.When(command => command.Format is not null)
@@ -190,6 +200,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
.When(command => command.VolumeNumber.HasValue)
.WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero);
// Validates the series the book is part of, when the request carries one.
RuleFor(command => command.Series)
.ChildRules(series =>
series.RuleFor(s => s!.Title)
@@ -199,6 +210,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong))
.When(command => command.Series is not null);
// Validates the external identifiers of the book.
RuleFor(command => command.ASIN)
.Length(10)
.When(command => command.ASIN is not null)
@@ -249,6 +261,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
.When(command => command.AppleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat);
// Validates the ISBN list of the book.
RuleFor(command => command.ISBNs)
.NotNull()
.WithError(Errors.WrittenContent.IsbnListCannotBeNull);
@@ -274,49 +287,27 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
.IsInEnum()
.WithError(Errors.WrittenContent.UnknownIsbnFormat);
});
// Validates the media contributors that contributed to the book.
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
.WithError(Errors.WrittenContent.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.Name)
.NotNull()
.WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty)
.ChildRules(name =>
{
name.RuleFor(n => n!.DisplayName)
.NotNull()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.NotEmpty()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.MaximumLength(100)
.WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong);
name.RuleFor(n => n!.LegalName)
.MaximumLength(100)
.When(n => n!.LegalName is not null)
.WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong);
});
contributor.RuleFor(c => c.ContributorId)
.NotEmpty()
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty)
.Must(contributorId => contributorId != Guid.Empty)
.WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
contributor.RuleFor(c => c.Role)
.NotNull()
.WithError(Errors.MediaContributor.ContributorRoleCannotBeNull)
.ChildRules(role =>
{
role.RuleFor(r => r!.Name)
.NotEmpty()
.WithError(Errors.MediaContributor.RoleNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
role.RuleFor(r => r!.Category)
.NotEmpty()
.WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
});
.IsInEnum()
.WithError(Errors.MediaContributor.UnknownMediaContributorRole);
});
// Validates the ratings of the book.
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Diagnostics;
#endregion
@@ -8,9 +9,9 @@ namespace Lumina.Contracts.DTO.MediaContributors;
/// Data transfer object for a media contributor.
/// </summary>
/// <param name="Name">The name details of the media contributor, including display and legal names.</param>
/// <param name="Role">The role details of the media contributor, including the role name and category.</param>
/// <param name="Role">The canonical role of the media contributor in the media item, used as the key of its localized display string.</param>
[DebuggerDisplay("Name: {Name}, Role: {Role}")]
public record MediaContributorDto(
MediaContributorNameDto? Name,
MediaContributorRoleDto? Role
MediaContributorRole? Role
);
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.DTO.MediaContributors;
/// <summary>
/// Data transfer object for the reference to a media contributor in a media item, carrying the role the contributor played.
/// </summary>
/// <param name="ContributorId">The unique identifier of the media contributor.</param>
/// <param name="Role">The role the contributor played.</param>
[DebuggerDisplay("{ContributorId} - {Role}")]
public record MediaContributorReferenceDto(
Guid ContributorId,
MediaContributorRole Role
);
@@ -1,17 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.DTO.MediaContributors;
/// <summary>
/// Data transfer object for the role of a media contributor in a media item.
/// </summary>
/// <param name="Name">The display name of the role assigned to the media contributor.</param>
/// <param name="Category">The canonical category of the role.</param>
[DebuggerDisplay("Name: {Name}, Category: {Category}")]
public record MediaContributorRoleDto(
string? Name,
MediaContributorRoleCategory? Category
);
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -13,8 +13,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// <summary>
/// Represents a request to add a book.
/// </summary>
/// <param name="LibraryId">The Id of the media library this book belongs to. Required.</param>
/// <param name="Path">The file system path of the book. Required.</param>
/// <param name="Path">The file system path of the book. It must be inside one of the content locations of the media library that owns it. Required.</param>
/// <param name="Metadata">Written content metadata of the book. Required.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback). Optional.</param>
/// <param name="Edition">The edition of the book. Optional.</param>
@@ -30,11 +29,10 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// <param name="BarnesAndNobleId">The Barnes & Noble Id of the book. Optional.</param>
/// <param name="AppleBooksId">The Apple Books Id of the book. Optional.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book. Required.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book. Required.</param>
/// <param name="Contributors">The list of media contributors of the book. Required.</param>
/// <param name="Ratings">The list of ratings for this book. Required.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record AddBookRequest(
Guid LibraryId,
string Path,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
@@ -51,6 +49,6 @@ public record AddBookRequest(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
);
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -31,7 +31,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibr
/// <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="Contributors">The list of references to the media contributors that contributed to this book, each with the role they played.</param>
/// <param name="Ratings">The list of ratings for this book.</param>
/// <param name="MetadataStatus">The status of the metadata enrichment of the book.</param>
/// <param name="LastMetadataUpdateUtc">The date and time when the metadata of the book was last enriched, if applicable.</param>
@@ -59,7 +59,7 @@ public record BookResponse(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings,
MetadataStatus MetadataStatus,
DateTime? LastMetadataUpdateUtc,
@@ -227,7 +227,8 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
.HasDefaultValue(null)
.HasColumnOrder(35);
builder.HasIndex(book => new { book.LibraryId, book.Path });
builder.HasIndex(book => new { book.LibraryId, book.Path })
.IsUnique(); // the same physical book on disk cannot appear twice in the same library
builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus });
}
}
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
@@ -22,40 +22,36 @@ public class BookContributorConfiguration : IEntityTypeConfiguration<BookContrib
builder.Property(bookContributor => bookContributor.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(bookContributor => bookContributor.BookId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(bookContributor => bookContributor.MediaContributorId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(bookContributor => bookContributor.RoleName)
.IsRequired()
.HasMaxLength(100)
.HasColumnOrder(3);
builder.Property(bookContributor => bookContributor.RoleCategory)
.IsRequired()
builder.Property(bookContributor => bookContributor.Role)
.HasConversion<string>()
.HasMaxLength(50)
.HasColumnOrder(4);
.IsRequired()
.HasColumnOrder(3);
// audit
builder.Property(bookContributor => bookContributor.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(5);
.HasColumnOrder(4);
builder.Property(bookContributor => bookContributor.CreatedBy)
.IsRequired()
.HasColumnOrder(6);
.HasColumnOrder(5);
builder.Property(bookContributor => bookContributor.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(7);
.HasColumnOrder(6);
builder.Property(bookContributor => bookContributor.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(8);
.HasColumnOrder(7);
builder.HasIndex(bookContributor => new { bookContributor.BookId, bookContributor.MediaContributorId });
builder.HasIndex(bookContributor => new { bookContributor.BookId, bookContributor.MediaContributorId, bookContributor.Role })
.IsUnique();
builder.HasIndex(bookContributor => bookContributor.MediaContributorId);
}
}
@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsUniqueBookLibraryIdPathIndex : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Books_LibraryId_Path",
table: "Books");
migrationBuilder.CreateIndex(
name: "IX_Books_LibraryId_Path",
table: "Books",
columns: new[] { "LibraryId", "Path" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Books_LibraryId_Path",
table: "Books");
migrationBuilder.CreateIndex(
name: "IX_Books_LibraryId_Path",
table: "Books",
columns: new[] { "LibraryId", "Path" });
}
}
}
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Specifications;
using Lumina.DataAccess.Core.Repositories.Books.Specifications;
@@ -58,6 +59,11 @@ internal sealed class BookRepository : IBookRepository
if (bookExists)
return Errors.WrittenContent.BookAlreadyExists;
// A book is unique within its library by its file system path, so the same file can never be registered twice in the same library.
bool bookPathExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.LibraryId == book.LibraryId && repositoryBook.Path == book.Path, cancellationToken: cancellationToken).ConfigureAwait(false);
if (bookPathExists)
return Errors.WrittenContent.BookAlreadyExists;
// Fetch existing tags and genres.
List<TagEntity> existingTags = await _luminaDbContext.Set<TagEntity>()
.Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name))
@@ -81,54 +87,52 @@ internal sealed class BookRepository : IBookRepository
/// <param name="id">The Id of the book to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="BookEntity"/>, or an error.</returns>
public async Task<Result<BookEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<BookEntity?>> GetByIdAsync(Guid id, bool includeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
return await _luminaDbContext.Books
.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);
IQueryable<BookEntity> query = _luminaDbContext.Books;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (includeNavigationProperties)
{
query = query
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork);
}
return await query.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all books.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="BookEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<BookEntity>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Books
.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);
}
/// <summary>
/// Gets paginated books.
/// Gets paginated books, or all the books of the matching filters when the pagination data is <see langword="null"/>.
/// </summary>
/// <typeparam name="TFilter">The type of the filter used for filtering the data.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching books are returned.</param>
/// <param name="sortBy">The name of the fields by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="includeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{BookEntity}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<BookEntity>>> GetPaginatedAsync<TFilter>(PaginationDataDto? paginationData, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
public async Task<Result<PaginatedResultDto<BookEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool includeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
IQueryable<BookEntity> booksQuery = _luminaDbContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookArtwork)
.AsNoTracking();
IQueryable<BookEntity> booksQuery = _luminaDbContext.Books;
if (!shouldTrackEntities)
booksQuery = booksQuery.AsNoTracking();
if (includeNavigationProperties)
{
booksQuery = booksQuery
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork);
}
// Books should always be retrieved only per owning libraries.
if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty)
@@ -178,6 +182,80 @@ internal sealed class BookRepository : IBookRepository
};
}
/// <summary>
/// Gets paginated lightweight read models of the books of the media library identified by the provided <paramref name="filterModel"/>,
/// or all of them when the pagination data is <see langword="null"/>, projecting only the fields needed to display the books in a grid or a list.
/// </summary>
/// <typeparam name="TFilter">The type of the filter used for filtering the data.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching books are returned.</param>
/// <param name="sortBy">The name of the fields by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{BookLiteRow}"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<BookLiteRow>>> GetAllLiteAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
// Books should always be retrieved only per owning libraries.
if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty)
return Errors.Library.FilterMustIncludeLibraryId;
// The lightweight read models are always retrieved without tracking, because they are never modified by the caller.
IQueryable<BookEntity> booksQuery = _luminaDbContext.Books
.AsNoTracking()
.Where(book => book.LibraryId == libraryFilter.LibraryId);
FilterSpecification<BookEntity>? filterSpecification = BuildFilterSpecification(libraryFilter);
if (filterSpecification is not null)
booksQuery = booksQuery.Where(filterSpecification.ToExpression());
// Apply sorting based on the specified sortBy and sortOrder parameters.
booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker);
IQueryable<BookLiteRow> liteRowsQuery = booksQuery.Select(book => new BookLiteRow
{
Id = book.Id,
Title = book.Title,
ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear,
CoverPath = book.BookArtwork
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.Select(artwork => artwork.FileName)
.FirstOrDefault()
});
// If no pagination was requested, return all the books of the library.
if (paginationData is null)
{
IReadOnlyList<BookLiteRow> allBooks = await liteRowsQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<BookLiteRow>
{
Data = allBooks,
CurrentPage = 1,
PerPage = allBooks.Count,
Count = allBooks.Count,
NumberOfPages = 1
};
}
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.
// Apply pagination.
IReadOnlyList<BookLiteRow> paginatedResult = await liteRowsQuery
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<BookLiteRow>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Gets all the books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
@@ -190,6 +268,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork)
.Where(book => book.LibraryId == libraryId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
@@ -353,7 +432,7 @@ internal sealed class BookRepository : IBookRepository
public async Task<Result<IReadOnlyDictionary<Guid, string?>>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection<Guid> bookIds, CancellationToken cancellationToken)
{
List<AuthorRow> authorRows = await _luminaDbContext.BookContributors
.Where(bookContributor => bookIds.Contains(bookContributor.BookId) && bookContributor.RoleCategory == MediaContributorRoleCategory.Author)
.Where(bookContributor => bookIds.Contains(bookContributor.BookId) && bookContributor.Role == MediaContributorRole.Author)
.Join(_luminaDbContext.MediaContributors,
bookContributor => bookContributor.MediaContributorId,
contributor => contributor.Id,
@@ -404,6 +483,7 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.BookContributors)
.Include(book => book.BookArtwork)
.FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundBook is null)
return Errors.WrittenContent.BookNotFound;
@@ -447,6 +527,8 @@ internal sealed class BookRepository : IBookRepository
foundBook.Ratings.AddRange(data.Ratings);
foundBook.BookContributors.Clear();
foundBook.BookContributors.AddRange(data.BookContributors);
foundBook.BookArtwork.Clear();
foundBook.BookArtwork.AddRange(data.BookArtwork);
return Result.Updated;
}
@@ -0,0 +1,180 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
/// <summary>
/// Enumeration for the role of a media contributor in a media item.
/// The role is used as the key of the localized display strings of the UI, and normalizes the free-form role names
/// returned by the metadata providers, so that roles that describe the same kind of contribution, like "Author" and
/// "Writer", are never treated as distinct.
/// </summary>
[DebuggerDisplay("{ToString()}")]
public enum MediaContributorRole
{
/// <summary>
/// The role does not fall into any of the known roles.
/// </summary>
Other,
/// <summary>
/// The contributor wrote the media item, like a book, a movie, or a piece of music.
/// </summary>
Author,
/// <summary>
/// The contributor translated the media item into another language.
/// </summary>
Translator,
/// <summary>
/// The contributor created the illustrations of the media item.
/// </summary>
Illustrator,
/// <summary>
/// The contributor published the media item.
/// </summary>
Publisher,
/// <summary>
/// The contributor narrated the media item.
/// </summary>
Narrator,
/// <summary>
/// The contributor played a role in a filmed media item.
/// </summary>
Actor,
/// <summary>
/// The contributor directed a filmed media item.
/// </summary>
Director,
/// <summary>
/// The contributor wrote the screenplay of a filmed media item.
/// </summary>
Screenwriter,
/// <summary>
/// The contributor wrote the music of the media item.
/// </summary>
Composer,
/// <summary>
/// The contributor wrote the lyrics of the media item.
/// </summary>
Lyricist,
/// <summary>
/// The contributor arranged the music of the media item.
/// </summary>
Arranger,
/// <summary>
/// The contributor conducted the ensemble performing the media item.
/// </summary>
Conductor,
/// <summary>
/// The contributor oversaw the production of the media item.
/// </summary>
Producer,
/// <summary>
/// The contributor oversaw the overall production of the media item, rather than a single track or episode.
/// </summary>
ExecutiveProducer,
/// <summary>
/// The contributor operated the recording equipment during the production of the media item.
/// </summary>
Engineer,
/// <summary>
/// The contributor mixed the audio of the media item.
/// </summary>
Mixer,
/// <summary>
/// The contributor created a remix of the media item.
/// </summary>
Remixer,
/// <summary>
/// The contributor released the media item under a record label.
/// </summary>
RecordLabel,
/// <summary>
/// The contributor sang the media item.
/// </summary>
Vocals,
/// <summary>
/// The contributor sang the backing vocals of the media item.
/// </summary>
BackingVocals,
/// <summary>
/// The contributor played the guitar in the media item.
/// </summary>
Guitar,
/// <summary>
/// The contributor played the bass guitar in the media item.
/// </summary>
BassGuitar,
/// <summary>
/// The contributor played the drums in the media item.
/// </summary>
Drums,
/// <summary>
/// The contributor played percussion in the media item.
/// </summary>
Percussion,
/// <summary>
/// The contributor played the keyboards in the media item.
/// </summary>
Keyboards,
/// <summary>
/// The contributor played the piano in the media item.
/// </summary>
Piano,
/// <summary>
/// The contributor played the synthesizer in the media item.
/// </summary>
Synthesizer,
/// <summary>
/// The contributor played a string instrument in the media item.
/// </summary>
Strings,
/// <summary>
/// The contributor played a woodwind instrument in the media item.
/// </summary>
Woodwinds,
/// <summary>
/// The contributor played a brass instrument in the media item.
/// </summary>
Brass,
/// <summary>
/// The contributor sang in a choir in the media item.
/// </summary>
Choir,
/// <summary>
/// The contributor orchestrated the music of the media item.
/// </summary>
Orchestrator
}
@@ -1,99 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
/// <summary>
/// Enumeration for the canonical category of the role of a media contributor in a media item.
/// The category normalizes the free-form role names returned by the metadata providers, so that roles
/// that describe the same kind of contribution, like "Author" and "Writer", are never treated as distinct.
/// </summary>
[DebuggerDisplay("{ToString()}")]
public enum MediaContributorRoleCategory
{
/// <summary>
/// The role does not fall into any of the known categories.
/// </summary>
Other,
/// <summary>
/// The contributor created the media item, like a book, a movie, or a piece of music.
/// </summary>
Author,
/// <summary>
/// The contributor translated the media item into another language.
/// </summary>
Translator,
/// <summary>
/// The contributor created the illustrations of the media item.
/// </summary>
Illustrator,
/// <summary>
/// The contributor published the media item.
/// </summary>
Publisher,
/// <summary>
/// The contributor narrated the media item.
/// </summary>
Narrator,
/// <summary>
/// The contributor is credited as the artist of the media item.
/// </summary>
Artist,
/// <summary>
/// The contributor performed the media item, whether singing or playing an instrument.
/// </summary>
Performer,
/// <summary>
/// The contributor wrote the music of the media item.
/// </summary>
Composer,
/// <summary>
/// The contributor wrote the lyrics of the media item.
/// </summary>
Lyricist,
/// <summary>
/// The contributor oversaw the production of the media item.
/// </summary>
Producer,
/// <summary>
/// The contributor operated the recording equipment during the production of the media item.
/// </summary>
Engineer,
/// <summary>
/// The contributor conducted the ensemble performing the media item.
/// </summary>
Conductor,
/// <summary>
/// The contributor arranged the music of the media item.
/// </summary>
Arranger,
/// <summary>
/// The contributor mixed the audio of the media item.
/// </summary>
Mixer,
/// <summary>
/// The contributor created a remix of the media item.
/// </summary>
Remixer,
/// <summary>
/// The contributor released the media item under a record label.
/// </summary>
RecordLabel
}
@@ -11,7 +11,6 @@ public static partial class Errors
{
public static class MediaContributor
{
public static Error ContributorsListCannotBeNull => Error.Validation(description: nameof(ContributorsListCannotBeNull));
public static Error ContributorNameCannotBeEmpty => Error.Validation(description: nameof(ContributorNameCannotBeEmpty));
public static Error ContributorDisplayNameCannotBeEmpty => Error.Validation(description: nameof(ContributorDisplayNameCannotBeEmpty));
public static Error ContributorDisplayNameMustBeMaximum100CharactersLong => Error.Validation(description: nameof(ContributorDisplayNameMustBeMaximum100CharactersLong));
@@ -20,5 +19,8 @@ public static partial class Errors
public static Error RoleNameMustBeMaximum50CharactersLong => Error.Validation(description: nameof(RoleNameMustBeMaximum50CharactersLong));
public static Error RoleCategoryCannotBeEmpty => Error.Validation(description: nameof(RoleCategoryCannotBeEmpty));
public static Error ContributorRoleCannotBeNull => Error.Validation(description: nameof(ContributorRoleCannotBeNull));
public static Error MediaContributorIdCannotBeEmpty => Error.Validation(description: nameof(MediaContributorIdCannotBeEmpty));
public static Error MediaContributorNotFound => Error.NotFound(description: nameof(MediaContributorNotFound));
public static Error UnknownMediaContributorRole => Error.Validation(description: nameof(UnknownMediaContributorRole));
}
}
@@ -1,76 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the credit of a media contributor in a music media element, carrying the role the contributor played.
/// The role carries both a free-form display name, as returned by the metadata providers, and the canonical category
/// the display name normalizes to, so that roles describing the same kind of contribution are never treated as distinct.
/// </summary>
[DebuggerDisplay("{RoleDisplayName}")]
public sealed class MediaContributorCredit : ValueObject
{
/// <summary>
/// Gets the unique identifier of the credited media contributor.
/// </summary>
public MediaContributorId ContributorId { get; }
/// <summary>
/// Gets the display name of the role the contributor played.
/// </summary>
public string RoleDisplayName { get; }
/// <summary>
/// Gets the canonical category of the role the contributor played.
/// </summary>
public MediaContributorRoleCategory RoleCategory { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributorCredit"/> class.
/// </summary>
/// <param name="contributorId">The unique identifier of the credited media contributor.</param>
/// <param name="roleDisplayName">The display name of the role the contributor played.</param>
/// <param name="roleCategory">The canonical category of the role the contributor played.</param>
private MediaContributorCredit(MediaContributorId contributorId, string roleDisplayName, MediaContributorRoleCategory roleCategory)
{
ContributorId = contributorId;
RoleDisplayName = roleDisplayName;
RoleCategory = roleCategory;
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorCredit"/> class.
/// </summary>
/// <param name="contributorId">The unique identifier of the credited media contributor.</param>
/// <param name="roleDisplayName">The display name of the role the contributor played.</param>
/// <param name="roleCategory">The canonical category of the role the contributor played.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="MediaContributorCredit"/>, or an error message.
/// </returns>
public static Result<MediaContributorCredit> Create(MediaContributorId contributorId, string roleDisplayName, MediaContributorRoleCategory roleCategory)
{
if (string.IsNullOrWhiteSpace(roleDisplayName))
return Errors.Music.CreditRoleDisplayNameCannotBeEmpty;
return new MediaContributorCredit(contributorId, roleDisplayName, roleCategory);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return ContributorId;
yield return RoleDisplayName;
yield return RoleCategory;
}
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for a media contributor of a music media element, carrying the role the contributor played.
/// The media contributor is identified only by its Id, duplicated from the Media Contributor bounded context, and the role is
/// the canonical role the contributor played, used as the key of its localized display string.
/// </summary>
[DebuggerDisplay("{Role}")]
public sealed class MusicMediaContributor : ValueObject
{
/// <summary>
/// Gets the unique identifier of the media contributor.
/// </summary>
public MediaContributorId ContributorId { get; }
/// <summary>
/// Gets the role the contributor played.
/// </summary>
public MediaContributorRole Role { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaContributor"/> class.
/// </summary>
/// <param name="contributorId">The unique identifier of the media contributor.</param>
/// <param name="role">The role the contributor played.</param>
private MusicMediaContributor(MediaContributorId contributorId, MediaContributorRole role)
{
ContributorId = contributorId;
Role = role;
}
/// <summary>
/// Creates a new instance of the <see cref="MusicMediaContributor"/> class.
/// </summary>
/// <param name="contributorId">The unique identifier of the media contributor.</param>
/// <param name="role">The role the contributor played.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="MusicMediaContributor"/>, or an error message.
/// </returns>
public static Result<MusicMediaContributor> Create(MediaContributorId contributorId, MediaContributorRole role)
{
return new MusicMediaContributor(contributorId, role);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return ContributorId;
yield return Role;
}
}
@@ -1,65 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
/// <summary>
/// Value Object for the role of a media contributor in a media item.
/// The role carries both a free-form display name, as returned by the metadata providers, and the canonical
/// category the display name normalizes to, so that roles describing the same kind of contribution are never
/// treated as distinct.
/// </summary>
[DebuggerDisplay("{DisplayName}")]
public sealed class MediaContributorRole : ValueObject
{
/// <summary>
/// Gets the display name of the role.
/// </summary>
public string DisplayName { get; }
/// <summary>
/// Gets the canonical category of the role.
/// </summary>
public MediaContributorRoleCategory Category { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributorRole"/> class.
/// </summary>
/// <param name="displayName">The display name of the role.</param>
/// <param name="category">The canonical category of the role.</param>
private MediaContributorRole(string displayName, MediaContributorRoleCategory category)
{
DisplayName = displayName;
Category = category;
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorRole"/> class, from a display <paramref name="displayName"/> and its canonical <paramref name="category"/>.
/// </summary>
/// <param name="displayName">The display name of the role.</param>
/// <param name="category">The canonical category of the role.</param>
/// <returns>The created <see cref="MediaContributorRole"/> instance.</returns>
public static Result<MediaContributorRole> Create(string displayName, MediaContributorRoleCategory category)
{
if (string.IsNullOrWhiteSpace(displayName))
return Errors.MediaContributors.MediaContributorRoleNameCannotBeEmpty;
return new MediaContributorRole(displayName, category);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return DisplayName;
yield return Category;
}
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for a media contributor of a book, carrying the role the contributor played.
/// The media contributor is identified only by its Id, duplicated from the Media Contributor bounded context, and the role is
/// the canonical role the contributor played, used as the key of its localized display string.
/// </summary>
[DebuggerDisplay("{Role}")]
public sealed class BookMediaContributor : ValueObject
{
/// <summary>
/// Gets the unique identifier of the media contributor.
/// </summary>
public MediaContributorId ContributorId { get; }
/// <summary>
/// Gets the role the contributor played.
/// </summary>
public MediaContributorRole Role { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BookMediaContributor"/> class.
/// </summary>
/// <param name="contributorId">The unique identifier of the media contributor.</param>
/// <param name="role">The role the contributor played.</param>
private BookMediaContributor(MediaContributorId contributorId, MediaContributorRole role)
{
ContributorId = contributorId;
Role = role;
}
/// <summary>
/// Creates a new instance of the <see cref="BookMediaContributor"/> class.
/// </summary>
/// <param name="contributorId">The unique identifier of the media contributor.</param>
/// <param name="role">The role the contributor played.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="BookMediaContributor"/>, or an error message.
/// </returns>
public static Result<BookMediaContributor> Create(MediaContributorId contributorId, MediaContributorRole role)
{
return new BookMediaContributor(contributorId, role);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return ContributorId;
yield return Role;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
/// <summary>
/// Value Object for the Id of a media contributor, duplicated from the MediaContributor bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class MediaContributorId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributorId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private MediaContributorId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorId"/> class.
/// </summary>
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
public static MediaContributorId CreateUnique()
{
return new MediaContributorId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="MediaContributorId"/> instance.</param>
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
public static MediaContributorId Create(Guid value)
{
return new MediaContributorId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// API endpoint for the <c>/{libraryId}/books</c> route.
/// </summary>
public class AddBookEndpoint : BaseEndpoint<AddBookRequest, IResult>
{
@@ -48,7 +48,9 @@ public class AddBookEndpoint : BaseEndpoint<AddBookRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddBookRequest request, CancellationToken cancellationToken)
{
Result<BookResponse> result = await _addBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Books.ADD_BOOK}/{result.Value.Id}", result.Value), Problem);
// take unique identifiers from the route
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
Result<BookResponse> result = await _addBookCommandHandler.HandleAsync(request.ToCommand(libraryId), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1/libraries/{libraryId}/books/{result.Value.Id}", result.Value), Problem);
}
}
@@ -30,8 +30,7 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
Description = "Creates a new book and returns its details, including the location of the newly created resource.";
ExampleRequest = new AddBookRequest(
LibraryId: Guid.NewGuid(),
Path: "/books/the-fellowship-of-the-ring.epub",
Path: "/media/libraries/books/the-fellowship-of-the-ring.epub",
Metadata: new(
Title: "The Fellowship of the Ring",
OriginalTitle: "The Fellowship of the Ring",
@@ -95,24 +94,12 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
],
Contributors: [
new(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: MediaContributorRoleCategory.Author
)
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Author
),
new(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: MediaContributorRoleCategory.Illustrator
)
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Illustrator
)
],
Ratings: [
@@ -131,8 +118,7 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
]
);
RequestParam(r => 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.Path, "The file system path of the book. It must be inside one of the content locations of the media library that owns it. 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.");
@@ -159,8 +145,8 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
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 name, if the book is part of a series. Optional.");
RequestParam(r => r.Series!.Title, "The title of the book series. Required.");
RequestParam(r => r.Series, "The series the book is part of. Book series are not yet supported and are ignored. Optional.");
RequestParam(r => r.Series!.Title, "The title of the book series. Book series are not yet supported and are ignored. Optional.");
RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book. Optional.");
RequestParam(r => r.GoodreadsId, "The Goodreads Id of the book. Optional.");
RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book. Optional.");
@@ -171,7 +157,7 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
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 (actors, directors, etc) starring in this book. Required.");
RequestParam(r => r.Contributors, "The list of media contributors of the book. Required.");
RequestParam(r => r.Ratings, "The list of ratings for this book. Required.");
ResponseParam<BookResponse>(r => r.Id, "The unique identifier of the book.");
@@ -203,8 +189,8 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
ResponseParam<BookResponse>(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
ResponseParam<BookResponse>(r => r.Edition, "The edition of the book, if applicable.");
ResponseParam<BookResponse>(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
ResponseParam<BookResponse>(r => r.Series, "The series the book is part of, if applicable.");
ResponseParam<BookResponse>(r => r.Series!.Title, "The title of the series the book is part of.");
ResponseParam<BookResponse>(r => r.Series, "The series the book is part of. Book series are not yet supported and this is always null.");
ResponseParam<BookResponse>(r => r.Series!.Title, "The title of the series the book is part of. Book series are not yet supported and this is always null.");
ResponseParam<BookResponse>(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
ResponseParam<BookResponse>(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
@@ -215,7 +201,7 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
ResponseParam<BookResponse>(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
ResponseParam<BookResponse>(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
ResponseParam<BookResponse>(r => r.Contributors, "The list of media contributors starring in this book.");
ResponseParam<BookResponse>(r => r.Contributors, "The list of references to the media contributors that contributed to this book, each with the role they played.");
ResponseParam<BookResponse>(r => r.Ratings, "The list of ratings for the book.");
ResponseParam<BookResponse>(r => r.MetadataStatus, "The status of the metadata enrichment of the book.");
ResponseParam<BookResponse>(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable.");
@@ -228,7 +214,7 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
new BookResponse(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/the-fellowship-of-the-ring.epub",
Path: "/media/libraries/books/the-fellowship-of-the-ring.epub",
Metadata: new(
Title: "The Fellowship of the Ring",
OriginalTitle: "The Fellowship of the Ring",
@@ -294,24 +280,12 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
],
Contributors: [
new(
Name: new MediaContributorNameDto(
DisplayName: "J.R.R. Tolkien",
LegalName: "John Ronald Reuel Tolkien"
),
Role: new MediaContributorRoleDto(
Name: "author",
Category: MediaContributorRoleCategory.Author
)
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Author
),
new(
Name: new MediaContributorNameDto(
DisplayName: "Alan Lee",
LegalName: "Alan Lee"
),
Role: new MediaContributorRoleDto(
Name: "illustrator",
Category: MediaContributorRoleCategory.Illustrator
)
ContributorId: Guid.NewGuid(),
Role: MediaContributorRole.Illustrator
)
],
Ratings: [
@@ -346,16 +320,16 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/books"
detail = "Authentication failed",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
instance = "/api/v1/books"
detail = "The token has expired",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books"
},
new
{
@@ -363,7 +337,7 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/books"
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books"
}
}
);
@@ -375,11 +349,59 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
title = "General.Unauthorized",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/books",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
Response(404, "The request failed because the media library or one of the referenced media contributors does not exist.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "LibraryNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "MediaContributorNotFound",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
);
Response(409, "The request failed because a book with the same identity or path already exists.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "BookAlreadyExists",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
title = "General.Conflict",
status = 409,
detail = "UniqueConstraintViolation",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
@@ -387,14 +409,16 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/books",
instance = $"/api/v1/libraries/{Guid.NewGuid()}/books",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"BookLibraryCannotBeNull",
"LibraryIdCannotBeEmpty",
"BookPathCannotBeEmpty",
"BookPathMustBeMaximum2048CharactersLong",
"BookPathMustBeWithinLibraryContentLocations",
"MetadataCannotBeNull",
"TitleCannotBeEmpty",
"TitleMustBeMaximum255CharactersLong",
@@ -403,7 +427,6 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
"ReleaseInfoCannotBeNull",
"OriginalReleaseYearMustBeBetween1And9999",
"ReReleaseYearMustBeBetween1And9999",
"CountryCodeMustBe2CharactersLong",
"ReleaseVersionMustBeMaximum50CharactersLong",
"OriginalReleaseDateAndYearMustMatch",
"ReReleaseDateAndYearMustMatch",
@@ -442,14 +465,8 @@ public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
"InvalidIsbn10Format",
"UnknownIsbnFormat",
"ContributorsListCannotBeNull",
"ContributorNameCannotBeEmpty",
"ContributorDisplayNameCannotBeEmpty",
"ContributorDisplayNameMustBeMaximum100CharactersLong",
"ContributorLegalNameMustBeMaximum100CharactersLong",
"ContributorRoleCannotBeNull",
"RoleNameCannotBeEmpty",
"RoleNameMustBeMaximum50CharactersLong",
"RoleCategoryCannotBeEmpty",
"MediaContributorIdCannotBeEmpty",
"UnknownMediaContributorRole",
"RatingsListCannotBeNull",
"RatingValueMustBePositive",
"RatingValueCannotBeGreaterThanMaxValue",
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.MediaContributors;
using System.Diagnostics;
#endregion
@@ -16,7 +17,7 @@ public class MediaContributorDto
public MediaContributorNameDto? Name { get; set; }
/// <summary>
/// Gets the role of the contributor.
/// Gets the canonical role of the contributor, used as the key of its localized display string.
/// </summary>
public MediaContributorRoleDto? Role { get; set; }
public MediaContributorRole? Role { get; set; }
}
@@ -1,22 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.MediaContributors;
/// <summary>
/// Data transfer object for a media contributor role.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class MediaContributorRoleDto
{
/// <summary>
/// Gets the value representing this object.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Gets the category of this object.
/// </summary>
public string? Category { get; set; }
}
@@ -0,0 +1,175 @@
namespace Lumina.Presentation.Web.Common.Enums.MediaContributors;
/// <summary>
/// Enumeration for the role of a media contributor in a media item.
/// The role is used as the key of the localized display strings of the UI, and normalizes the free-form role names
/// returned by the metadata providers, so that roles that describe the same kind of contribution, like "Author" and
/// "Writer", are never treated as distinct.
/// </summary>
public enum MediaContributorRole
{
/// <summary>
/// The role does not fall into any of the known roles.
/// </summary>
Other,
/// <summary>
/// The contributor wrote the media item, like a book, a movie, or a piece of music.
/// </summary>
Author,
/// <summary>
/// The contributor translated the media item into another language.
/// </summary>
Translator,
/// <summary>
/// The contributor created the illustrations of the media item.
/// </summary>
Illustrator,
/// <summary>
/// The contributor published the media item.
/// </summary>
Publisher,
/// <summary>
/// The contributor narrated the media item.
/// </summary>
Narrator,
/// <summary>
/// The contributor played a role in a filmed media item.
/// </summary>
Actor,
/// <summary>
/// The contributor directed a filmed media item.
/// </summary>
Director,
/// <summary>
/// The contributor wrote the screenplay of a filmed media item.
/// </summary>
Screenwriter,
/// <summary>
/// The contributor wrote the music of the media item.
/// </summary>
Composer,
/// <summary>
/// The contributor wrote the lyrics of the media item.
/// </summary>
Lyricist,
/// <summary>
/// The contributor arranged the music of the media item.
/// </summary>
Arranger,
/// <summary>
/// The contributor conducted the ensemble performing the media item.
/// </summary>
Conductor,
/// <summary>
/// The contributor oversaw the production of the media item.
/// </summary>
Producer,
/// <summary>
/// The contributor oversaw the overall production of the media item, rather than a single track or episode.
/// </summary>
ExecutiveProducer,
/// <summary>
/// The contributor operated the recording equipment during the production of the media item.
/// </summary>
Engineer,
/// <summary>
/// The contributor mixed the audio of the media item.
/// </summary>
Mixer,
/// <summary>
/// The contributor created a remix of the media item.
/// </summary>
Remixer,
/// <summary>
/// The contributor released the media item under a record label.
/// </summary>
RecordLabel,
/// <summary>
/// The contributor sang the media item.
/// </summary>
Vocals,
/// <summary>
/// The contributor sang the backing vocals of the media item.
/// </summary>
BackingVocals,
/// <summary>
/// The contributor played the guitar in the media item.
/// </summary>
Guitar,
/// <summary>
/// The contributor played the bass guitar in the media item.
/// </summary>
BassGuitar,
/// <summary>
/// The contributor played the drums in the media item.
/// </summary>
Drums,
/// <summary>
/// The contributor played percussion in the media item.
/// </summary>
Percussion,
/// <summary>
/// The contributor played the keyboards in the media item.
/// </summary>
Keyboards,
/// <summary>
/// The contributor played the piano in the media item.
/// </summary>
Piano,
/// <summary>
/// The contributor played the synthesizer in the media item.
/// </summary>
Synthesizer,
/// <summary>
/// The contributor played a string instrument in the media item.
/// </summary>
Strings,
/// <summary>
/// The contributor played a woodwind instrument in the media item.
/// </summary>
Woodwinds,
/// <summary>
/// The contributor played a brass instrument in the media item.
/// </summary>
Brass,
/// <summary>
/// The contributor sang in a choir in the media item.
/// </summary>
Choir,
/// <summary>
/// The contributor orchestrated the music of the media item.
/// </summary>
Orchestrator
}