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

@@ -1,9 +1,9 @@
POST {{host}}/api/v1/books
POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books
Authorization: Bearer {{ACCESS_TOKEN}}
Content-Type: application/json
{
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/books/the-fellowship-of-the-ring.pdf",
"path": "/media/libraries/books/the-fellowship-of-the-ring.pdf",
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
@@ -13,7 +13,7 @@ Content-Type: application/json
"originalReleaseYear": 1954,
"reReleaseDate": "2001-09-06",
"reReleaseYear": 2001,
"releaseCountry": "uk",
"releaseCountry": "GB",
"releaseVersion": "50th Anniversary Edition"
},
"genres": [
@@ -56,31 +56,27 @@ Content-Type: application/json
"appleBooksId": "id395211",
"isbns": [
{
"value": "0395272238",
"format": "Isbn10"
"value": "0395272238",
"format": "Isbn10"
},
{
"value": "9780395272237",
"format": "Isbn13"
"value": "9780395272237",
"format": "Isbn13"
}
],
"contributors": [
{
"name": {
"displayName": "J.R.R. Tolkien"
},
"contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d",
"role": "Author"
},
{
"name": {
"displayName": "Alan Lee"
},
"contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e",
"role": "Illustrator"
}
],
"ratings": [
{
"source": "Goodreads",
"source": "GoogleBooks",
"value": 4.36,
"maxValue": 5,
"voteCount": 2345678
@@ -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
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
@@ -8,7 +8,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Fixture class for the <see cref="BookContributorEntity"/> class.
@@ -24,23 +24,20 @@ public class BookContributorEntityFixture
/// <param name="id">Optional. The Id of the participation.</param>
/// <param name="bookId">Optional. The Id of the book the contributor participated in.</param>
/// <param name="mediaContributorId">Optional. The Id of the media contributor.</param>
/// <param name="roleName">Optional. The display name of the role the contributor played in the book.</param>
/// <param name="roleCategory">Optional. The canonical category of the role the contributor played in the book.</param>
/// <param name="role">Optional. The role the contributor played in the book.</param>
/// <returns>The created <see cref="BookContributorEntity"/>.</returns>
public BookContributorEntity Create(
Guid? id = null,
Guid? bookId = null,
Guid? mediaContributorId = null,
string? roleName = null,
MediaContributorRoleCategory? roleCategory = null)
MediaContributorRole? role = null)
{
return new BookContributorEntity
{
Id = id ?? Guid.NewGuid(),
BookId = bookId ?? Guid.NewGuid(),
MediaContributorId = mediaContributorId ?? Guid.NewGuid(),
RoleName = roleName ?? _faker.Lorem.Word(),
RoleCategory = roleCategory ?? _faker.PickRandom<MediaContributorRoleCategory>(),
Role = role ?? MediaContributorRole.Author,
CreatedOnUtc = _faker.Date.Past(),
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = null,
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Contracts.DTO.MediaContributors;
@@ -11,6 +11,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
#endregion
@@ -24,7 +25,7 @@ public class AddBookCommandFixture
{
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
@@ -53,7 +54,7 @@ public class AddBookCommandFixture
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <returns>The created command to add a book.</returns>
public AddBookCommand Create(
Guid? libraryId = null,
string? libraryId = null,
string? path = null,
WrittenContentMetadataDto? metadata = null,
BookFormat? format = null,
@@ -70,7 +71,7 @@ public class AddBookCommandFixture
string? barnesAndNobleId = null,
string? appleBooksId = null,
List<IsbnDto>? isbns = null,
List<MediaContributorDto>? contributors = null,
List<MediaContributorReferenceDto>? contributors = null,
List<BookRatingDto>? ratings = null,
bool includeMetadata = true,
bool includeOptionalProperties = true)
@@ -97,8 +98,8 @@ public class AddBookCommandFixture
default!,
default!
))
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
.RuleFor(x => x.Path, f => path ?? f.System.FilePath())
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid().ToString())
.RuleFor(x => x.Path, f => path ?? Path.Combine(Path.GetTempPath(), "lumina-books", f.System.FileName()))
.RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null)
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
@@ -115,7 +116,7 @@ public class AddBookCommandFixture
.RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null))
.RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
}
/// <summary>
@@ -21,35 +21,27 @@ public class MediaContributorDtoFixture
/// Creates a random valid <see cref="MediaContributorDto"/>.
/// </summary>
/// <param name="displayName">Optional. The display name of the media contributor.</param>
/// <param name="roleName">Optional. The name of the role assigned to the media contributor.</param>
/// <param name="roleCategory">Optional. The category of the role.</param>
/// <param name="role">Optional. The canonical role assigned to the media contributor.</param>
/// <param name="legalName">Optional. The legal name of the media contributor.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDisplayName">Whether the display name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeLegalName">Whether the legal name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRole">Whether the role should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRoleName">Whether the role name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRoleCategory">Whether the role category should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="MediaContributorDto"/>.</returns>
public MediaContributorDto Create(
string? displayName = null,
string? roleName = null,
MediaContributorRoleCategory? roleCategory = null,
MediaContributorRole? role = null,
string? legalName = null,
bool includeName = true,
bool includeDisplayName = true,
bool includeLegalName = true,
bool includeRole = true,
bool includeRoleName = true,
bool includeRoleCategory = true)
bool includeRole = true)
{
return new MediaContributorDto(
Name: includeName ? new MediaContributorNameDto(
DisplayName: includeDisplayName ? displayName ?? _faker.Name.FullName() : null,
LegalName: includeLegalName ? legalName : null) : null,
Role: includeRole ? new MediaContributorRoleDto(
Name: includeRoleName ? roleName ?? _faker.Commerce.Department() : null,
Category: includeRoleCategory ? roleCategory ?? _faker.PickRandom<MediaContributorRoleCategory>() : null) : null);
Role: includeRole ? role ?? _faker.PickRandom<MediaContributorRole>() : null);
}
/// <summary>
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
/// <summary>
/// Fixture class for the <see cref="MediaContributorReferenceDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorReferenceDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="MediaContributorReferenceDto"/>.
/// </summary>
/// <param name="contributorId">Optional. The Id of the media contributor.</param>
/// <param name="role">Optional. The role the contributor played.</param>
/// <returns>The created <see cref="MediaContributorReferenceDto"/>.</returns>
public MediaContributorReferenceDto Create(Guid? contributorId = null, MediaContributorRole? role = null)
{
return new MediaContributorReferenceDto(
ContributorId: contributorId ?? Guid.NewGuid(),
Role: role ?? _faker.PickRandom<MediaContributorRole>());
}
/// <summary>
/// Creates a list of <see cref="MediaContributorReferenceDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<MediaContributorReferenceDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,44 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
/// <summary>
/// Fixture class for the <see cref="MediaContributorRoleDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorRoleDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="MediaContributorRoleDto"/>.
/// </summary>
/// <param name="name">Optional. The name of the role assigned to the media contributor.</param>
/// <param name="category">Optional. The category of the role.</param>
/// <returns>The created <see cref="MediaContributorRoleDto"/>.</returns>
public MediaContributorRoleDto Create(
string? name = null,
MediaContributorRoleCategory? category = null)
{
return new MediaContributorRoleDto(
name ?? _faker.Commerce.Department(),
category ?? _faker.PickRandom<MediaContributorRoleCategory>());
}
/// <summary>
/// Creates a list of <see cref="MediaContributorRoleDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<MediaContributorRoleDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
@@ -11,6 +11,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
#endregion
@@ -24,13 +25,12 @@ public class AddBookRequestFixture
{
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
/// Creates a random valid request to add a book.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
/// <param name="path">Optional. The file system path of the book.</param>
/// <param name="metadata">Optional. The written content metadata of the book.</param>
/// <param name="format">Optional. The format of the book.</param>
@@ -52,7 +52,6 @@ public class AddBookRequestFixture
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <returns>The created request to add a book.</returns>
public AddBookRequest Create(
Guid? libraryId = null,
string? path = null,
WrittenContentMetadataDto? metadata = null,
BookFormat? format = null,
@@ -69,13 +68,12 @@ public class AddBookRequestFixture
string? barnesAndNobleId = null,
string? appleBooksId = null,
List<IsbnDto>? isbns = null,
List<MediaContributorDto>? contributors = null,
List<MediaContributorReferenceDto>? contributors = null,
List<BookRatingDto>? ratings = null,
bool includeOptionalProperties = true)
{
return new Faker<AddBookRequest>()
.CustomInstantiator(f => new AddBookRequest(
default,
default!,
default!,
default,
@@ -95,8 +93,7 @@ public class AddBookRequestFixture
default!,
default!
))
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
.RuleFor(x => x.Path, f => path ?? f.System.FilePath())
.RuleFor(x => x.Path, f => path ?? Path.Combine(Path.GetTempPath(), "lumina-books", f.System.FileName()))
.RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create())
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
@@ -113,7 +110,7 @@ public class AddBookRequestFixture
.RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null))
.RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
}
/// <summary>
@@ -24,7 +24,7 @@ public class BookResponseFixture
private readonly Faker _faker = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly BookSeriesDtoFixture _bookSeriesDtoFixture = new();
@@ -70,7 +70,7 @@ public class BookResponseFixture
_faker.Random.AlphaNumeric(10),
_faker.Random.AlphaNumeric(8),
_isbnDtoFixture.CreateMany(1),
_mediaContributorDtoFixture.CreateMany(1),
_mediaContributorReferenceDtoFixture.CreateMany(1),
_bookRatingDtoFixture.CreateMany(1),
metadataStatus ?? _faker.PickRandom<MetadataStatus>(),
_faker.Date.Recent().ToUniversalTime(),
@@ -1,42 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
/// <summary>
/// Fixture class for the <see cref="MediaContributorRole"/> domain value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorRoleFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="MediaContributorRole"/>.
/// </summary>
/// <param name="name">Optional. The name of the role. If not provided, a random name is generated.</param>
/// <param name="category">Optional. The category of the role. If not provided, a random category is generated.</param>
/// <returns>The created <see cref="MediaContributorRole"/>.</returns>
public MediaContributorRole Create(string? name = null, MediaContributorRoleCategory? category = null)
{
return MediaContributorRole.Create(
name ?? _faker.Lorem.Word(),
category ?? _faker.PickRandom<MediaContributorRoleCategory>()).Value;
}
/// <summary>
/// Creates multiple <see cref="MediaContributorRole"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MediaContributorRole"/> instances.</returns>
public List<MediaContributorRole> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,14 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
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.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -27,7 +27,6 @@ public class BookFixture
private readonly WrittenContentMetadataFixture _writtenContentMetadataFixture = new();
private readonly IsbnFixture _isbnFixture = new();
private readonly BookRatingFixture _bookRatingFixture = new();
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="Book"/> domain aggregate.
@@ -70,7 +69,7 @@ public class BookFixture
string? barnesAndNobleId = null,
string? appleBooksId = null,
List<Isbn>? isbns = null,
List<MediaContributorId>? contributors = null,
List<BookMediaContributor>? contributors = null,
List<BookRating>? ratings = null)
{
return Book.Create(
@@ -91,7 +90,7 @@ public class BookFixture
barnesAndNobleId is null ? Optional<string>.Some(_faker.Random.String2(10, "0123456789")) : Optional<string>.Some(barnesAndNobleId),
appleBooksId is null ? Optional<string>.Some($"id{_faker.Random.Number(1, 999999)}") : Optional<string>.Some(appleBooksId),
isbns ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _isbnFixture.Create())],
contributors ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _mediaContributorIdFixture.Create())],
contributors ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => BookMediaContributor.Create(MediaContributorId.CreateUnique(), MediaContributorRole.Author).Value)],
ratings ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _bookRatingFixture.Create())]
).Value;
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
using Lumina.Presentation.Web.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -14,7 +15,6 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
[ExcludeFromCodeCoverage]
public class MediaContributorDtoFixture
{
private static readonly string[] RoleCategories = ["Author", "Translator", "Illustrator", "Editor", "Narrator"];
private readonly Faker _faker = new();
/// <summary>
@@ -22,16 +22,13 @@ public class MediaContributorDtoFixture
/// </summary>
/// <param name="displayName">Optional. The name by which the contributor is popularly known.</param>
/// <param name="legalName">Optional. The legal name of the contributor.</param>
/// <param name="roleName">Optional. The name of the role of the contributor.</param>
/// <param name="roleCategory">Optional. The category of the role of the contributor.</param>
/// <param name="role">Optional. The canonical role of the contributor.</param>
/// <returns>A configured <see cref="MediaContributorDto"/> instance.</returns>
public MediaContributorDto Create(
string? displayName = null,
string? legalName = null,
string? roleName = null,
string? roleCategory = null)
MediaContributorRole? role = null)
{
string resolvedRoleCategory = roleCategory ?? _faker.Random.ArrayElement(RoleCategories);
return new MediaContributorDto
{
Name = new MediaContributorNameDto
@@ -39,11 +36,7 @@ public class MediaContributorDtoFixture
DisplayName = displayName ?? _faker.Name.FullName(),
LegalName = legalName ?? _faker.Name.FullName()
},
Role = new MediaContributorRoleDto
{
Name = roleName ?? resolvedRoleCategory.ToLowerInvariant(),
Category = resolvedRoleCategory
}
Role = role ?? MediaContributorRole.Author
};
}
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
@@ -135,4 +136,58 @@ public class BookRepositoryTests
Assert.NotNull(keptArtwork);
Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status);
}
[Fact]
public async Task InsertAsync_WhenCalledWithAValidBook_ShouldPersistTheBook()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
BookEntity book = _bookEntityFixture.Create();
// Act
Result<Created> result = await sut.InsertAsync(book, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
BookEntity? storedBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
Assert.NotNull(storedBook);
Assert.Equal(book.Path, storedBook!.Path);
Assert.Equal(book.Title, storedBook.Title);
}
[Fact]
public async Task InsertAsync_WhenAnotherBookOfTheSameLibraryHasTheSamePath_ShouldReturnBookAlreadyExists()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity existingBook = _bookEntityFixture.Create();
existingBook.LibraryId = libraryId;
existingBook.Path = "/books/existing.epub";
context.Books.Add(existingBook);
await context.SaveChangesAsync();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.Path = "/books/existing.epub";
// Act
Result<Created> result = await sut.InsertAsync(book, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
}
}
@@ -1,7 +1,10 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
@@ -23,6 +26,7 @@ using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
@@ -59,8 +63,10 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly string _libraryContentLocation = Path.GetTempPath();
private Guid _libraryId;
/// <summary>
@@ -85,7 +91,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = dbContext.Users.Single(user => user.Username == _apiFactory.TestUsername).Id;
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: _libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: _libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [_libraryContentLocation]));
await dbContext.SaveChangesAsync();
}
@@ -187,7 +193,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// check Location header
Assert.NotNull(response.Headers.Location);
string locationUri = response.Headers.Location!.ToString();
Assert.EndsWith("/api/v1/books/" + bookResponse.Id.Value, locationUri);
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id.Value}", locationUri);
// extract ID from Location header and compare
string idFromHeader = locationUri.Split('/').Last();
@@ -1107,130 +1113,39 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
public async Task AddBook_WhenCalledWithNullContributors_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(includeOptionalProperties: false);
AddBookRequest bookRequest = _requestBookFixture.Create() with { Contributors = null };
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Description);
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.ContributorsListCannotBeNull.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithNullContributorName_ShouldReturnUnprocessableEntity()
public async Task AddBook_WhenCalledWithEmptyContributorId_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(roleName: "author", roleCategory: MediaContributorRoleCategory.Author, includeName: false)]);
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorNameCannotBeEmpty.Description);
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.MediaContributorIdCannotBeEmpty.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithEmptyContributorDisplayName_ShouldReturnUnprocessableEntity()
public async Task AddBook_WhenCalledWithInvalidContributorRole_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]);
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithNullContributorDisplayName_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(includeDisplayName: false, includeLegalName: false, roleName: "author", roleCategory: MediaContributorRoleCategory.Author)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithInvalidLengthContributorDisplayName_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(150))]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithInvalidLengthContributorLegalName_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), legalName: new Faker().Random.String2(150), roleName: "author", roleCategory: MediaContributorRoleCategory.Author)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithEmptyContributorRole_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), includeRole: false)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorRoleCannotBeNull.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithEmptyContributorRoleName_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), includeRoleName: false, roleCategory: MediaContributorRoleCategory.Author)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleNameCannotBeEmpty.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleName_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), roleName: new Faker().Random.String2(100), roleCategory: MediaContributorRoleCategory.Author)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description);
}
[Fact]
public async Task AddBook_WhenCalledWithEmptyContributorRoleCategory_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), roleName: "author", includeRoleCategory: false)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description);
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.UnknownMediaContributorRole.Description);
}
[Fact]
@@ -1304,13 +1219,14 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
}
[Fact]
public async Task AddBook_WhenTwoContributorsShareTheSameDisplayName_ShouldCreateOneContributorWithTwoBookLinks()
public async Task AddBook_WhenTwoContributorsHaveTheSameIdWithDifferentRoles_ShouldCreateTwoBookLinks()
{
// Arrange
Guid contributorId = Guid.NewGuid();
AddBookRequest bookRequest = _requestBookFixture.Create(contributors:
[
_mediaContributorDtoFixture.Create(displayName: "Duplicated Author", legalName: "Duplicated Author Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(displayName: "Duplicated Author", legalName: "Duplicated Author Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator)
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator)
]);
// Act
@@ -1324,15 +1240,518 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
MediaContributorEntity contributor = dbContext.MediaContributors.Single(mediaContributor => mediaContributor.DisplayName == "Duplicated Author");
List<BookContributorEntity> links = [.. dbContext.Books
.Include(book => book.BookContributors)
.Single(book => book.Id == bookResponse!.Id.Value)
.BookContributors];
Assert.Equal(2, links.Count);
Assert.All(links, link => Assert.Equal(contributor.Id, link.MediaContributorId));
Assert.Contains(links, link => link.RoleName == "author");
Assert.Contains(links, link => link.RoleName == "illustrator");
Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId));
Assert.Contains(links, link => link.Role == MediaContributorRole.Author);
Assert.Contains(links, link => link.Role == MediaContributorRole.Illustrator);
}
[Fact]
public async Task AddBook_WhenBookPathIsNotWithinTheLibraryContentLocations_ShouldReturnUnprocessableEntity()
{
// Arrange
string pathOutsideTheLibrary = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "..", "lumina-books-outside", $"{Guid.NewGuid():N}.epub"));
AddBookRequest bookRequest = _requestBookFixture.Create(path: pathOutsideTheLibrary);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.BookPathMustBeWithinLibraryContentLocations.Description);
}
[Fact]
public async Task AddBook_WhenBookPathAlreadyExistsInTheLibrary_ShouldReturnConflict()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create();
// Act
HttpResponseMessage firstResponse = await PostBookAsync(bookRequest);
HttpResponseMessage secondResponse = await PostBookAsync(bookRequest);
// Assert
Assert.Equal(HttpStatusCode.Created, firstResponse.StatusCode);
Assert.Equal(HttpStatusCode.Conflict, secondResponse.StatusCode);
Assert.Equal("application/problem+json", secondResponse.Content.Headers.ContentType?.MediaType);
string content = await secondResponse.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status409Conflict, problemDetails!["status"].GetInt32());
Assert.Equal(Errors.WrittenContent.BookAlreadyExists.Description, problemDetails["detail"].GetString());
}
[Fact]
public async Task AddBook_WhenAReferencedContributorDoesNotExist_ShouldReturnNotFound()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
// Act
HttpResponseMessage response = await PostBookWithoutSeedingContributorsAsync(bookRequest);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal(Errors.MediaContributor.MediaContributorNotFound.Description, problemDetails["detail"].GetString());
}
[Fact]
public async Task AddBook_WhenCalledWithTooLongPath_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.BookPathMustBeMaximum2048CharactersLong.Description);
}
[Fact]
public async Task AddBook_WhenTheLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
// only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
Guid missingLibraryId = Guid.NewGuid();
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await adminClient.PostAsJsonAsync($"/api/v1/libraries/{missingLibraryId}/books", bookRequest);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal(Errors.Library.LibraryNotFound.Description, problemDetails["detail"].GetString());
await _apiFactory.RemoveTestUserAsync();
}
[Fact]
public async Task AddBook_WhenTitleIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200)));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenOriginalTitleIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenDescriptionIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenOriginalReleaseYearIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false)));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenReReleaseYearIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false)));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenReleaseVersionIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenGenresAreValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenTagsAreValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidPublisher_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100)));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenPageCountIsPositive_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenFormatIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(format: BookFormat.Hardcover);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenEditionIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(edition: new Faker().Random.String2(50));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenVolumeNumberIsPositive_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(volumeNumber: 1);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenAsinIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(asin: new Faker().Random.String2(10));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenGoodreadsIdIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(goodreadsId: "123456789");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenLccnIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(lccn: "n78890351");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidOclcNumberFormat1_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "ocm12345678");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidOclcNumberFormat2_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "ocn123456789");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidOclcNumberFormat3_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "on1234567890");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidOclcNumberFormat4_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "(OCoLC)1234567890");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidOclcNumberFormat5_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "12345678");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenOpenLibraryIdIsValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(openLibraryId: "OL123456M");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidLibraryThingId_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(libraryThingId: new Faker().Random.String2(50));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidGoogleBooksId_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"));
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidBarnesAndNobleId_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString());
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidAppleBooksId_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(appleBooksId: "id123456");
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidIsbn10_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidIsbn13_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenContributorsAreValid_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenCalledWithValidRatings_ShouldAddBook()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]);
// Act
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task AddBook_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/not-a-guid/books", bookRequest);
// Assert
// The route value is kept as a raw string, so the unparseable Id becomes an empty Guid in the command mapping and the
// command validator reports a clean validation error instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
@@ -1340,9 +1759,40 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
/// </summary>
/// <param name="request">The request to post.</param>
/// <returns>The HTTP response of the POST request.</returns>
private Task<HttpResponseMessage> PostBookAsync(AddBookRequest request)
private async Task<HttpResponseMessage> PostBookAsync(AddBookRequest request)
{
return _client.PostAsJsonAsync("/api/v1/books", request with { LibraryId = _libraryId });
await SeedContributorsAsync(request.Contributors);
return await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", request);
}
/// <summary>
/// Posts a request to add a book to the media library owned by the authenticated user of the current test, without seeding the contributors it references.
/// </summary>
/// <param name="request">The request to post.</param>
/// <returns>The HTTP response of the POST request.</returns>
private Task<HttpResponseMessage> PostBookWithoutSeedingContributorsAsync(AddBookRequest request)
{
return _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", request);
}
/// <summary>
/// Seeds the media contributors referenced by the provided book contributors, so that the handler finds them already existing.
/// </summary>
/// <param name="contributors">The contributors of the book request.</param>
private async Task SeedContributorsAsync(List<MediaContributorReferenceDto>? contributors)
{
if (contributors is null || contributors.Count == 0)
return;
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
foreach (Guid contributorId in contributors.Select(contributor => contributor.ContributorId).Distinct())
{
if (contributorId == Guid.Empty || await dbContext.MediaContributors.AnyAsync(contributor => contributor.Id == contributorId))
continue;
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()));
}
await dbContext.SaveChangesAsync();
}
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, params string[] expectedErrorCodes)
@@ -1355,7 +1805,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/books", problemDetails["instance"].GetString());
Assert.Equal($"/api/v1/libraries/{_libraryId}/books", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
@@ -1383,4 +1833,4 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
{
await _apiFactory.RemoveTestUserAsync();
}
}
}
@@ -1,15 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
@@ -26,7 +30,10 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo
public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly AddBookRequestFixture _addBookRequestFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
@@ -39,6 +46,59 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
public AddBookEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task AddBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/books", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task AddBook_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
[Theory]
@@ -50,11 +110,18 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, userId);
AddBookRequest request = _addBookRequestFixture.Create(libraryId: libraryId, path: maliciousPath);
string contentLocation = Path.GetTempPath();
string injectedPath = Path.Combine(contentLocation, $"{maliciousPath}.epub");
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation]));
await seedDbContext.SaveChangesAsync();
}
AddBookRequest request = _addBookRequestFixture.Create(path: injectedPath, contributors: []);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/books", request);
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
// the malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted
@@ -71,6 +138,71 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
await _apiFactory.RemoveTestUserAsync(username);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task AddBook_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
string contentLocation = Path.GetTempPath();
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation]));
await seedDbContext.SaveChangesAsync();
}
string bookPath = Path.Combine(contentLocation, $"{Guid.NewGuid()}.epub");
AddBookRequest request = _addBookRequestFixture.Create(path: bookPath, metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle), contributors: []);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
// the malicious title passes the authenticated handler, reaches the parameterized insert, and is persisted
// verbatim: if it were concatenated into raw SQL, the insert would fail and the book would not be created
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity storedBook = await dbContext.Books.SingleAsync(book => book.LibraryId == libraryId);
Assert.Equal(maliciousTitle, storedBook.Title);
await _apiFactory.RemoveTestUserAsync(username);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task AddBook_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books", request);
// Assert
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
// or the injected payload.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
await _apiFactory.RemoveTestUserAsync(username);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
@@ -0,0 +1,106 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaContributors;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaContributors;
/// <summary>
/// Contains unit tests for the <see cref="MediaContributorReferenceDtoMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorReferenceDtoMappingTests
{
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
[Fact]
public void ToBookDomainEntity_WhenMappingCompleteMediaContributorReferenceDto_ShouldMapAllPropertiesCorrectly()
{
// Arrange
Guid contributorId = Guid.NewGuid();
MediaContributorReferenceDto dto = _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author);
// Act
Result<BookMediaContributor> result = dto.ToBookDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(dto.ContributorId, result.Value.ContributorId.Value);
Assert.Equal(dto.Role, result.Value.Role);
}
[Fact]
public void ToBookDomainEntities_WhenMappingMultipleValidMediaContributorReferenceDtos_ShouldMapAllCorrectly()
{
// Arrange
List<MediaContributorReferenceDto> dtos =
[
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Illustrator)
];
// Act
IEnumerable<Result<BookMediaContributor>> results = dtos.ToBookDomainEntities();
// Assert
Assert.NotNull(results);
Assert.Equal(dtos.Count, results.Count());
List<Result<BookMediaContributor>> resultList = [.. results];
Assert.All(resultList, result => Assert.False(result.IsFailure));
Assert.Equal(dtos[0].ContributorId, resultList[0].Value.ContributorId.Value);
Assert.Equal(dtos[0].Role, resultList[0].Value.Role);
Assert.Equal(dtos[1].ContributorId, resultList[1].Value.ContributorId.Value);
Assert.Equal(dtos[1].Role, resultList[1].Value.Role);
}
[Fact]
public void ToMusicDomainEntity_WhenMappingCompleteMediaContributorReferenceDto_ShouldMapAllPropertiesCorrectly()
{
// Arrange
Guid contributorId = Guid.NewGuid();
MediaContributorReferenceDto dto = _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Producer);
// Act
Result<MusicMediaContributor> result = dto.ToMusicDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(dto.ContributorId, result.Value.ContributorId.Value);
Assert.Equal(dto.Role, result.Value.Role);
}
[Fact]
public void ToMusicDomainEntities_WhenMappingMultipleValidMediaContributorReferenceDtos_ShouldMapAllCorrectly()
{
// Arrange
List<MediaContributorReferenceDto> dtos =
[
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Vocals),
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Guitar)
];
// Act
IEnumerable<Result<MusicMediaContributor>> results = dtos.ToMusicDomainEntities();
// Assert
Assert.NotNull(results);
Assert.Equal(dtos.Count, results.Count());
List<Result<MusicMediaContributor>> resultList = [.. results];
Assert.All(resultList, result => Assert.False(result.IsFailure));
Assert.Equal(dtos[0].ContributorId, resultList[0].Value.ContributorId.Value);
Assert.Equal(dtos[0].Role, resultList[0].Value.Role);
Assert.Equal(dtos[1].ContributorId, resultList[1].Value.ContributorId.Value);
Assert.Equal(dtos[1].Role, resultList[1].Value.Role);
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains unit tests for the <see cref="AddBookCommandMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddBookCommandMappingTests
{
private readonly AddBookCommandFixture _commandBookFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
[Fact]
public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookCommand command = _commandBookFixture.Create(libraryId: libraryId.ToString());
// Act
Result<Book> result = command.ToDomainEntity(libraryId);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(libraryId, result.Value.LibraryId.Value);
Assert.Equal(command.Path, result.Value.Path);
Assert.Equal(command.Metadata!.Title, result.Value.Metadata.Title);
Assert.Equal(command.Metadata.ReleaseInfo!.OriginalReleaseYear, result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
Assert.Equal(command.Metadata.Genres!.Count, result.Value.Metadata.Genres.Count);
Assert.Equal(command.Metadata.Tags!.Count, result.Value.Metadata.Tags.Count);
Assert.Equal(command.ISBNs!.Count, result.Value.ISBNs.Count);
Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count);
Assert.Equal(command.Ratings!.Count, result.Value.Ratings.Count);
Assert.True(result.Value.Format.HasValue);
Assert.Equal(command.Format, result.Value.Format.Value);
}
[Fact]
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapRequiredPropertiesCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookCommand command = _commandBookFixture.Create(
libraryId: libraryId.ToString(),
isbns: [],
contributors: [],
ratings: [],
includeOptionalProperties: false);
// Act
Result<Book> result = command.ToDomainEntity(libraryId);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(libraryId, result.Value.LibraryId.Value);
Assert.Equal(command.Path, result.Value.Path);
Assert.Empty(result.Value.ISBNs);
Assert.Empty(result.Value.Contributors);
Assert.Empty(result.Value.Ratings);
Assert.False(result.Value.Format.HasValue);
Assert.False(result.Value.Edition.HasValue);
Assert.False(result.Value.VolumeNumber.HasValue);
Assert.False(result.Value.ASIN.HasValue);
Assert.False(result.Value.GoodreadsId.HasValue);
Assert.False(result.Value.LCCN.HasValue);
Assert.False(result.Value.OCLCNumber.HasValue);
Assert.False(result.Value.OpenLibraryId.HasValue);
Assert.False(result.Value.LibraryThingId.HasValue);
Assert.False(result.Value.GoogleBooksId.HasValue);
Assert.False(result.Value.BarnesAndNobleId.HasValue);
Assert.False(result.Value.AppleBooksId.HasValue);
}
[Fact]
public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError()
{
// Arrange
AddBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]);
// Act
Result<Book> result = command.ToDomainEntity(Guid.NewGuid());
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description);
}
[Fact]
public void ToDomainEntity_WhenIsbnCreationFails_ShouldReturnError()
{
// Arrange
AddBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]);
// Act
Result<Book> result = command.ToDomainEntity(Guid.NewGuid());
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description);
}
[Fact]
public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError()
{
// Arrange
AddBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]));
// Act
Result<Book> result = command.ToDomainEntity(Guid.NewGuid());
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
}
}
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
@@ -21,20 +21,22 @@ public class AddBookRequestMappingTests
{
private readonly AddBookRequestFixture _requestFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new();
private readonly MediaContributorRoleDtoFixture _mediaContributorRoleDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
[Fact]
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _requestFixture.Create();
// Act
AddBookCommand result = request.ToCommand();
AddBookCommand result = request.ToCommand(libraryId.ToString());
// Assert
Assert.NotNull(result);
Assert.Equal(libraryId.ToString(), result.LibraryId);
Assert.Equal(request.Path, result.Path);
Assert.Equal(request.Metadata, result.Metadata);
Assert.Equal(request.Format, result.Format);
Assert.Equal(request.Edition, result.Edition);
@@ -58,15 +60,15 @@ public class AddBookRequestMappingTests
public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _requestFixture.Create(
libraryId: Guid.NewGuid(),
path: "/books/test.epub",
metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"),
includeOptionalProperties: false
);
// Act
AddBookCommand result = request.ToCommand();
AddBookCommand result = request.ToCommand(libraryId.ToString());
// Assert
Assert.NotNull(result);
@@ -93,24 +95,21 @@ public class AddBookRequestMappingTests
public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _requestFixture.Create(
libraryId: Guid.NewGuid(),
path: "/books/test.epub",
metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"),
isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)],
contributors:
[
new(
_mediaContributorNameDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe"),
_mediaContributorRoleDtoFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author)
)
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)
],
ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
includeOptionalProperties: false
);
// Act
AddBookCommand result = request.ToCommand();
AddBookCommand result = request.ToCommand(libraryId.ToString());
// Assert
Assert.NotNull(result);
@@ -134,38 +134,6 @@ public class BookMetadataDtoMappingTests
Assert.True(result.IsFailure);
}
[Fact]
public void ApplyMetadata_WhenLanguageIsInvalid_ShouldReturnError()
{
// Arrange
Book book = _bookFixture.Create();
BookMetadataDto metadata = _bookMetadataDtoFixture.Create(
title: "A valid title",
language: new LanguageInfoDto("", "English", "English"));
// Act
Result<Success> result = book.ApplyMetadata(metadata);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public void ApplyMetadata_WhenOriginalLanguageIsInvalid_ShouldReturnError()
{
// Arrange
Book book = _bookFixture.Create();
BookMetadataDto metadata = _bookMetadataDtoFixture.Create(
title: "A valid title",
originalLanguage: new LanguageInfoDto("", "English", "English"));
// Act
Result<Success> result = book.ApplyMetadata(metadata);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public void ApplyMetadata_WhenIsbnIsInvalid_ShouldReturnError()
{
@@ -1,10 +1,12 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
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.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
@@ -12,6 +14,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.Setup;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
@@ -21,11 +24,15 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -42,9 +49,12 @@ public class AddBookCommandHandlerTests
private readonly IFixture _fixture;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMediaContributorRepository _mockMediaContributorRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<AddBookCommand> _mockValidator;
private readonly IPathService _mockPathService;
private readonly Guid _userId;
private readonly AddBookCommandHandler _sut;
private readonly AddBookCommandFixture _commandBookFixture = new();
@@ -53,10 +63,9 @@ public class AddBookCommandHandlerTests
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandHandlerTests"/> class.
@@ -69,24 +78,66 @@ public class AddBookCommandHandlerTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockPathService = Substitute.For<IPathService>();
_userId = Guid.NewGuid();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_mediaContributorEntityFixture.Create()));
// Default stub: saving changes succeeds.
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Default stubs: the current user is authenticated and the library ownership policy allows access.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
// Default stub: the book path is inside the content locations of the library.
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>())
.Returns(true);
// Default stub: every referenced media contributor already exists.
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
IReadOnlyCollection<Guid> contributorIds = callInfo.Arg<IReadOnlyCollection<Guid>>();
return Result.From<IReadOnlyList<MediaContributorEntity>>([.. contributorIds.Select(contributorId => new MediaContributorEntity
{
Id = contributorId,
DisplayName = contributorId.ToString(),
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
})]);
});
IValidator<AddBookCommand> mockValidator = Substitute.For<IValidator<AddBookCommand>>();
mockValidator.Validate(Arg.Any<AddBookCommand>())
.Returns([]);
_sut = new AddBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, mockValidator);
_mockValidator = mockValidator;
_sut = new AddBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService);
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
_mockValidator.Validate(Arg.Any<AddBookCommand>())
.Returns([Errors.WrittenContent.IsbnListCannotBeNull]);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.IsbnListCannotBeNull, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -95,8 +146,15 @@ public class AddBookCommandHandlerTests
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
BookEntity? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
.Returns(callInfo =>
{
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<BookEntity?>(insertedEntity));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
@@ -127,6 +185,26 @@ public class AddBookCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesDetectsAConcurrentDuplicatePath_ShouldReturnThePersistenceError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult()
{
@@ -216,53 +294,17 @@ public class AddBookCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLanguageInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English")));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English")));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorsAreLinked_ShouldAttachBookContributorRowsAndReturnThemInTheResponse()
{
// Arrange
Guid firstContributorId = Guid.NewGuid();
Guid secondContributorId = Guid.NewGuid();
AddBookCommand bookCommand = _commandBookFixture.Create(contributors:
[
_mediaContributorDtoFixture.Create(displayName: "Author One", legalName: "Author One Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(displayName: "Author Two", legalName: "Author Two Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator)
_mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Illustrator)
]);
MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create();
MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From(callInfo.ArgAt<string>(0) == "Author One" ? firstContributor : secondContributor));
BookEntity? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
@@ -270,37 +312,33 @@ public class AddBookCommandHandlerTests
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<BookEntity?>(insertedEntity));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(bookCommand.Contributors, result.Value.Contributors);
Assert.NotNull(insertedEntity);
Assert.Equal(2, insertedEntity!.BookContributors.Count);
Assert.Equal(firstContributor.Id, insertedEntity.BookContributors[0].MediaContributorId);
Assert.Equal("author", insertedEntity.BookContributors[0].RoleName);
Assert.Equal(MediaContributorRoleCategory.Author, insertedEntity.BookContributors[0].RoleCategory);
Assert.Equal(secondContributor.Id, insertedEntity.BookContributors[1].MediaContributorId);
Assert.Equal("illustrator", insertedEntity.BookContributors[1].RoleName);
Assert.Equal(MediaContributorRoleCategory.Illustrator, insertedEntity.BookContributors[1].RoleCategory);
Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == firstContributorId && contributor.Role == MediaContributorRole.Author);
Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == secondContributorId && contributor.Role == MediaContributorRole.Illustrator);
await _mockBookRepository.Received(1).InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole()
public async Task HandleAsync_WhenContributorsHaveTheSameIdAndRole_ShouldLinkThemOnlyOnce()
{
// Arrange
Guid contributorId = Guid.NewGuid();
AddBookCommand bookCommand = _commandBookFixture.Create(contributors:
[
_mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator)
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator)
]);
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(contributor));
BookEntity? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
@@ -308,73 +346,22 @@ public class AddBookCommandHandlerTests
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<BookEntity?>(insertedEntity));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"John Doe", "John Smith Doe", Arg.Any<CancellationToken>());
Assert.NotNull(insertedEntity);
Assert.Equal(2, insertedEntity!.BookContributors.Count);
Assert.All(insertedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId));
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author");
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator");
Assert.All(insertedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorHasNullDisplayName_ShouldSkipIt()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors:
[
_mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(includeName: false, roleName: "unknown", roleCategory: MediaContributorRoleCategory.Other)
]);
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(contributor));
BookEntity? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"John Doe", "John Smith Doe", Arg.Any<CancellationToken>());
Assert.NotNull(insertedEntity);
Assert.Single(insertedEntity!.BookContributors);
Assert.Equal(contributor.Id, insertedEntity.BookContributors[0].MediaContributorId);
}
[Fact]
public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutInserting()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
Error findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor.");
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(findOrCreateError);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(findOrCreateError, result.FirstError);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
@@ -407,33 +394,62 @@ public class AddBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == bookCommand.LibraryId), Arg.Any<CancellationToken>());
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == Guid.Parse(bookCommand.LibraryId!)), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldStampTheCurrentUserAsTheAuditActor()
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create()]);
BookEntity? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
AddBookCommand bookCommand = _commandBookFixture.Create();
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(null));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(insertedEntity);
Assert.Equal(_userId, insertedEntity!.CreatedBy);
Assert.NotEmpty(insertedEntity.BookContributors);
Assert.All(insertedEntity.BookContributors, contributor => Assert.Equal(_userId, contributor.CreatedBy));
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookPathIsNotWithinTheLibraryContentLocations_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>())
.Returns(false);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookPathMustBeWithinLibraryContentLocations, result.FirstError);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
@@ -35,7 +35,20 @@ public class AddBookCommandValidatorTests
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
[Fact]
public void Validate_WhenPathIsLongerThan2048Characters_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub");
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookPathMustBeMaximum2048CharactersLong);
}
[Fact]
public void Validate_WhenTitleIsNull_ShouldHaveValidationError()
@@ -479,6 +492,19 @@ public class AddBookCommandValidatorTests
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong);
}
[Fact]
public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1))));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong);
}
[Fact]
public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError()
{
@@ -557,6 +583,19 @@ public class AddBookCommandValidatorTests
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty);
}
[Fact]
public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1))));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong);
}
[Fact]
public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError()
{
@@ -1224,7 +1263,7 @@ public class AddBookCommandValidatorTests
}
[Fact]
public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldAddBook()
public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldNotHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
@@ -1250,7 +1289,7 @@ public class AddBookCommandValidatorTests
}
[Fact]
public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnBadRequest()
public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(51));
@@ -1367,7 +1406,7 @@ public class AddBookCommandValidatorTests
}
[Fact]
public void AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook()
public void Validate_WhenCalledWithEmptyAppleBooksId_ShouldNotHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
@@ -1380,7 +1419,7 @@ public class AddBookCommandValidatorTests
}
[Fact]
public void AddBook_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError()
public void Validate_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "id123456");
@@ -1393,7 +1432,7 @@ public class AddBookCommandValidatorTests
}
[Fact]
public void AddBook_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError()
public void Validate_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "invalid_id");
@@ -1497,120 +1536,55 @@ public class AddBookCommandValidatorTests
}
[Fact]
public void Validate_WhenCalledWithNullContributors_ShouldHaveValidationError()
public void Validate_WhenContributorsIsNull_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
AddBookCommand bookCommand = _commandBookFixture.Create() with { Contributors = null };
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
}
[Fact]
public void Validate_WhenCalledWithNullContributorName_ShouldHaveValidationError()
public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(null, new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author))]);
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorNameCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
}
[Fact]
public void Validate_WhenCalledWithInvalidLengthContributorDisplayName_ShouldHaveValidationError()
public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(101))]);
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong);
result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCalledWithEmptyContributorDisplayName_ShouldHaveValidationError()
public void Validate_WhenContributorRoleIsInvalid_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]);
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenCalledWithInvalidLengthContributorLegalName_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), new Faker().Random.String2(101)), new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author))]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong);
}
[Fact]
public void Validate_WhenCalledWithNullContributorRole_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), null)]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorRoleCannotBeNull);
}
[Fact]
public void Validate_WhenCalledWithEmptyContributorRoleName_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto(null, MediaContributorRoleCategory.Author))]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.RoleNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenCalledWithInvalidLengthContributorRoleName_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto(new Faker().Random.String2(51), MediaContributorRoleCategory.Author))]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
}
[Fact]
public void Validate_WhenCalledWithEmptyContributorRoleCategory_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto("author", null))]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole);
}
[Fact]
@@ -1708,12 +1682,12 @@ public class AddBookCommandValidatorTests
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty);
AddBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty.ToString());
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookLibraryCannotBeNull);
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -24,7 +24,7 @@ public class MediaContributorDtoTests
// Arrange
MediaContributorDto expected = new(
new MediaContributorNameDto("John Smith", "Johnathan Smith"),
new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author)
MediaContributorRole.Author
);
// Act
@@ -1,49 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
#endregion
namespace Lumina.Contracts.UnitTests.DTO.MediaContributors;
/// <summary>
/// Contains unit tests for the <see cref="MediaContributorRoleDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorRoleDtoTests
{
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
[Fact]
public void RoundTrip_WhenSerializingRole_ShouldPreserveValues()
{
// Arrange
MediaContributorRoleDto expected = new("Author", MediaContributorRoleCategory.Author);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
MediaContributorRoleDto? actual = JsonSerializer.Deserialize<MediaContributorRoleDto>(json, _jsonOptions);
// Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
[Fact]
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
{
// Arrange
MediaContributorRoleDto first = new("Illustrator", null);
MediaContributorRoleDto second = new("Illustrator", null);
// Act
bool areEqual = first == second;
// Assert
Assert.True(areEqual);
}
}
@@ -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;
@@ -36,7 +36,6 @@ public class AddBookRequestTests
// Assert
Assert.NotNull(sut);
Assert.NotEqual(Guid.Empty, sut.LibraryId);
Assert.False(string.IsNullOrWhiteSpace(sut.Path));
Assert.NotNull(sut.Metadata);
Assert.NotNull(sut.ISBNs);
@@ -83,10 +82,9 @@ public class AddBookRequestTests
AddBookRequest sut = _addBookRequestFixture.Create();
// Act
(Guid libraryId, string path, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List<IsbnDto>? isbns, List<MediaContributorDto>? contributors, List<BookRatingDto>? ratings) = sut;
(string path, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List<IsbnDto>? isbns, List<MediaContributorReferenceDto>? contributors, List<BookRatingDto>? ratings) = sut;
// Assert
Assert.Equal(sut.LibraryId, libraryId);
Assert.Equal(sut.Path, path);
Assert.Equal(sut.Metadata, metadata);
Assert.Equal(sut.Format, format);
@@ -96,6 +96,50 @@ public class BookRepositoryTests
Assert.Single(_mockContext.ChangeTracker.Entries<BookEntity>()); // Only the existing book should be in the context.
}
[Fact]
public async Task InsertAsync_WhenAnotherBookOfTheSameLibraryHasTheSamePath_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity existingBook = _bookEntityFixture.Create();
existingBook.LibraryId = libraryId;
existingBook.Path = "/books/existing.epub";
_mockContext.Books.Add(existingBook);
await _mockContext.SaveChangesAsync();
BookEntity bookModel = _bookEntityFixture.Create();
bookModel.LibraryId = libraryId;
bookModel.Path = "/books/existing.epub";
// Act
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
}
[Fact]
public async Task InsertAsync_WhenAnotherLibraryHasABookWithTheSamePath_ShouldAddBookToContextAndReturnCreated()
{
// Arrange
BookEntity existingBook = _bookEntityFixture.Create();
existingBook.Path = "/books/existing.epub";
_mockContext.Books.Add(existingBook);
await _mockContext.SaveChangesAsync();
BookEntity bookModel = _bookEntityFixture.Create();
bookModel.LibraryId = Guid.NewGuid();
bookModel.Path = "/books/existing.epub";
// Act
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
}
[Fact]
public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes()
{
@@ -151,54 +195,66 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks()
public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooksOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
foreach (BookEntity book in books)
book.LibraryId = libraryId;
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync<LibraryFilterDto>(filterModel: filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(3, result.Value.Count());
Assert.Equal(books, result.Value);
Assert.Equal(3, result.Value.Data.Count);
Assert.Equal([.. books.OrderBy(book => book.Id)], [.. result.Value.Data.OrderBy(book => book.Id)]);
}
[Fact]
public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList()
{
// Arrange
LibraryFilterDto filter = _libraryFilterDtoFixture.Create();
// Act
Result<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync<LibraryFilterDto>(filterModel: filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Empty(result.Value);
Assert.Empty(result.Value.Data);
}
[Fact]
public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities()
public async Task GetAllAsync_WhenPaginationIsNotProvided_ShouldIncludeRelatedEntities()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync<LibraryFilterDto>(filterModel: filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Single(result.Value);
BookEntity retrievedBook = result.Value.First();
Assert.Single(result.Value.Data);
BookEntity retrievedBook = result.Value.Data.First();
Assert.Equal(2, retrievedBook.Tags.Count);
Assert.Equal(2, retrievedBook.Genres.Count);
Assert.Equal(2, retrievedBook.ISBNs.Count);
@@ -441,14 +497,14 @@ public class BookRepositoryTests
BookEntity storedBook = _bookEntityFixture.Create();
storedBook.ISBNs = [_isbnEntityFixture.Create(value: "9780395272237", format: IsbnFormat.Isbn13)];
storedBook.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
storedBook.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, roleCategory: MediaContributorRoleCategory.Author)];
storedBook.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, role: MediaContributorRole.Author)];
_mockContext.Books.Add(storedBook);
await _mockContext.SaveChangesAsync();
BookEntity data = _bookEntityFixture.Create(id: storedBook.Id);
data.ISBNs = [_isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)];
data.Ratings = [_bookRatingEntityFixture.Create(value: 3.5M, maxValue: 5, source: BookRatingSource.Amazon, voteCount: 50)];
data.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), roleCategory: MediaContributorRoleCategory.Illustrator)];
data.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Illustrator)];
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
@@ -467,11 +523,11 @@ public class BookRepositoryTests
BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.BookContributors);
Assert.Equal("9780261102693", retrievedIsbn.Value);
Assert.Equal(3.5M, retrievedRating.Value);
Assert.Equal(MediaContributorRoleCategory.Illustrator, retrievedContributor.RoleCategory);
Assert.Equal(MediaContributorRole.Illustrator, retrievedContributor.Role);
}
[Fact]
public async Task GetPaginatedAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks()
public async Task GetAllAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -485,7 +541,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -497,14 +553,14 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError()
public async Task GetAllAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError()
{
// Arrange
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
BaseFilterDto filter = _baseFilterDtoFixture.Create();
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -512,14 +568,14 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError()
public async Task GetAllAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError()
{
// Arrange
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -527,7 +583,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenPaginationDataIsNull_ShouldReturnAllBooks()
public async Task GetAllAsync_WhenPaginationDataIsNull_ShouldReturnAllBooks()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -540,7 +596,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(null, null, null, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -552,7 +608,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingBooks()
public async Task GetAllAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingBooks()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -569,7 +625,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship");
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -579,7 +635,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata()
public async Task GetAllAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -593,7 +649,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -605,7 +661,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByTitleDescending_ShouldReturnBooksInDescendingOrder()
public async Task GetAllAsync_WhenSortByTitleDescending_ShouldReturnBooksInDescendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -622,7 +678,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "title", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -630,7 +686,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenCalled_ShouldIncludeRelatedEntities()
public async Task GetAllAsync_WhenPaginationIsProvided_ShouldIncludeRelatedEntities()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -647,7 +703,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -733,8 +789,8 @@ public class BookRepositoryTests
await _mockContext.SaveChangesAsync();
_mockContext.BookContributors.AddRange(
_bookContributorEntityFixture.Create(bookId: firstBook.Id, mediaContributorId: author.Id, roleName: "Author", roleCategory: MediaContributorRoleCategory.Author),
_bookContributorEntityFixture.Create(bookId: secondBook.Id, mediaContributorId: translator.Id, roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator));
_bookContributorEntityFixture.Create(bookId: firstBook.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author),
_bookContributorEntityFixture.Create(bookId: secondBook.Id, mediaContributorId: translator.Id, role: MediaContributorRole.Translator));
await _mockContext.SaveChangesAsync();
// Act
@@ -786,7 +842,7 @@ public class BookRepositoryTests
await _mockContext.SaveChangesAsync();
// Act
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, CancellationToken.None);
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -797,7 +853,7 @@ public class BookRepositoryTests
public async Task GetByIdAsync_WhenBookDoesNotExist_ShouldReturnNull()
{
// Act
Result<BookEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
Result<BookEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -817,7 +873,7 @@ public class BookRepositoryTests
await _mockContext.SaveChangesAsync();
// Act
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, CancellationToken.None);
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -857,7 +913,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByLanguageCodeAscending_ShouldReturnBooksInAscendingOrder()
public async Task GetAllAsync_WhenSortByLanguageCodeAscending_ShouldReturnBooksInAscendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -874,7 +930,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Ascending, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "languageCode", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -882,7 +938,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByLanguageCodeDescending_ShouldReturnBooksInDescendingOrder()
public async Task GetAllAsync_WhenSortByLanguageCodeDescending_ShouldReturnBooksInDescendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -899,7 +955,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Descending, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "languageCode", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -907,7 +963,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByFormatAscending_ShouldReturnBooksInAscendingOrder()
public async Task GetAllAsync_WhenSortByFormatAscending_ShouldReturnBooksInAscendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -924,7 +980,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Ascending, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "format", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -932,7 +988,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByFormatDescending_ShouldReturnBooksInDescendingOrder()
public async Task GetAllAsync_WhenSortByFormatDescending_ShouldReturnBooksInDescendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -949,7 +1005,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Descending, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "format", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -957,7 +1013,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByMetadataProviderAscending_ShouldReturnBooksInAscendingOrder()
public async Task GetAllAsync_WhenSortByMetadataProviderAscending_ShouldReturnBooksInAscendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -974,7 +1030,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Ascending, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "metadataProvider", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -982,7 +1038,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenSortByMetadataProviderDescending_ShouldReturnBooksInDescendingOrder()
public async Task GetAllAsync_WhenSortByMetadataProviderDescending_ShouldReturnBooksInDescendingOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -999,7 +1055,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Descending, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "metadataProvider", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -1007,7 +1063,7 @@ public class BookRepositoryTests
}
[Fact]
public async Task GetPaginatedAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix()
public async Task GetAllAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -1022,7 +1078,7 @@ public class BookRepositoryTests
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -1,84 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="MediaContributorRole"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorRoleTests
{
private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new();
[Fact]
public void Create_WhenCalledWithDisplayNameAndCategory_ShouldCreateRole()
{
// Act
Result<MediaContributorRole> result = MediaContributorRole.Create("Author", MediaContributorRoleCategory.Author);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Author", result.Value.DisplayName);
Assert.Equal(MediaContributorRoleCategory.Author, result.Value.Category);
}
[Fact]
public void Create_WhenCalledWithEmptyDisplayName_ShouldReturnError()
{
// Act
Result<MediaContributorRole> result = MediaContributorRole.Create(" ", MediaContributorRoleCategory.Author);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributors.MediaContributorRoleNameCannotBeEmpty, result.FirstError);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
// Act
bool result = firstRole.Equals(secondRole);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentDisplayName_ShouldReturnFalse()
{
// Arrange
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Writer", category: MediaContributorRoleCategory.Author);
// Act
bool result = firstRole.Equals(secondRole);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_WithDifferentCategory_ShouldReturnFalse()
{
// Arrange
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Translator);
// Act
bool result = firstRole.Equals(secondRole);
// Assert
Assert.False(result);
}
}
@@ -43,11 +43,13 @@ public class AddBookEndpointTests
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithBookResponse()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _addBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
BookResponse expectedResponse = _bookResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
ConfigureRequest(libraryId.ToString());
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
@@ -87,10 +89,12 @@ public class AddBookEndpointTests
public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _addBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest(libraryId.ToString());
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -98,7 +102,7 @@ public class AddBookEndpointTests
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<AddBookCommand>(command =>
command.LibraryId == request.LibraryId &&
command.LibraryId == libraryId.ToString() &&
command.Path == request.Path),
Arg.Is(cancellationToken));
}
@@ -130,4 +134,86 @@ public class AddBookEndpointTests
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _addBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = Error.Validation(description: "LibraryIdCannotBeEmpty");
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRequest(libraryId.ToString());
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithRawRouteValue()
{
// Arrange
AddBookRequest request = _addBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequest("not-a-library-guid");
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<AddBookCommand>(command => command.LibraryId == "not-a-library-guid"),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullLibraryId()
{
// Arrange
AddBookRequest request = _addBookRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_bookResponseFixture.Create()));
ConfigureRequestWithoutLibraryId();
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<AddBookCommand>(command => command.LibraryId == null),
Arg.Is(cancellationToken));
}
/// <summary>
/// Sets the <c>libraryId</c> route value the endpoint reads the identifier from.
/// </summary>
/// <param name="libraryId">The raw route value of the library Id.</param>
private void ConfigureRequest(string libraryId)
{
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId;
}
/// <summary>
/// Leaves the <c>libraryId</c> route value unset.
/// </summary>
private void ConfigureRequestWithoutLibraryId()
{
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
}
}