Scopes books to a media library and tracks their metadata enrichment status

This commit is contained in:
BinaryAlley committed 2026-08-12 11:01:59 -07:00
1 parent 386d583a2b
commit f33817f2d2
48 files changed
+2038 -63

No files matched your search

+9 -4
View File
@@ -21,6 +21,8 @@ POST api/v1/books
```json
{
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/books/the-fellowship-of-the-ring.epub",
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
@@ -122,6 +124,9 @@ POST api/v1/books
```json
{
"id": "32b336e8-dafc-4a08-9dec-9454e66dd55d",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/books/the-fellowship-of-the-ring.epub",
"metadata": {
"publisher": "Houghton Mifflin",
"pageCount": 398,
@@ -205,9 +210,9 @@ POST api/v1/books
"voteCount": 87654
}
],
"id": {
"value": "32b336e8-dafc-4a08-9dec-9454e66dd55d"
}
"metadataStatus": "Pending",
"lastMetadataUpdateUtc": null,
"metadataProvider": null
}
```
@@ -216,7 +221,7 @@ POST api/v1/books
#### Get Books Request
```js
GET /books
GET /books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a
```
#### Get Books Response
+2
View File
@@ -2,6 +2,8 @@ POST {{host}}/api/v1/books
Content-Type: application/json
{
"libraryId": "00000000-0000-0000-0000-000000000000",
"path": "/books/the-fellowship-of-the-ring.epub",
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -19,6 +19,16 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the Id of the media library this book belongs to.
/// </summary>
public required Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the file system path of the book.
/// </summary>
public required string Path { get; set; }
/// <summary>
/// Gets or sets the title of the media item.
/// </summary>
@@ -195,6 +205,21 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// </summary>
public List<BookRatingEntity> Ratings { get; set; } = [];
/// <summary>
/// Gets or sets the status of the metadata enrichment of the book.
/// </summary>
public MetadataStatus MetadataStatus { get; set; }
/// <summary>
/// Gets or sets the date and time when the metadata of the book was last enriched.
/// </summary>
public DateTime? LastMetadataUpdateUtc { get; set; }
/// <summary>
/// Gets or sets the name of the plugin that enriched the metadata of the book.
/// </summary>
public string? MetadataProvider { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -1,7 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
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 System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Books;
@@ -11,6 +16,43 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Books;
/// </summary>
public interface IBookRepository : IRepository<BookEntity>,
IInsertRepositoryAction<BookEntity>,
IUpdateRepositoryAction<BookEntity>,
IGetByIdRepositoryAction<BookEntity, Guid>,
IGetAllRepositoryAction<BookEntity>
{
/// <summary>
/// Gets all the books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="BookEntity"/>, or an error.</returns>
Task<ErrorOr<IEnumerable<BookEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets the book of the media library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book is retrieved.</param>
/// <param name="path">The file system path of the book to be retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the <see cref="BookEntity"/> stored at the provided path, or an error.</returns>
Task<ErrorOr<BookEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken);
/// <summary>
/// Gets a page of the books of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet,
/// ordered by path, using keyset pagination.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are retrieved.</param>
/// <param name="lastPath">The path of the last retrieved book, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
/// <param name="pageSize">The maximum number of books to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a page of books needing their metadata enriched, or an error.</returns>
Task<ErrorOr<IReadOnlyList<BookEntity>>> GetBooksNeedingMetadataAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken);
/// <summary>
/// Gets the number of books of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the number of books needing their metadata enriched, or an error.</returns>
Task<ErrorOr<int>> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -24,6 +24,14 @@ public interface ILibraryScanSnapshotRepository : IRepository<LibraryScanSnapsho
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of deleted media library scan snapshot item paths, or an error.</returns>
Task<ErrorOr<IReadOnlyList<string>>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Gets the paths of all the media library scan snapshot items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The unique identifier of the library whose media library scan snapshot item paths are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of media library scan snapshot item paths, or an error.</returns>
Task<ErrorOr<IReadOnlyList<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Atomically applies the results of the current scan to the storage medium, by replacing the media library scan snapshot of the previous scan with the snapshot of the current scan.
/// The operation updates the changed media library scan snapshot items, deletes the ones that are no longer present on disk, adds audit entries for all changed, new and deleted items,
@@ -19,6 +19,8 @@ public static class AddBookRequestMapping
public static AddBookCommand ToCommand(this AddBookRequest request)
{
return new AddBookCommand(
request.LibraryId,
request.Path,
request.Metadata,
request.Format,
request.Edition,
@@ -7,12 +7,13 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
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 System;
using System.Collections.Generic;
using System.Linq;
@@ -110,6 +111,8 @@ public static class BookEntityMapping
return Book.Create(
BookId.Create(repositoryEntity.Id),
LibraryId.Create(repositoryEntity.LibraryId),
repositoryEntity.Path,
writtenContentMetadataResult.Value,
bookFormat,
Optional<string>.FromNullable(repositoryEntity.Edition),
@@ -190,6 +193,8 @@ public static class BookEntityMapping
);
return new BookResponse(
repositoryEntity.Id,
repositoryEntity.LibraryId,
repositoryEntity.Path,
metadata,
repositoryEntity.Format,
repositoryEntity.Edition,
@@ -207,6 +212,9 @@ public static class BookEntityMapping
[.. repositoryEntity.ISBNs.ToResponses()],
null,
[.. repositoryEntity.Ratings.ToResponses()],
repositoryEntity.MetadataStatus,
repositoryEntity.LastMetadataUpdateUtc,
repositoryEntity.MetadataProvider,
repositoryEntity.CreatedOnUtc,
repositoryEntity.UpdatedOnUtc
);
@@ -24,6 +24,8 @@ public static class BookMapping
return new BookEntity
{
Id = domainEntity.Id.Value,
LibraryId = domainEntity.LibraryId.Value,
Path = domainEntity.Path,
Title = domainEntity.Metadata.Title,
OriginalTitle = domainEntity.Metadata.OriginalTitle.HasValue ? domainEntity.Metadata.OriginalTitle.Value : null,
Description = domainEntity.Metadata.Description.HasValue ? domainEntity.Metadata.Description.Value : null,
@@ -57,6 +59,9 @@ public static class BookMapping
AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null,
ISBNs = domainEntity.ISBNs.ToRepositoryEntities().ToList(),
Ratings = domainEntity.Ratings.ToRepositoryEntities().ToList(),
MetadataStatus = domainEntity.MetadataStatus,
LastMetadataUpdateUtc = domainEntity.LastMetadataUpdateUtc.HasValue ? domainEntity.LastMetadataUpdateUtc.Value : null,
MetadataProvider = domainEntity.MetadataProvider.HasValue ? domainEntity.MetadataProvider.Value : null,
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Extension methods for converting <see cref="GetBooksRequest"/>.
/// </summary>
public static class GetBooksRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetBooksQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetBooksQuery ToQuery(this GetBooksRequest request)
{
return new GetBooksQuery(request.LibraryId);
}
}
@@ -2,10 +2,9 @@
using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.Configuration;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
@@ -18,6 +17,7 @@ using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
@@ -30,7 +30,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
private readonly IUnitOfWork _unitOfWork;
private readonly IEnvironmentContext _environmentContext;
private readonly IPathService _pathService;
private readonly MediaSettingsModel _mediaSettingsModel;
private readonly MediaSettingsDto _mediaSettingsModel;
/// <summary>
/// Initializes a new instance of the <see cref="LibrarySavedDomainEventHandler"/> class.
@@ -38,12 +38,12 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsModel"/>.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsDto"/>.</param>
public LibrarySavedDomainEventHandler(
IUnitOfWork unitOfWork,
IEnvironmentContext environmentContext,
IPathService pathService,
IOptions<MediaSettingsModel> mediaSettingsModelOptions)
IOptions<MediaSettingsDto> mediaSettingsModelOptions)
{
_unitOfWork = unitOfWork;
_environmentContext = environmentContext;
@@ -1,8 +1,9 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Lumina.Contracts.DTO.MediaContributors;
@@ -15,6 +16,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <summary>
/// Command for adding a book.
/// </summary>
/// <param name="LibraryId">The Id of the media library this book belongs to.</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>
/// <param name="Edition">The edition of the book, if applicable.</param>
@@ -32,8 +35,10 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book.</param>
/// <param name="Ratings">The list of ratings for this book.</param>
[DebuggerDisplay("Title: {Title}")]
[DebuggerDisplay("Title: {Metadata.Title}")]
public record AddBookCommand(
Guid LibraryId,
string Path,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
@@ -4,7 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
@@ -12,6 +12,7 @@ using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaCon
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 Mediator;
using System;
using System.Collections.Generic;
@@ -139,6 +140,8 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
if (metadataResult.IsError)
return metadataResult.Errors;
ErrorOr<Book> createBookResult = Book.Create(
LibraryId.Create(request.LibraryId),
request.Path,
metadataResult.Value,
Optional<BookFormat>.FromNullable(request.Format),
Optional<string>.FromNullable(request.Edition),
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
@@ -16,6 +16,10 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
/// </summary>
public AddBookCommandValidator()
{
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.WrittenContent.BookLibraryCannotBeNull.Description);
RuleFor(x => x.Path)
.NotEmpty().WithMessage(Errors.WrittenContent.BookPathCannotBeEmpty.Description);
RuleFor(x => x.Metadata)
.NotNull().WithMessage(Errors.Metadata.MetadataCannotBeNull.Description)
.ChildRules(metadata =>
@@ -2,12 +2,16 @@
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
/// <summary>
/// Query for getting all books.
/// Query for getting all the books of a media library.
/// </summary>
public record class GetBooksQuery() : IRequest<ErrorOr<IEnumerable<BookResponse>>>;
/// <param name="LibraryId">The Id of the media library whose books are retrieved.</param>
public record GetBooksQuery(
Guid LibraryId
) : IRequest<ErrorOr<IEnumerable<BookResponse>>>;
@@ -41,8 +41,8 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
{
// get a books repository
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
// get all books from the book repository
ErrorOr<IEnumerable<BookEntity>> getBooksResult = await bookRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
// get all books of the media library from the book repository
ErrorOr<IEnumerable<BookEntity>> getBooksResult = await bookRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(result => ErrorOrFactory.From(getBooksResult.Value.ToResponses()), errors => errors);
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Data transfer object for a genre.
/// </summary>
/// <param name="Name">Gets the name of the genre.</param>
/// <param name="Name">The name of the genre.</param>
[DebuggerDisplay("Name: {Name}")]
public record GenreDto(
string? Name
@@ -7,9 +7,9 @@ namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Data transfer object for language information.
/// </summary>
/// <param name="LanguageCode">Gets the ISO code of the language (e.g., "en" for English). Required.</param>
/// <param name="LanguageName">Gets the name of the language in English. Required.</param>
/// <param name="NativeName">Gets the native name of the language (e.g., "Español" for Spanish). Optional.</param>
/// <param name="LanguageCode">The ISO code of the language (e.g., "en" for English). Required.</param>
/// <param name="LanguageName">The name of the language in English. Required.</param>
/// <param name="NativeName">The native name of the language (e.g., "Español" for Spanish). Optional.</param>
[DebuggerDisplay("LanguageName: {LanguageName}")]
public record LanguageInfoDto(
string? LanguageCode,
+3 -3
View File
@@ -7,9 +7,9 @@ namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Data transfer object for a rating.
/// </summary>
/// <param name="Value">Gets the rating value.</param>
/// <param name="MaxValue">Gets the maximum possible rating value.</param>
/// <param name="VoteCount">Gets the number of votes that contributed to the rating.</param>
/// <param name="Value">The rating value.</param>
/// <param name="MaxValue">The maximum possible rating value.</param>
/// <param name="VoteCount">The number of votes that contributed to the rating.</param>
[DebuggerDisplay("{Value}/{MaxValue}")]
public abstract record RatingDto(
decimal? Value,
@@ -8,12 +8,12 @@ namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Data transfer object for a release information.
/// </summary>
/// <param name="OriginalReleaseDate">Gets the original release date of the content. Optional.</param>
/// <param name="OriginalReleaseYear">Gets the original release year of the content. Optional.</param>
/// <param name="ReReleaseDate">Gets the re-release date of the content. Optional.</param>
/// <param name="ReReleaseYear">Gets the re-release year of the content. Optional.</param>
/// <param name="ReleaseCountry">Gets the country where the content was released. Optional.</param>
/// <param name="ReleaseVersion">Gets the version or edition of the content's release. Optional.</param>
/// <param name="OriginalReleaseDate">The original release date of the content. Optional.</param>
/// <param name="OriginalReleaseYear">The original release year of the content. Optional.</param>
/// <param name="ReReleaseDate">The re-release date of the content. Optional.</param>
/// <param name="ReReleaseYear">The re-release year of the content. Optional.</param>
/// <param name="ReleaseCountry">The country where the content was released. Optional.</param>
/// <param name="ReleaseVersion">The version or edition of the content's release. Optional.</param>
[DebuggerDisplay("OriginalReleaseDate: {OriginalReleaseDate}")]
public record ReleaseInfoDto(
DateOnly? OriginalReleaseDate,
+1 -1
View File
@@ -7,7 +7,7 @@ namespace Lumina.Contracts.DTO.Common;
/// <summary>
/// Data transfer object for a tag.
/// </summary>
/// <param name="Name">Gets the name of the tag.</param>
/// <param name="Name">The name of the tag.</param>
[DebuggerDisplay("Name: {Name}")]
public record TagDto(
string? Name
@@ -2,7 +2,8 @@
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
@@ -12,6 +13,8 @@ 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="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>
@@ -31,6 +34,8 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra
/// <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,
string? Edition,
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Represents a request to get the books of a media library.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose books are retrieved. Required.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetBooksRequest(
Guid LibraryId
);
@@ -2,7 +2,7 @@
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -14,6 +14,8 @@ namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibr
/// Represents a book response.
/// </summary>
/// <param name="Id">The id of the book.</param>
/// <param name="LibraryId">The Id of the media library this book belongs to.</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>
/// <param name="Edition">The edition of the book, if applicable.</param>
@@ -31,11 +33,16 @@ namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibr
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book.</param>
/// <param name="Ratings">The list of ratings for this book.</param>
/// <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>
/// <param name="MetadataProvider">The name of the plugin that enriched the metadata of the book, if applicable.</param>
/// <param name="CreatedOnUtc">The date and time when the book was created.</param>
/// <param name="UpdatedOnUtc">The optional date and time when the book was updated.</param>
[DebuggerDisplay("Title: {Metadata.Title}")]
public record BookResponse(
Guid Id,
Guid LibraryId,
string Path,
WrittenContentMetadataDto Metadata,
BookFormat? Format,
string? Edition,
@@ -53,6 +60,9 @@ public record BookResponse(
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<BookRatingDto>? Ratings,
MetadataStatus MetadataStatus,
DateTime? LastMetadataUpdateUtc,
string? MetadataProvider,
DateTime CreatedOnUtc,
DateTime? UpdatedOnUtc
);
@@ -130,6 +130,23 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
.HasColumnOrder(28);
builder.Property(book => book.AppleBooksId)
.HasColumnOrder(29);
builder.Property(book => book.LibraryId)
.IsRequired()
.HasColumnOrder(36);
builder.Property(book => book.Path)
.IsRequired()
.HasMaxLength(2048)
.HasColumnOrder(37);
builder.Property(book => book.MetadataStatus)
.HasConversion<string>()
.HasMaxLength(20)
.IsRequired()
.HasColumnOrder(38);
builder.Property(book => book.LastMetadataUpdateUtc)
.HasColumnOrder(39);
builder.Property(book => book.MetadataProvider)
.HasMaxLength(100)
.HasColumnOrder(40);
builder.Property(book => book.CreatedOnUtc)
.HasColumnOrder(30);
builder.Property(book => book.UpdatedOnUtc)
@@ -219,6 +236,9 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
builder.Property(book => book.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(35);
builder.HasIndex(book => new { book.LibraryId, book.Path });
builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus });
}
}
@@ -0,0 +1,98 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsBookLibraryAndPathAndMetadataStatus : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "LastMetadataUpdateUtc",
table: "Books",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 39);
migrationBuilder.AddColumn<Guid>(
name: "LibraryId",
table: "Books",
type: "TEXT",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"))
.Annotation("Relational:ColumnOrder", 36);
migrationBuilder.AddColumn<string>(
name: "MetadataProvider",
table: "Books",
type: "TEXT",
maxLength: 100,
nullable: true)
.Annotation("Relational:ColumnOrder", 40);
migrationBuilder.AddColumn<string>(
name: "MetadataStatus",
table: "Books",
type: "TEXT",
maxLength: 20,
nullable: false,
defaultValue: "")
.Annotation("Relational:ColumnOrder", 38);
migrationBuilder.AddColumn<string>(
name: "Path",
table: "Books",
type: "TEXT",
maxLength: 2048,
nullable: false,
defaultValue: "")
.Annotation("Relational:ColumnOrder", 37);
migrationBuilder.CreateIndex(
name: "IX_Books_LibraryId_MetadataStatus",
table: "Books",
columns: new[] { "LibraryId", "MetadataStatus" });
migrationBuilder.CreateIndex(
name: "IX_Books_LibraryId_Path",
table: "Books",
columns: new[] { "LibraryId", "Path" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Books_LibraryId_MetadataStatus",
table: "Books");
migrationBuilder.DropIndex(
name: "IX_Books_LibraryId_Path",
table: "Books");
migrationBuilder.DropColumn(
name: "LastMetadataUpdateUtc",
table: "Books");
migrationBuilder.DropColumn(
name: "LibraryId",
table: "Books");
migrationBuilder.DropColumn(
name: "MetadataProvider",
table: "Books");
migrationBuilder.DropColumn(
name: "MetadataStatus",
table: "Books");
migrationBuilder.DropColumn(
name: "Path",
table: "Books");
}
}
}
@@ -4,8 +4,10 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -59,6 +61,21 @@ internal sealed class BookRepository : IBookRepository
return Result.Created;
}
/// <summary>
/// Gets a book by its Id.
/// </summary>
/// <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="ErrorOr{TValue}"/> containing either a <see cref="BookEntity"/>, or an error.</returns>
public async Task<ErrorOr<BookEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all books.
/// </summary>
@@ -72,4 +89,91 @@ internal sealed class BookRepository : IBookRepository
.Include(book => book.ISBNs)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="BookEntity"/>, or an error.</returns>
public async Task<ErrorOr<IEnumerable<BookEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Where(book => book.LibraryId == libraryId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the book of the media library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book is retrieved.</param>
/// <param name="path">The file system path of the book to be retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the <see cref="BookEntity"/> stored at the provided path, or an error.</returns>
public async Task<ErrorOr<BookEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken)
{
return await _luminaDbContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a page of the books of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet,
/// ordered by path, using keyset pagination.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are retrieved.</param>
/// <param name="lastPath">The path of the last retrieved book, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
/// <param name="pageSize">The maximum number of books to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a page of books needing their metadata enriched, or an error.</returns>
public async Task<ErrorOr<IReadOnlyList<BookEntity>>> GetBooksNeedingMetadataAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken)
{
return await _luminaDbContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Where(book => book.LibraryId == libraryId
&& book.MetadataStatus != MetadataStatus.Enriched
&& (lastPath == null || book.Path.CompareTo(lastPath) > 0))
.OrderBy(book => book.Path)
.Take(pageSize)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the number of books of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the number of books needing their metadata enriched, or an error.</returns>
public async Task<ErrorOr<int>> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Books
.CountAsync(book => book.LibraryId == libraryId && book.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a book.
/// </summary>
/// <param name="data">The book to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<ErrorOr<Updated>> UpdateAsync(BookEntity data, CancellationToken cancellationToken)
{
BookEntity? foundBook = await _luminaDbContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundBook is null)
return Errors.WrittenContent.BookNotFound;
// update the scalar properties of the book
_luminaDbContext.Entry(foundBook).CurrentValues.SetValues(data);
return Result.Updated;
}
}
@@ -59,6 +59,27 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
return deletedPaths.ToList();
}
/// <summary>
/// Gets the paths of all the media library scan snapshot items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The unique identifier of the library whose media library scan snapshot item paths are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of media library scan snapshot item paths, or an error.</returns>
public async Task<ErrorOr<IReadOnlyList<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken)
{
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
const string GET_PATHS_SQL = """
SELECT snapshot.Path
FROM LibraryScanSnapshots AS snapshot
WHERE snapshot.LibraryId = @libraryId;
""";
CommandDefinition command = new(GET_PATHS_SQL, new { libraryId }, cancellationToken: cancellationToken);
IEnumerable<string> paths = await connection.QueryAsync<string>(command).ConfigureAwait(false);
return paths.ToList();
}
/// <summary>
/// Atomically applies the results of the current scan to the storage medium, by replacing the media library scan snapshot of the previous scan with the snapshot of the current scan.
/// The operation updates the changed media library scan snapshot items, deletes the ones that are no longer present on disk, adds audit entries for all changed, new and deleted items,
@@ -1,11 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
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 System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -28,6 +29,31 @@ public sealed class Book : AggregateRoot<BookId>
/// </summary>
public WrittenContentMetadata Metadata { get; private set; }
/// <summary>
/// Gets the Id of the media library this book belongs to.
/// </summary>
public LibraryId LibraryId { get; private set; }
/// <summary>
/// Gets the file system path of the book.
/// </summary>
public string Path { get; private set; }
/// <summary>
/// Gets the status of the metadata enrichment of the book.
/// </summary>
public MetadataStatus MetadataStatus { get; private set; }
/// <summary>
/// Gets the date and time when the metadata of the book was last enriched, if applicable.
/// </summary>
public Optional<DateTime> LastMetadataUpdateUtc { get; private set; }
/// <summary>
/// Gets the name of the plugin that enriched the metadata of the book, if applicable.
/// </summary>
public Optional<string> MetadataProvider { get; private set; }
/// <summary>
/// Gets the format of the book (e.g., Hardcover, Paperback), if applicable.
/// </summary>
@@ -133,6 +159,8 @@ public sealed class Book : AggregateRoot<BookId>
/// <param name="ratings">The list of ratings for the book.</param>
private Book(
BookId id,
LibraryId libraryId,
string path,
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
@@ -154,7 +182,12 @@ public sealed class Book : AggregateRoot<BookId>
List<BookRating> ratings) : base(id)
{
Id = id;
LibraryId = libraryId;
Path = path;
Metadata = metadata;
MetadataStatus = MetadataStatus.Pending;
LastMetadataUpdateUtc = Optional<DateTime>.None();
MetadataProvider = Optional<string>.None();
Format = format;
Edition = edition;
VolumeNumber = volumeNumber;
@@ -178,6 +211,8 @@ public sealed class Book : AggregateRoot<BookId>
/// <summary>
/// Creates a new instance of the <see cref="Book"/> class.
/// </summary>
/// <param name="libraryId">The Id of the media library this book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="metadata">The metadata of the book.</param>
/// <param name="format">The optional format of the book (e.g., Hardcover, Paperback).</param>
/// <param name="edition">The optional edition of the book.</param>
@@ -199,6 +234,8 @@ public sealed class Book : AggregateRoot<BookId>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
LibraryId libraryId,
string path,
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
@@ -220,6 +257,8 @@ public sealed class Book : AggregateRoot<BookId>
// TODO: enforce invariants
return new Book(
BookId.CreateUnique(),
libraryId,
path,
metadata,
format,
edition,
@@ -246,6 +285,8 @@ public sealed class Book : AggregateRoot<BookId>
/// Creates a new instance of the <see cref="Book"/>, with a pre-existing <paramref name="id"/>.
/// </summary>
/// <param name="id">The object representing the unique identifier of the book.</param>
/// <param name="libraryId">The Id of the media library this book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="metadata">The metadata of the book.</param>
/// <param name="format">The optional format of the book (e.g., Hardcover, Paperback).</param>
/// <param name="edition">The optional edition of the book.</param>
@@ -270,6 +311,8 @@ public sealed class Book : AggregateRoot<BookId>
/// </returns>
public static ErrorOr<Book> Create(
BookId id,
LibraryId libraryId,
string path,
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
@@ -293,6 +336,8 @@ public sealed class Book : AggregateRoot<BookId>
// TODO: enforce invariants
return new Book(
id,
libraryId,
path,
metadata,
format,
edition,
@@ -314,4 +359,87 @@ public sealed class Book : AggregateRoot<BookId>
ratings
);
}
/// <summary>
/// Marks the metadata of the book as enriched by the provided <paramref name="providerName"/>.
/// </summary>
/// <param name="providerName">The name of the metadata provider that enriched the book.</param>
/// <param name="lastUpdateUtc">The date and time when the metadata of the book was enriched.</param>
public void MarkMetadataAsEnriched(string providerName, DateTime lastUpdateUtc)
{
MetadataProvider = providerName;
LastMetadataUpdateUtc = lastUpdateUtc;
MetadataStatus = MetadataStatus.Enriched;
}
/// <summary>
/// Marks the metadata enrichment of the book as failed.
/// </summary>
public void MarkMetadataAsFailed()
{
MetadataStatus = MetadataStatus.Failed;
}
/// <summary>
/// Applies the enriched <paramref name="metadata"/> and the related fields to the book, marking its metadata as enriched by the provided <paramref name="providerName"/>.
/// </summary>
/// <param name="metadata">The enriched metadata of the book.</param>
/// <param name="format">The optional format of the book.</param>
/// <param name="edition">The optional edition of the book.</param>
/// <param name="volumeNumber">The optional volume or book number in the series.</param>
/// <param name="series">The optional series the book is part of.</param>
/// <param name="asin">The optional ASIN of the book.</param>
/// <param name="goodreadsId">The optional Goodreads ID of the book.</param>
/// <param name="lccn">The optional LCCN of the book.</param>
/// <param name="oclcNumber">The optional OCLC Number of the book.</param>
/// <param name="openLibraryId">The optional Open Library ID of the book.</param>
/// <param name="libraryThingId">The optional LibraryThing ID of the book.</param>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes &amp; Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
/// <param name="providerName">The name of the metadata provider that enriched the book.</param>
/// <param name="lastUpdateUtc">The date and time when the metadata was enriched.</param>
public void ApplyEnrichedMetadata(
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
Optional<int> volumeNumber,
Optional<BookSeries> series,
Optional<string> asin,
Optional<string> goodreadsId,
Optional<string> lccn,
Optional<string> oclcNumber,
Optional<string> openLibraryId,
Optional<string> libraryThingId,
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
List<Isbn> isbns,
List<BookRating> ratings,
string providerName,
DateTime lastUpdateUtc)
{
Metadata = metadata;
Format = format;
Edition = edition;
VolumeNumber = volumeNumber;
Series = series;
ASIN = asin;
GoodreadsId = goodreadsId;
LCCN = lccn;
OCLCNumber = oclcNumber;
OpenLibraryId = openLibraryId;
LibraryThingId = libraryThingId;
GoogleBooksId = googleBooksId;
BarnesAndNobleId = barnesAndNobleId;
AppleBooksId = appleBooksId;
// replace the contents of the collections in place, preserving the readonly reference invariants of the aggregate
_isbns.Clear();
_isbns.AddRange(isbns);
_ratings.Clear();
_ratings.AddRange(ratings);
MarkMetadataAsEnriched(providerName, lastUpdateUtc);
}
}
@@ -0,0 +1,48 @@
#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.LibraryManagementBoundedContext.LibraryAggregate;
/// <summary>
/// Value Object for the Id of a media library, duplicated from the LibraryManagement bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class LibraryId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="LibraryId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private LibraryId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryId"/> class.
/// </summary>
/// <returns>The created <see cref="LibraryId"/> instance.</returns>
public static LibraryId CreateUnique()
{
return new LibraryId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="LibraryId"/> instance.</param>
/// <returns>The created <see cref="LibraryId"/> instance.</returns>
public static LibraryId Create(Guid value)
{
return new LibraryId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -5,7 +5,7 @@ using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.DTO.MediaContributors;
using System;
@@ -28,6 +28,8 @@ public class AddLibraryEndpointSummary : 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",
Metadata: new(
Title: "The Fellowship of the Ring",
OriginalTitle: "The Fellowship of the Ring",
@@ -179,6 +181,8 @@ public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest
Response(201, "The new book is returned.", example:
new BookResponse(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/the-fellowship-of-the-ring.epub",
Metadata: new(
Title: "The Fellowship of the Ring",
OriginalTitle: "The Fellowship of the Ring",
@@ -276,6 +280,9 @@ public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest
VoteCount: 87654
)
],
MetadataStatus: MetadataStatus.Pending,
LastMetadataUpdateUtc: default,
MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default
)
@@ -1,7 +1,9 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
@@ -17,7 +19,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// </summary>
public class GetBooksEndpoint : BaseEndpoint<EmptyRequest, IResult>
public class GetBooksEndpoint : BaseEndpoint<GetBooksRequest, IResult>
{
private readonly ISender _sender;
@@ -42,12 +44,13 @@ public class GetBooksEndpoint : BaseEndpoint<EmptyRequest, IResult>
}
/// <summary>
/// Gets the list of all books.
/// Gets the list of all the books of the media library identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the Id of the media library whose books are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(GetBooksRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<BookResponse>> result = await _sender.Send(new GetBooksQuery(), cancellationToken).ConfigureAwait(false);
ErrorOr<IEnumerable<BookResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -4,7 +4,7 @@ using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -31,6 +31,8 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
example: new BookResponse[] {
new(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/the-fellowship-of-the-ring.epub",
Metadata: new(
Title: "The Fellowship of the Ring",
OriginalTitle: "The Fellowship of the Ring",
@@ -128,11 +130,16 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
VoteCount: 87654
)
],
MetadataStatus: MetadataStatus.Pending,
LastMetadataUpdateUtc: default,
MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default
),
new(
Id: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
Path: "/books/the-two-towers.epub",
Metadata: new(
Title: "The Two Towers",
OriginalTitle: "The Two Towers",
@@ -229,6 +236,9 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
VoteCount: 90000
)
],
MetadataStatus: MetadataStatus.Pending,
LastMetadataUpdateUtc: default,
MetadataProvider: default,
CreatedOnUtc: DateTime.UtcNow,
UpdatedOnUtc: default
)
@@ -10,6 +10,11 @@ public enum BookRatingSource
/// </summary>
User,
/// <summary>
/// Rating sourced from Open Library.
/// </summary>
OpenLibrary,
/// <summary>
/// Ratings sourced from Goodreads, a social network for book readers that provides book recommendations and reviews.
/// </summary>
@@ -24,4 +29,4 @@ public enum BookRatingSource
/// Ratings from Google Books, a service that searches the full text of books and magazines that Google has scanned and converted to text.
/// </summary>
GoogleBooks,
}
}
@@ -18,6 +18,16 @@ public class BookModel
/// </summary>
public Guid Id { get; init; }
/// <summary>
/// Gets the Id of the media library this book belongs to.
/// </summary>
public Guid LibraryId { get; init; }
/// <summary>
/// Gets the file system path of the book.
/// </summary>
public string Path { get; init; } = null!;
/// <summary>
/// Gets the title of the media item.
/// </summary>
@@ -1,11 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
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 System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -36,6 +37,8 @@ public class BookJsonConverter : JsonConverter<Book>
JsonElement root = doc.RootElement;
Guid id = root.GetProperty("id").GetGuid();
Guid libraryId = root.GetProperty("libraryId").GetGuid();
string path = root.GetProperty("path").GetString()!;
DateTime createdOnUtc = root.GetProperty("createdOnUtc").GetDateTime();
WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata"));
BookFormat? format = null;
@@ -66,6 +69,8 @@ public class BookJsonConverter : JsonConverter<Book>
ErrorOr.ErrorOr<Book> createBookResult = Book.Create(
BookId.Create(id),
LibraryId.Create(libraryId),
path,
metadata,
Optional<BookFormat>.FromNullable(format),
Optional<string>.FromNullable(edition),
@@ -6,7 +6,7 @@ using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -192,6 +192,8 @@ public class AddBookRequestFixture
return new Faker<AddBookRequest>()
.CustomInstantiator(f => new AddBookRequest(
default,
default!,
default!,
default,
default,
@@ -204,12 +206,14 @@ public class AddBookRequestFixture
default,
default,
default,
default,
default,
default!,
default!,
default!,
default!,
default!
))
.RuleFor(x => x.LibraryId, _fixture.Create<Guid>())
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.Metadata, metadata)
.RuleFor(x => x.Format, _fixture.Create<BookFormat>())
.RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50)))
@@ -1,12 +1,13 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
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.Presentation.Api.IntegrationTests.Common.Setup;
using System;
using System.Collections.Generic;
@@ -37,6 +38,8 @@ public class DomainBookFixture
public Book CreateDomainBook()
{
return Book.Create(
LibraryId.Create(_fixture.Create<Guid>()),
_fixture.Create<string>(),
_fixture.Create<WrittenContentMetadata>(),
_fixture.Create<BookFormat>(),
_fixture.Create<Optional<string>>(),
@@ -5,7 +5,8 @@ using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.Books
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -62,6 +63,8 @@ public class AddBookRequestMappingTests
{
// Arrange
AddBookRequest request = new(
LibraryId: Guid.NewGuid(),
Path: "/books/test.epub",
Metadata: new WrittenContentMetadataDto(
Title: "Test Book",
OriginalTitle: null,
@@ -119,6 +122,8 @@ public class AddBookRequestMappingTests
{
// Arrange
AddBookRequest request = new(
LibraryId: Guid.NewGuid(),
Path: "/books/test.epub",
Metadata: new WrittenContentMetadataDto(
Title: "Test Book",
OriginalTitle: null,
@@ -7,7 +7,7 @@ using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -191,6 +191,8 @@ public class AddBookCommandFixture
return new Faker<AddBookCommand>()
.CustomInstantiator(f => new AddBookCommand(
default,
default!,
default!,
default,
default,
@@ -204,11 +206,13 @@ public class AddBookCommandFixture
default,
default,
default,
default,
default!,
default!,
default!,
default!
))
.RuleFor(x => x.LibraryId, _fixture.Create<Guid>())
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.Metadata, metadata)
.RuleFor(x => x.Format, _fixture.Create<BookFormat>())
.RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50)))
@@ -2,7 +2,7 @@
using AutoFixture;
using Bogus;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -192,6 +192,8 @@ public class AddBookRequestFixture
return new Faker<AddBookRequest>()
.CustomInstantiator(f => new AddBookRequest(
default,
default!,
default!,
default,
default,
@@ -204,12 +206,14 @@ public class AddBookRequestFixture
default,
default,
default,
default,
default,
default!,
default!,
default!,
default!,
default!
))
.RuleFor(x => x.LibraryId, _fixture.Create<Guid>())
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.Metadata, metadata)
.RuleFor(x => x.Format, _fixture.Create<BookFormat>())
.RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50)))
@@ -4,7 +4,7 @@ using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -105,6 +105,8 @@ public class BookEntityFixture
return new BookEntity
{
Id = Guid.NewGuid(),
LibraryId = Guid.NewGuid(),
Path = _faker.System.FilePath(),
Title = _faker.Random.String2(_faker.Random.Number(1, 255)),
OriginalTitle = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 255)) : null,
Description = _faker.Random.Bool() ? _faker.Random.String2(_faker.Random.Number(1, 2000)) : null,
@@ -1,13 +1,14 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
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 System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -42,6 +43,8 @@ public class BookFixture
public Book CreateDomainBook()
{
return Book.Create(
LibraryId.Create(_fixture.Create<Guid>()),
_fixture.Create<string>(),
_fixture.Create<WrittenContentMetadata>(),
_fixture.Create<BookFormat>(),
_fixture.Create<Optional<string>>(),
@@ -6,10 +6,11 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -188,4 +189,147 @@ public class BookRepositoryTests
Assert.Equal(2, retrievedBook.Genres.Count);
Assert.Equal(2, retrievedBook.ISBNs.Count);
}
[Fact]
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyBooksOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity bookOfLibrary = _bookEntityFixture.CreateBookModel();
bookOfLibrary.LibraryId = libraryId;
BookEntity bookOfAnotherLibrary = _bookEntityFixture.CreateBookModel();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
_mockContext.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<IEnumerable<BookEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsError);
BookEntity retrievedBook = Assert.Single(result.Value);
Assert.Equal(bookOfLibrary.Id, retrievedBook.Id);
}
[Fact]
public async Task GetByPathAsync_WhenBookExists_ShouldReturnTheBook()
{
// Arrange
BookEntity book = _bookEntityFixture.CreateBookModel();
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<BookEntity?> result = await _sut.GetByPathAsync(book.LibraryId, book.Path, CancellationToken.None);
// Assert
Assert.False(result.IsError);
Assert.Equal(book.Id, result.Value!.Id);
}
[Fact]
public async Task GetByPathAsync_WhenBookDoesNotExist_ShouldReturnNull()
{
// Arrange
BookEntity book = _bookEntityFixture.CreateBookModel();
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<BookEntity?> result = await _sut.GetByPathAsync(book.LibraryId, "/books/non-existent.epub", CancellationToken.None);
// Assert
Assert.False(result.IsError);
Assert.Null(result.Value);
}
[Fact]
public async Task GetBooksNeedingMetadataAsync_WhenCalled_ShouldReturnOnlyBooksWhoseMetadataIsNotEnriched()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity pendingBook = _bookEntityFixture.CreateBookModel();
pendingBook.LibraryId = libraryId;
pendingBook.Path = "/books/a.epub";
pendingBook.MetadataStatus = MetadataStatus.Pending;
BookEntity enrichedBook = _bookEntityFixture.CreateBookModel();
enrichedBook.LibraryId = libraryId;
enrichedBook.Path = "/books/b.epub";
enrichedBook.MetadataStatus = MetadataStatus.Enriched;
BookEntity failedBook = _bookEntityFixture.CreateBookModel();
failedBook.LibraryId = libraryId;
failedBook.Path = "/books/c.epub";
failedBook.MetadataStatus = MetadataStatus.Failed;
BookEntity bookOfAnotherLibrary = _bookEntityFixture.CreateBookModel();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Pending;
_mockContext.Books.AddRange(pendingBook, enrichedBook, failedBook, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<IReadOnlyList<BookEntity>> result = await _sut.GetBooksNeedingMetadataAsync(libraryId, null, 10, CancellationToken.None);
// Assert
Assert.False(result.IsError);
Assert.Equal(2, result.Value.Count);
Assert.Contains(result.Value, book => book.Id == pendingBook.Id);
Assert.Contains(result.Value, book => book.Id == failedBook.Id);
}
[Fact]
public async Task GetBooksNeedingMetadataAsync_WhenLastPathProvided_ShouldReturnBooksAfterIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity firstBook = _bookEntityFixture.CreateBookModel();
firstBook.LibraryId = libraryId;
firstBook.Path = "/books/a.epub";
BookEntity secondBook = _bookEntityFixture.CreateBookModel();
secondBook.LibraryId = libraryId;
secondBook.Path = "/books/b.epub";
_mockContext.Books.AddRange(firstBook, secondBook);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<IReadOnlyList<BookEntity>> result = await _sut.GetBooksNeedingMetadataAsync(libraryId, firstBook.Path, 10, CancellationToken.None);
// Assert
Assert.False(result.IsError);
BookEntity retrievedBook = Assert.Single(result.Value);
Assert.Equal(secondBook.Id, retrievedBook.Id);
}
[Fact]
public async Task UpdateAsync_WhenBookExists_ShouldUpdateItsScalarProperties()
{
// Arrange
BookEntity book = _bookEntityFixture.CreateBookModel();
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
book.Title = "Updated Title";
// Act
ErrorOr<Updated> result = await _sut.UpdateAsync(book, CancellationToken.None);
// Assert
Assert.False(result.IsError);
Assert.Equal(Result.Updated, result.Value);
BookEntity? retrievedBook = await _mockContext.Books.FindAsync(book.Id);
Assert.Equal("Updated Title", retrievedBook!.Title);
}
[Fact]
public async Task UpdateAsync_WhenBookDoesNotExist_ShouldReturnError()
{
// Arrange
BookEntity book = _bookEntityFixture.CreateBookModel();
// Act
ErrorOr<Updated> result = await _sut.UpdateAsync(book, CancellationToken.None);
// Assert
Assert.True(result.IsError);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
}
}
@@ -3,7 +3,7 @@ using AutoFixture;
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.DataAccess.UnitTests.Common.Setup;
using System;
using System.Collections.Generic;
@@ -48,6 +48,8 @@ public class BookEntityFixture
return new Faker<BookEntity>()
.RuleFor(x => x.Id, f => f.Random.Guid())
.RuleFor(x => x.LibraryId, f => f.Random.Guid())
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000)))
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.UnitTests.Core.Aggregates.BookLibraryAggregate.Fixtures;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.BookLibraryAggregate;
/// <summary>
/// Contains unit tests for the <see cref="Book"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookTests
{
[Fact]
public void Create_WhenCalledWithValidData_ShouldCreateBookWithPendingMetadataStatus()
{
// Act
Book book = BookFixture.CreateValidBook();
// Assert
Assert.NotNull(book);
Assert.Equal(MetadataStatus.Pending, book.MetadataStatus);
Assert.False(book.LastMetadataUpdateUtc.HasValue);
Assert.False(book.MetadataProvider.HasValue);
}
[Fact]
public void MarkMetadataAsEnriched_WhenCalled_ShouldUpdateStatusAndProvider()
{
// Arrange
Book book = BookFixture.CreateValidBook();
DateTime lastUpdateUtc = DateTime.UtcNow;
// Act
book.MarkMetadataAsEnriched("Goodreads", lastUpdateUtc);
// Assert
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
Assert.Equal("Goodreads", book.MetadataProvider.Value);
Assert.Equal(lastUpdateUtc, book.LastMetadataUpdateUtc.Value);
}
[Fact]
public void MarkMetadataAsFailed_WhenCalled_ShouldUpdateStatus()
{
// Arrange
Book book = BookFixture.CreateValidBook();
// Act
book.MarkMetadataAsFailed();
// Assert
Assert.Equal(MetadataStatus.Failed, book.MetadataStatus);
}
}
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
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 System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.Aggregates.BookLibraryAggregate.Fixtures;
/// <summary>
/// Fixture class for the <see cref="Book"/> domain entity.
/// </summary>
[ExcludeFromCodeCoverage]
public static class BookFixture
{
/// <summary>
/// Creates a valid book domain entity with random data.
/// </summary>
/// <returns>The created <see cref="Book"/> domain entity.</returns>
public static Book CreateValidBook()
{
ErrorOr<Book> bookResult = Book.Create(
LibraryId.Create(Guid.NewGuid()),
"/books/test.epub",
WrittenContentMetadata.Create(
"Test Title",
Optional<string>.None(),
Optional<string>.None(),
ReleaseInfo.Create(
Optional<DateOnly>.None(),
Optional<int>.None(),
Optional<DateOnly>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<string>.None()
).Value,
[],
[],
Optional<LanguageInfo>.None(),
Optional<LanguageInfo>.None(),
Optional<string>.None(),
Optional<int>.None()
).Value,
Optional<BookFormat>.None(),
Optional<string>.None(),
Optional<int>.None(),
Optional<BookSeries>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<string>.None(),
Optional<string>.None(),
[],
[],
[]
);
if (bookResult.IsError)
throw new InvalidOperationException("Failed to create a valid book in the test fixture.");
return bookResult.Value;
}
}